Compare commits

..
Author SHA1 Message Date
spoopyghosty0 b2103d9fb5 Game menu: Update with a newer version… for Linux apps and PC VR games (#161)
Follow-up to "Update with a newer APK…": Linux apps take their new AppImage/archive or folder (a file or a folder
picker, like the app was added), PC VR games their new game folder. pipeline.replace_linux_app / replace_rift_game
re-run the add path (add_linux_app(replace=) / add_rift_game(replace=)): the entry keeps its package (so the Steam
shortcut), name, artwork, tags, switches and the user's recipe; a folder keeps the program chosen before if it's still
there, else FramePort picks again (and asks, for ambiguous PC VR games). A name that looks like another app's is
allowed with a heads-up.

The entry gets a new source_id, recorded in the deployment's recipe at install (no agent change):
components.source_replaced shows the Frame copy (and a PC install, pc_outdated) as outdated until then. Such an
install also re-sends same-size files changed after the last install (installer.changed_since), since uploads
otherwise skip files the Frame has with the same size. The old PC VR folder is left out of later scans
(replaced_dirs). CLI: frameport new-version <game> <path> (APKs too). Docs: INSTALL.md.
2026-10-15 20:02:27 -04:00
26 changed files with 68 additions and 1453 deletions

No files matched your search

-19
View File
@@ -911,13 +911,6 @@ hide_space_warp / vk_hide_fdm / no Valve layers; FNAF HW (#135) "freeze" = first
on Zink (threads busy in zink/disk cache), not a hang; VR4 (#199) reporter's patch.203 OBB truncated. Upload benchmark
(`scripts/upload_bench.py`, #242): home Wi-Fi caps every method at ~11 MB/s; paramiko uses ~3x OpenSSH's CPU; Windows
OpenSSH refuses FramePort's key file (ACL "bad permissions") until its permissions are tightened.
**OpenSSH uploads (2026-10-15, #324/#242):** sftp escapes `* ? [` inside double quotes itself (and undoes it for
put's destination), so `native_upload.quote` escapes only `\\`/`"`; Win32 sftp turns every local backslash into `/`
(escapes too) → local paths go as `C:/…`. Logins: `Frame.auth` = the attempt that worked (app_key / user_key = a key
file from Settings → Installing → SSH keys, library `ssh.extra_keys`, CLI `frame ssh-keys` / agent / password).
OpenSSH strict (FramePort + Settings keys, IdentitiesOnly) unless auth was "agent"; a refused strict login retries
relaxed (+ private copies of ~/.ssh/id_{rsa,dsa,ecdsa,ed25519}: OpenSSH skips its defaults once any -i is given, + the
agent); `-v` key lines go into the error. FramePort doesn't add its key to the Frame for this. Windows-tested.
**Meta user id (GitHub #182, 2026-10-11):** OVRPort's platform loader (runtimes 3.4.3-23204ea and -aa54c3f) answers
`ovr_GetLoggedInUserID` (and two other callers) without a Meta account with a made-up id from a helper (`stp; mov x29,
sp; bl random; …; mov/movk x9 = 0x53444835ec580000 (6e18); add x0, x8, x9; ldp; ret`), kept only in memory → a new id
@@ -1163,15 +1156,3 @@ the unresolved eye distortion, and testing the release bundles on real Windows/m
(regenerates docs/PATCHES.md + site/src/data/patches.json, the site's id → anchor map; a test runs `--check`).
- Known-good backups of every working APK and the signing keys: `PATCHED/_known-good-2026-09-28/` (don't delete).
- Your development Frame: `frameport frame info` (remembered in `<user data>/frames.json`); SSH as `steamos@<frame>`.
Steam library scheduling (#305, agent v92): `install.steam_library` = now/later/off; agent `library_mode` persists it.
Automatic restarts also hold on a fresh local `frameport-app/gui.alive` (10 s; existing 12 h cap).
Later journals changes and installs steam.service ExecStartPre/ExecStartPost hooks to reapply after Steam's exit
writes and verify before clearing; preserve this ordering and avoid locking across systemctl's startup hooks.
Off Play (also pending Later Play) uses detached systemd-run launch.sh, with no shortcut/devkit registration;
Steam's per-game controller/overlay/Exit game integration is lost. Restart Steam now explicitly bypasses holds,
asks before ending a running game, and closes local FramePort/Desktop Mode. Purge removes the startup hook.
Hook hardening: both lines `-` + `/usr/bin/timeout -k 5 20`; ExecStartPost only `systemd-run --no-block`s the
verify (unit frameport-library-verify) so Steam's start never waits; drop-in removed once mode != later and nothing
pending (`drop_library_hooks_if_idle`). Steam = static user unit steam.service (Type=simple, Restart=always, 90 s).
+9 -282
View File
@@ -30,7 +30,6 @@ import os
import re
import shlex
import shutil
import signal
import struct
import subprocess
import sys
@@ -45,7 +44,7 @@ try:
except ImportError: # Windows: pc_revive loads this file for its VDF code only (GitHub #131)
fcntl = None
AGENT_VERSION = 92
AGENT_VERSION = 91
HOME = os.path.expanduser("~")
STEAM = os.path.join(HOME, ".local/share/Steam")
ANCHORS = os.path.join(HOME, "Applications/quest-frame")
@@ -1112,216 +1111,6 @@ def remove_shortcut(vdf_path, exe):
STATUS_FILE = os.path.join(HOME, ".local/share/frameport/shortcuts-status.json")
LIBRARY_MODE_FILE = os.path.join(HOME, ".local/share/frameport/library-mode.json")
PENDING_FILE = os.path.join(HOME, ".local/share/frameport/library-pending.json")
RESTART_REQUEST_FILE = os.path.join(HOME, ".local/share/frameport/restart-request.json")
def library_mode(args=None):
mode = (args or {}).get("mode")
if mode is None:
try:
mode = json.load(open(LIBRARY_MODE_FILE))["mode"]
except (OSError, ValueError, KeyError):
mode = "now"
if mode not in ("now", "later", "off"):
raise AgentError("Steam library mode must be now, later or off")
return mode
def cmd_library_mode(args):
mode = library_mode(args)
_write_json(LIBRARY_MODE_FILE, {"mode": mode})
os.makedirs(os.path.dirname(STATUS_FILE), exist_ok=True)
with open(STATUS_FILE + ".lock", "w") as lock:
fcntl.flock(lock, fcntl.LOCK_EX)
if mode == "off":
pending = pending_library()
pending["packages"] = []
_write_json(PENDING_FILE, pending)
drop_library_hooks_if_idle()
return {"mode": mode}
def pending_library():
try:
pending = json.load(open(PENDING_FILE))
except (OSError, ValueError):
pending = {}
if not isinstance(pending, dict):
pending = {}
pending["packages"] = [p for p in pending.get("packages") or [] if isinstance(p, str)]
pending["remove"] = [r for r in pending.get("remove") or [] if isinstance(r, dict)]
return pending
def queue_library(packages, remove):
# Serialize with the worker and Steam's startup hooks; persist before touching the live VDF.
os.makedirs(os.path.dirname(STATUS_FILE), exist_ok=True)
with open(STATUS_FILE + ".lock", "w") as lock:
fcntl.flock(lock, fcntl.LOCK_EX)
return _queue_library(packages, remove)
def _queue_library(packages, remove):
"""Caller holds the shortcut lock."""
pending = pending_library()
pending["packages"] = sorted(set(pending["packages"]) | set(packages))
pending["remove"].extend(remove)
_write_json(PENDING_FILE, pending)
result = {"state": "pending", **pending, "added": [], "errors": []}
for user in library_users():
update_library(user, packages, result)
_write_json(STATUS_FILE, result)
return result
LIBRARY_HOOK_DIR = os.path.join(HOME, ".config/systemd/user/steam.service.d")
LIBRARY_HOOK = os.path.join(LIBRARY_HOOK_DIR, "frameport-library.conf")
TIMEOUT_BIN = "/usr/bin/timeout" # coreutils; present on SteamOS (checked on the Frame, 2026-10-16)
SYSTEMD_RUN_BIN = "/usr/bin/systemd-run"
LIBRARY_HOOK_SECONDS = 20 # steam.service's start timeout is 90 s: a stuck hook must never get near it
LIBRARY_VERIFY_UNIT = "frameport-library-verify"
def _unit_quote(value):
"""One argument of a systemd Exec= line: quoted, with the specifier (%) and variable ($) characters escaped."""
return '"' + value.replace("\\", "\\\\").replace('"', '\\"').replace("%", "%%").replace("$", "$$") + '"'
def library_hooks_text(python=None, agent=None, timeout_bin=None):
"""steam.service drop-in for the `later` mode. Both hooks start with '-' (a failure never fails Steam's start)
and run under timeout(1) (systemd's '-' ignores exit codes, not a hook that hangs until the unit's start
timeout), so a missing interpreter/agent (exit 127/2) or a hang can't keep Steam from starting. The
pre-start hook rewrites shortcuts.vdf before Steam reads it; the post-start check (it waits for Steam and may
register devkit entries) runs as its own transient unit, so Steam's start never waits for it."""
python = python or sys.executable
agent = agent or os.path.abspath(__file__)
timeout_bin = TIMEOUT_BIN if timeout_bin is None else timeout_bin
wrap = f"{timeout_bin} -k 5 {LIBRARY_HOOK_SECONDS} " if timeout_bin else ""
command = _unit_quote(python) + " " + _unit_quote(agent)
return ("# Written by FramePort (Steam library: \"later\"); removed again when nothing waits for Steam's start.\n"
"[Service]\n"
f"ExecStartPre=-{wrap}{command} library_pending\n"
f"ExecStartPost=-{wrap}{SYSTEMD_RUN_BIN} --user --collect --quiet --no-block "
f"--unit={LIBRARY_VERIFY_UNIT} --property=RuntimeMaxSec=300 {command} library_pending_verify\n")
def ensure_library_hooks():
"""SteamOS runs Steam as the user unit steam.service (Type=simple, Restart=always, TimeoutStartSec 90 s).
Apply AFTER its exit writes and BEFORE its next start; keep the journal until the post-start verification
succeeds, including across reboots/crashes."""
text = library_hooks_text(timeout_bin=TIMEOUT_BIN if os.access(TIMEOUT_BIN, os.X_OK) else "")
try:
if open(LIBRARY_HOOK).read() == text:
return
except OSError:
pass
os.makedirs(LIBRARY_HOOK_DIR, exist_ok=True)
with open(LIBRARY_HOOK + ".tmp", "w") as f:
f.write(text)
os.replace(LIBRARY_HOOK + ".tmp", LIBRARY_HOOK)
if run(["systemctl", "--user", "daemon-reload"]).returncode:
raise AgentError("Could not enable Steam library startup hooks")
def remove_library_hooks():
"""Remove the steam.service drop-in (mode switched away from `later` with nothing pending, purge).
Returns whether there was one."""
if not os.path.exists(LIBRARY_HOOK):
return False
try:
os.remove(LIBRARY_HOOK)
except FileNotFoundError:
return False
try:
os.rmdir(LIBRARY_HOOK_DIR) # only when empty: the user's own drop-ins (extra_args.conf) stay
except OSError:
pass
run(["systemctl", "--user", "daemon-reload"])
return True
def drop_library_hooks_if_idle():
"""The drop-in only stays while the `later` mode is on or something still waits for Steam's next start."""
pending = pending_library()
if library_mode() != "later" and not pending["packages"] and not pending["remove"]:
return remove_library_hooks()
return False
def cmd_library_pending(args):
os.makedirs(os.path.dirname(STATUS_FILE), exist_ok=True)
with open(STATUS_FILE + ".lock", "w") as lock:
try:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
return {"worker_active": True} # that worker writes before start and verifies afterward
pending = pending_library()
result = {"added": [], "errors": []}
if not pending["packages"] and not pending["remove"]:
return result # every Steam start runs this: leave shortcuts.vdf alone when nothing waits
# An uninstall queued after an install wins; never resurrect a deleted deployment.
packages = [p for p in pending["packages"] if deployment(p)]
for user in steam_users():
remove_from_library(user, pending["remove"], result)
for user in library_users():
update_library(user, packages, result)
pending["errors"] = result["errors"]
_write_json(PENDING_FILE, pending)
return result
def cmd_library_pending_verify(args):
os.makedirs(os.path.dirname(STATUS_FILE), exist_ok=True)
with open(STATUS_FILE + ".lock", "w") as lock:
try:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
return {"worker_active": True} # that worker writes before start and verifies afterward
pending = pending_library()
packages = [p for p in pending["packages"] if deployment(p)]
result = {"state": "done", "added": [], "errors": list(pending.get("errors", []))}
if not packages and not pending["remove"]:
if pending["packages"]: # only uninstalled games were left
_write_json(PENDING_FILE, {"packages": [], "remove": []})
drop_library_hooks_if_idle()
return result
for pkg in shortcuts_lost(library_users(), packages):
add_devkit_entry(pkg, result)
if not result["errors"]:
_write_json(PENDING_FILE, {"packages": [], "remove": []})
drop_library_hooks_if_idle()
_write_json(STATUS_FILE, result)
return result
def frameport_running():
"""A local GUI heartbeat is refreshed every second; crashed/closed windows expire in ten seconds."""
data = os.environ.get("XDG_DATA_HOME", os.path.join(HOME, ".local/share"))
try:
age = time.time() - os.path.getmtime(os.path.join(data, "frameport-app/gui.alive"))
return 0 <= age < 10
except OSError:
return False
def restart_hold():
return "game" if game_running() else "desktop" if desktop_mode() else "frameport" if frameport_running() else None
def cmd_restart_steam(args):
if game_running() and not args.get("confirm"):
return {"confirmation_required": True}
status = cmd_shortcut_status({})
if status.get("state") == "waiting" and time.time() - float(status.get("started") or 0) < 60:
# Wake the worker already holding the lock; a second worker would wait behind the local GUI hold.
_write_json(RESTART_REQUEST_FILE, {"requested": time.time()})
return {"started": True, "waiting_worker": True}
return cmd_shortcuts({"packages": pending_library()["packages"], "restart_now": True,
"remove": pending_library()["remove"], "mode": "now"})
def cmd_shortcuts(args):
"""Add library entries (+ grid artwork) for installed games. Steam must be closed while shortcuts.vdf is
rewritten, so the work runs in a detached systemd unit (terminals/SSH sessions started from Steam live in
@@ -1329,27 +1118,18 @@ def cmd_shortcuts(args):
packages = [check_pkg(p) for p in args.get("packages", [])]
remove = [r for r in args.get("remove", [])
if isinstance(r, dict) and str(r.get("exe", "")).startswith('"' + ANCHORS)]
mode = library_mode(args)
if mode == "off" and not remove:
return {"state": "done", "disabled": True, "added": [], "errors": []}
if mode == "off":
packages = []
if mode == "later":
ensure_library_hooks()
return queue_library(packages, remove)
if not packages and not remove and not args.get("restart_now"):
if not packages and not remove:
return {"started": False}
current = cmd_shortcut_status({})
alive = time.time() - float(current.get("started") or 0) < 60 # a waiting worker rewrites its status every 10 s
if (not args.get("restart_now") and current.get("state") == "waiting" and alive
and set(packages) <= set(current.get("packages") or []) and not remove):
if current.get("state") == "waiting" and alive and set(packages) <= set(current.get("packages") or []) \
and not remove:
return {"started": False, "waiting": True} # the update for these games already waits (Gaming Mode / game)
os.makedirs(os.path.dirname(STATUS_FILE), exist_ok=True)
with open(STATUS_FILE, "w") as f:
json.dump({"state": "running", "packages": packages, "started": time.time()}, f)
unit = f"frameport-shortcuts-{int(time.time())}"
payload = json.dumps({"packages": packages, "remove": remove, "restart": args.get("restart", True),
"restart_now": bool(args.get("restart_now"))})
payload = json.dumps({"packages": packages, "remove": remove, "restart": args.get("restart", True)})
run(["systemd-run", "--user", "--collect", "--quiet", f"--unit={unit}", "--setenv=HOME=" + HOME,
sys.executable, os.path.abspath(__file__), "_shortcuts_worker", payload])
return {"started": True, "unit": unit}
@@ -1426,14 +1206,7 @@ def shortcuts_worker(payload):
os.makedirs(os.path.dirname(STATUS_FILE), exist_ok=True)
with open(STATUS_FILE + ".lock", "w") as lock:
if json.loads(payload).get("restart_now"):
try:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
_write_json(RESTART_REQUEST_FILE, {"requested": time.time()})
return # wake an existing hold, rather than queueing another restart behind it
else:
fcntl.flock(lock, fcntl.LOCK_EX)
fcntl.flock(lock, fcntl.LOCK_EX)
_shortcuts_worker(payload)
@@ -1457,7 +1230,7 @@ def _shortcuts_worker(payload):
copy_grid_art(pkg, appid)
args["packages"] = [p for p in args["packages"] if p not in devkit]
result["devkit"] = devkit
if not args.get("restart_now") and not args.get("remove") and not library_changes(users, args["packages"]):
if not args.get("remove") and not library_changes(users, args["packages"]):
# nothing to change in shortcuts.vdf (e.g. a reinstall): only the artwork, no Steam restart
for user in users:
update_library(user, args["packages"], result, shortcuts=False)
@@ -1467,25 +1240,8 @@ def _shortcuts_worker(payload):
json.dump(result, f)
return
deadline = time.time() + 12 * 3600
while not args.get("restart_now") and time.time() < deadline:
try:
requested = json.load(open(RESTART_REQUEST_FILE))["requested"]
if 0 <= time.time() - requested < 60:
os.remove(RESTART_REQUEST_FILE)
break
except (OSError, ValueError, KeyError):
pass
mode = library_mode()
if mode == "later":
ensure_library_hooks()
_queue_library(args["packages"], args.get("remove", []))
return
if mode == "off" and not args.get("remove"):
_write_json(STATUS_FILE, {"state": "done", "disabled": True, "added": [], "errors": []})
return
if mode == "off":
args["packages"] = []
reason = restart_hold()
while time.time() < deadline: # restarting Steam would end the game being played, or Desktop Mode
reason = "game" if game_running() else "desktop" if desktop_mode() else None
if not reason:
break
with open(STATUS_FILE, "w") as f:
@@ -1496,9 +1252,6 @@ def _shortcuts_worker(payload):
service = stop_steam()
except AgentError:
raise AgentError("Steam did not close; library not modified") from None
pending = pending_library()
args["packages"] = sorted(set(args["packages"]) | {p for p in pending["packages"] if deployment(p)})
args.setdefault("remove", []).extend(pending["remove"])
for user in steam_users(): # uninstalled games leave every account's library
remove_from_library(user, args.get("remove", []), result)
for user in users:
@@ -1519,13 +1272,6 @@ def _shortcuts_worker(payload):
result["state"] = "failed"
result["errors"].append(str(exc))
run(["systemctl", "--user", "start", "steam.service"])
if result["state"] == "done" and not result["errors"]:
_write_json(PENDING_FILE, {"packages": [], "remove": []})
drop_library_hooks_if_idle()
try:
os.remove(RESTART_REQUEST_FILE)
except OSError:
pass
result["finished"] = time.time()
with open(STATUS_FILE, "w") as f:
json.dump(result, f)
@@ -2037,18 +1783,6 @@ def cmd_launch(args):
check_base_present(dep["base"], dep.get("title") or pkg)
if run(["pgrep", "-x", "steam"]).returncode != 0:
raise AgentError("Steam isn't running on the Frame")
mode = library_mode(args)
if mode == "off" or (mode == "later" and pkg in pending_library()["packages"]):
# Detached from SSH/FramePort. The launcher keeps Lepton/Proton's environment; SteamVR must be running.
unit = f"frameport-play-{dep['appid']}"
if game_is_running(dep) or run(["systemctl", "--user", "is-active", "--quiet", unit]).returncode == 0:
raise AgentError("the game is already running") # (or its launcher is still starting it)
run(["systemctl", "--user", "reset-failed", unit]) # a failed earlier start would block the unit name
p = run(["systemd-run", "--user", "--collect", "--quiet", f"--unit={unit}",
os.path.join(ANCHORS, pkg, "launch.sh")])
if p.returncode:
raise AgentError("could not start the launcher: " + p.stderr[-300:])
return {"package": pkg, "title": dep.get("title"), "via": "direct"}
devkit = devkit_gameid(pkg)
appid = devkit_appid(devkit) if devkit else None # this Frame needed the fallback entry before: use it
if devkit and not appid:
@@ -6822,11 +6556,6 @@ def purge_worker(payload):
result["removed"].append(VR_OVERLAY_UNIT_PATH)
except Exception as exc: # noqa: BLE001
result["errors"].append(f"overlay autostart service: {exc}")
try:
if remove_library_hooks():
result["removed"].append(LIBRARY_HOOK)
except Exception as exc: # noqa: BLE001
result["errors"].append(f"Steam library hook: {exc}")
try:
service = stop_steam()
except AgentError as exc:
@@ -8223,8 +7952,6 @@ def main():
if len(sys.argv) != 2 or sys.argv[1] not in COMMANDS:
print(json.dumps({"ok": False, "error": f"usage: frameport_agent.py <{'|'.join(sorted(COMMANDS))}>"}))
return 2
if sys.argv[1] == "library_pending" and hasattr(signal, "alarm"):
signal.alarm(LIBRARY_HOOK_SECONDS + 5) # Steam's ExecStartPre: own deadline too, should timeout(1) be missing
raw = sys.stdin.read() if not sys.stdin.isatty() else ""
try:
args = json.loads(raw) if raw.strip() else {}
+1 -1
View File
@@ -1,5 +1,5 @@
package: com.asg.clockworkdev
title: The Last Clockwinder
title: Clockwork
status: works
tested_version: '1.29'
engine: Unity
-18
View File
@@ -1,18 +0,0 @@
package: org.crisiszone.vr
title: Crisis Zone VR
status: works
notes: Played the beginning of the first mission without issues.
tested_version: 0.1.4
engine: Other
xr: OpenXR
frame:
- frame.sdl_clipboard
verified:
date: '2026-10-15'
known_good_sha256: 747d1e6613ae443ef03e509b509e4ec89039eec1aecf3689643db4057e53266a
app: 1.2.1.dev433
overport_cli: 1.2.5
frame_build: '20261007.6125817'
agent: 91
issue: 331
source_hint: CrisisZoneVR-v0.1.4-quest3
+6 -6
View File
@@ -1,9 +1,9 @@
package: xyz.TheAviary.Vermillion
title: Vermillion
status: works
notes: "The canvas used to hide the hand and brush while painting (the Frame draws the game's canvas layer in front
of everything); the recipe makes the game draw canvases in the scene instead (fix found by Klownicle, GitHub #200).
Confirmed in the headset by Klownicle."
status: issues
notes: Runs. The canvas used to hide the hand and brush while painting (the Frame draws the game's canvas layer in
front of everything); the recipe makes the game draw canvases in the scene instead (fix found by Klownicle, GitHub
#200). Not yet confirmed in the headset with this patch.
tested_version: 1.7.2
engine: Unity
xr: OpenXR
@@ -16,10 +16,10 @@ adapter:
haptic_fix: 1
scene_emul: 1
verified:
date: '2026-10-15'
date: '2026-10-11'
app: 1.0.1
frame_build: '20261007.6125817'
agent: 79
issue: 200
updated: '2026-10-15'
updated: '2026-10-12'
source_hint: Vermillion - VR Painting
-30
View File
@@ -421,33 +421,3 @@ sighting, command lines checked once per process, render fds cached (rescanned e
game processes without one), temperatures every 2 s, the CPU-cluster power rails every 5 s and the battery gauge every
2-10 s, the stream measured ~10-13 ms CPU per 1 s tick on the device (idle clocks; idle or with 4XVR running) = about
1 % of one core, ~0.15 % of the whole CPU. The I2C sensors (power monitors, battery gauge) are the slowest reads.
## Steam library scheduling
Agent v92 holds automatic shortcut restarts while the local app's
`~/.local/share/frameport-app/gui.alive` heartbeat is under ten seconds old, as well as while a game or Desktop Mode
is open. Closed/crashed GUIs expire; the existing twelve-hour hold limit still applies.
`library_mode` accepts `now` (default), `later`, and `off`; FramePort stores its preference as
`install.steam_library`. Later writes shortcuts and journals packages/removals in
`~/.local/share/frameport/library-pending.json`. Steam rewrites shortcuts.vdf on exit, so a user drop-in
`~/.config/systemd/user/steam.service.d/frameport-library.conf` reapplies the journal in ExecStartPre, after the
previous session has exited. ExecStartPost verifies the entries and uses the existing live devkit fallback if Steam
removed them. The journal is cleared only after success, and survives agent/app exit and reboot. The hooks share the
shortcut worker lock; an active worker performs its own write/verification instead. Both hook lines start with
`-` and run under `/usr/bin/timeout -k 5 20` (present on SteamOS; `-` ignores exit codes, including 127 for a missing
interpreter or agent, but not a hook that hangs until the unit's 90 s start timeout); ExecStartPre also has its own
SIGALRM deadline. ExecStartPost only starts the verification as the transient unit `frameport-library-verify`
(`--no-block`, RuntimeMaxSec 300), so Steam's start never waits for its Steam/devkit waits. The pre hook leaves
shortcuts.vdf alone when nothing is pending. The drop-in is removed (and the user manager reloaded) as soon as the
mode isn't `later` and nothing is pending, and by purge; an otherwise empty `steam.service.d` goes with it.
SteamOS 0.3.0 facts (checked 2026-10-16): Steam is the static user unit `/usr/lib/systemd/user/steam.service`
(Type=simple, Restart=always, TimeoutStartSec 90 s, its own `-` ExecStartPre lines; `extra_args.conf` drop-ins are
Valve's documented way to extend it), systemd 257; no user drop-ins exist by default.
This automatic application targets SteamOS's `steam.service`; if Steam is started outside that service, use
FramePort's Restart Steam now action to apply the journal safely.
Off skips new shortcuts (existing entries remain). Play in Off, and Play for a pending Later entry, starts launch.sh
in a detached user systemd unit, just as launch tests do, without adding a devkit entry. Steam/SteamVR must already
be running. This loses Steam's per-game overlay/controller setup and Exit game integration; use FramePort Monitor
to stop the game. This direct path has unit coverage; headset input/visual behaviour needs device validation.
+2 -3
View File
@@ -31,11 +31,11 @@ Generated from [catalog/games](../catalog/games) by `scripts/compat_list.py`.
| BONELAB | Quest | ✅ Works | |
| Carve Snowboarding | Quest | ✅ Works | |
| Caves | Quest | ✅ Works | |
| Clockwork | Quest | ✅ Works | |
| COMPOUND | Quest | ✅ Works | |
| Cook-Out | Quest | ✅ Works | |
| Cosmodread | Quest | ✅ Works | |
| Creed | Quest | ✅ Works | |
| Crisis Zone VR | Quest | ✅ Works | |
| cubism | Quest | ✅ Works | |
| Dance Central | Quest | ✅ Works | |
| Deep Cuts | Quest | ✅ Works | |
@@ -129,7 +129,6 @@ Generated from [catalog/games](../catalog/games) by `scripts/compat_list.py`.
| TetrisEffect | Quest | ✅ Works | |
| The Boys VR | Quest | ✅ Works | |
| The Climb 2 | Quest | ✅ Works | |
| The Last Clockwinder | Quest | ✅ Works | |
| The Room VR | Quest | ✅ Works | |
| The Tale of Onogoro | Quest | ✅ Works | |
| Time Crisis II VR (Test) | Quest | ✅ Works | |
@@ -144,7 +143,6 @@ Generated from [catalog/games](../catalog/games) by `scripts/compat_list.py`.
| Vader Immortal: Episode III | Quest | ✅ Works | |
| Vampire Survivors | Quest | ✅ Works | |
| Vendetta Forever | Quest | ✅ Works | |
| Vermillion | Quest | ✅ Works | |
| VR HOT Quest | Quest | ✅ Works | |
| VR4 | Quest | ✅ Works | |
| Walkabout Mini Golf | Quest | ✅ Works | |
@@ -176,6 +174,7 @@ Generated from [catalog/games](../catalog/games) by `scripts/compat_list.py`.
| The Light Brigade | Quest | ⚠️ Works with issues | Judder in weapons |
| The Thrill Of The Fight | Quest | ⚠️ Works with issues | Right eye doesn't draw the opponent or the referee. |
| Time Stall | Quest | ⚠️ Works with issues | Both eyes distort during movement (unresolved). |
| Vermillion | Quest | ⚠️ Works with issues | Runs. |
| WiiCompiled VR | Quest | ⚠️ Works with issues | To add a game: in FramePort's Files tab, upload your .wcgame file to this game's storage, folder Android/data/org.wiicompiled.quest/files/WiiCompiledOpenXRVR… |
| Deadly Delivery | Quest | ❌ Doesn't run | Quits after Meta's entitlement check fails: it needs Meta's online services. |
| Espire 1: VR Operative (Quest Edition) | Quest | ❌ Doesn't run | Mesa GL driver crash during texture upload. |
+2 -18
View File
@@ -86,24 +86,8 @@ FramePort can run on the Frame itself, without a PC:
2. In Desktop Mode, download `FramePort-linux-arm64.tar.gz`, unpack it (`tar xzf FramePort-linux-arm64.tar.gz`) and
start `FramePort/FramePort`.
With the default **Steam library: Now**, games appear after you close FramePort and return to Gaming Mode.
FramePort also waits while its window is open in Gaming Mode, so you can install several games in one session.
Please report anything odd with **Report a problem…**.
Settings → Installing → **Steam library** controls future installs:
- **Now** (default): restart Steam after adding shortcuts, waiting while a game, Desktop Mode, or FramePort's local
window is open (up to 12 hours). Unchanged shortcuts need no restart.
- **Later**: save shortcuts without restarting Steam. Keep installing; changes are applied at the next Steam
service start, including after a reboot. **Restart Steam now** applies them immediately. It closes Desktop Mode
and FramePort running on the Frame, and asks again if a game is running.
- **Off**: skip new Steam shortcuts; existing entries stay. FramePort's **Play** runs the installed launcher directly.
Steam and SteamVR must already be running. Steam's per-game overlay, controller setup, and Exit game integration
are unavailable; stop the game from FramePort's Monitor. Pending games in Later also use this direct Play path.
CLI: `frameport frame steam-library now|later|off` saves the setting and applies it to the connected Frame.
`frameport frame restart-steam` applies pending entries now; `--yes` confirms ending a running game.
These settings concern game shortcuts; installing a missing Steam runtime such as Proton can still require a restart.
Games appear in the Steam library when you go back to Gaming Mode. Please report anything odd with **Report a
problem…**.
## Installing games
+4 -4
View File
@@ -71,7 +71,7 @@ Link to an entry with its id, dots replaced by dashes: `PATCHES.md#frame-unity_t
| [Platform compat (ovrMessageType_ToString)](#frame-ovrplatformcompat) | `frame.ovrplatformcompat` | Steam Frame patches | default |
| [Stub missing Meta platform functions](#frame-ovrstubs) | `frame.ovrstubs` | Steam Frame patches | default |
| [Unpaired pointer-authentication checks](#frame-pac_hints) | `frame.pac_hints` | Steam Frame patches | 1 |
| [SDL apps: start without a clipboard service](#frame-sdl_clipboard) | `frame.sdl_clipboard` | Steam Frame patches | 5 |
| [SDL apps: start without a clipboard service](#frame-sdl_clipboard) | `frame.sdl_clipboard` | Steam Frame patches | 4 |
| [Stress Level Zero: let Unity start Vulkan itself](#frame-slz_vulkan_hooks) | `frame.slz_vulkan_hooks` | Steam Frame patches | 1 |
| [Start straight in VR (skip the 2D launcher)](#frame-start_activity) | `frame.start_activity` | Steam Frame patches | |
| [Allow swapchains larger than 4096 px](#frame-swapchain_limit) | `frame.swapchain_limit` | Steam Frame patches | default |
@@ -838,7 +838,7 @@ Lets SDL and LÖVE games start on the Frame (they'd crash looking for a clipboar
- `frame.sdl_clipboard` · also for 2D apps
- **Changes:** Changes the APK (a rebuild and reinstall apply it).
- **Suggested (on):** SDL app: it crashes at start in Lepton, which has no clipboard service.
- **Catalog games (5):** Crisis Zone VR, Majora's Mask VR, Time Crisis II VR (Test), Time Crisis VR (Experimental), WiiCompiled VR.
- **Catalog games (4):** Majora's Mask VR, Time Crisis II VR (Test), Time Crisis VR (Experimental), WiiCompiled VR.
- **Suggested by launch-test signatures:**
- `sdl-no-clipboard` (fatal): The app crashed at start because the Frame's Android has no clipboard.
- **Source:** [patches/frame/sdl_clipboard.py](../src/frameport/patches/frame/sdl_clipboard.py)
@@ -904,7 +904,7 @@ Stops a gray or frozen screen in Unity games that turn on anti-aliasing while ru
- `frame.unity_gl_shim`
- **Changes:** Changes the APK (a rebuild and reinstall apply it).
- **Suggested (on):** Unity GLES game that may switch to MSAA at runtime: hide multisampled render-to-texture, which crashes the Frame's GL driver (for example The Room VR).
- **Catalog games (23):** Audica, BattleSisters, Beat Saber, COMPOUND, Cosmodread, Down the Rabbit Hole, Drunkn Bar Fight, End Space and 15 more.
- **Catalog games (23):** Audica, BattleSisters, Beat Saber, Clockwork, COMPOUND, Cosmodread, Down the Rabbit Hole, Drunkn Bar Fight and 15 more.
- **Suggested by launch-test signatures:**
- `unreal-msrtt-crash` (fatal): The game's graphics crashed a few seconds after start.
- **Source:** [patches/frame/vrapi_bridge.py](../src/frameport/patches/frame/vrapi_bridge.py)
@@ -973,7 +973,7 @@ Keeps a smoothing setting off that the game turns on itself and that can freeze
- `frame.unity_runtime_msaa_off` · revision 2
- **Changes:** Changes the APK (a rebuild and reinstall apply it).
- **Suggested (on):** GLES Unity game whose OVRManager turns 4x MSAA on at runtime: multisampled render-to-texture can hang the Frame's GPU.
- **Catalog games (28):** Audica, BattleSisters, Beat Saber, COMPOUND, Cosmodread, Down the Rabbit Hole, Drunkn Bar Fight, End Space and 20 more.
- **Catalog games (28):** Audica, BattleSisters, Beat Saber, Clockwork, COMPOUND, Cosmodread, Down the Rabbit Hole, Drunkn Bar Fight and 20 more.
- **Suggested by launch-test signatures:**
- `unity-render-crash` (fatal): The game's graphics crashed, so the picture freezes or stays gray.
- `unity-runtime-msaa` (info): The game turns MSAA on at runtime, which can hang the Frame's GPU.
-2
View File
@@ -63,8 +63,6 @@ version is `catalog/triage.yaml` (used by `frameport test` / the Job screen); ke
| Un-cracked Oculus PC VR game: "Initializing OVR session" then exits / signature check on the runtime | Revive's hooks don't install on Proton-arm64; the Oculus shim rejects the unsigned Revive runtime | Not runnable on the Frame without the repack's crack extracted (not done by FramePort); use the PC version |
| PC VR game: `Failed to initialize Oculus API (-3001)` / `Unable to load LibOVRRT DLL` | Revive's LoadLibrary hook doesn't work under Proton arm64 (ARM64EC kernelbase); the game's LibOVR shim finds no runtime DLL | Symlink `LibOVRRT64_1.dll` → Revive's DLL in the prefix's system32 (manual so far) → then -3021 (runtime signature check; open) |
| Uploads to the Frame are slow | The link, storage or transfer backend can limit throughput | Check the job's "Transfer link"; try the Frame's hotspot or USB cable. Large install files prefer system OpenSSH SFTP, retaining paired-host checks and `.part` resume; unavailable or failed native uploads fall back to Paramiko. The log names the backend. Settings → Installing → Parallel uploads accepts 1–8 (default 3; saved preferences are preserved). More is not always faster. Measure the production path with `scripts/upload_bench.py --methods app-files-3 --check-resume` (three repetitions, checksum verification) |
| Log: `OpenSSH SFTP failed (255): … Permission denied (publickey,password)`, then Paramiko | OpenSSH offered keys the Frame doesn't authorize (GitHub #242) | The log lists the keys OpenSSH offered (`Offering public key`) and its warnings. A connection that logged in with the PC's own keys/agent makes OpenSSH use them too (copies of `~/.ssh/id_*` + the agent); a refused FramePort key is retried that way once. A Frame that accepts only another key file: Settings → Installing → SSH keys (CLI `frameport frame ssh-keys --add <file>`); passphrase keys go through the SSH agent |
| Log: `OpenSSH SFTP failed (1): stat C://…/[…: No such file or directory` | sftp got glob escapes inside its quotes (GitHub #324, fixed): `[` in a local folder name | Update FramePort; the native_upload `quote()` passes only `\\` and `\"` escapes, Windows paths with `/` |
| PC VR game exits right away: `Unhandled Exception: 0xc06d007e` (after `FOnlineSubsystemOculus::InitWithWindowsPlatform`) | Delay-loaded `LibOVRPlatform64_1.dll` (Oculus Platform SDK, installed with the Oculus app) is missing | None on the Frame (entitlement check; FramePort doesn't replace it). PC mode with the Oculus app |
| Unity PC VR game (Oculus + SteamVR build: `OVRPlugin.dll` and `openvr_api.dll` in `<Name>_Data/Plugins`) opens a window and quits after ~20 s; no VR Vulkan instance after the game's DXVK device in launch.log; Unity log (`unity log … Player.log`, agent v67): `OpenVR failed initialization` / `Initialization of device … failed` | Unity's built-in VR tries its SDKs in list order (Oculus first) unless `-vrmode` picks one; a catalog recipe verified with another build of the game (for example SUPERHOT VR's OpenXR build, GitHub #105) used to drop the build's own arguments | `pcvr.launch_args` = `-vrmode OpenVR` (detected for such builds; kept when the catalog's `xr` differs from the build's). A game's Electron launcher next to it (SHVR.exe) is ranked below the game |
| Unreal PC VR game opens the crash reporter instead of closing | UE starts CrashReportClient.exe on a crash | `pcvr.no_crash_reporter` (default for Unreal Rift games): `-nocrashreports` + CrashReportClient.exe renamed `.disabled` in the Frame copy |
Binary file not shown.

Before

Width:  |  Height:  |  Size: 421 KiB

After

Width:  |  Height:  |  Size: 415 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 663 KiB

After

Width:  |  Height:  |  Size: 668 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 99 KiB

After

Width:  |  Height:  |  Size: 103 KiB

+1 -2
View File
@@ -137,8 +137,7 @@ def main() -> int:
("monitor", lambda a: a.go("monitor")), ("monitor-details", open_monitor_details),
("tools", lambda a: a.go("settings")),
# the index on the left: "This PC" scrolls the page there
("settings-index", lambda a: a.page.run_task(a.settings_view.show_section, "pc")),
("settings-installing", lambda a: a.page.run_task(a.settings_view.show_section, "installing"))]
("settings-index", lambda a: a.page.run_task(a.settings_view.show_section, "pc"))]
if game:
steps.insert(1, ("game", lambda a: a.open_game(game)))
steps.insert(2, ("game-customize", lambda a: a.open_game(game, advanced=True)))
-50
View File
@@ -709,31 +709,6 @@ def frame_move(package: str = typer.Argument(..., help="an installed game"),
typer.echo(f"moved to {st.get('base') or st.get('to')}")
@frame_app.command("steam-library")
def frame_steam_library(mode: str = typer.Argument(..., help="now, later or off"),
frame: Optional[str] = typer.Option(None, help=FRAME_HELP)):
"""Save Steam shortcut behaviour for future installs and Play, and apply it on the Frame."""
from .core import library
if mode not in ("now", "later", "off"):
raise typer.BadParameter("choose now, later or off")
_target(frame).connect().frame.agent("library_mode", mode=mode)
library.set_setting("install.steam_library", mode)
typer.echo(mode)
@frame_app.command("restart-steam")
def frame_restart_steam(frame: Optional[str] = typer.Option(None, help=FRAME_HELP),
yes: bool = typer.Option(False, "--yes", help="confirm ending a running game")):
"""Restart Steam now and apply pending library changes. Closes local FramePort/Desktop Mode too."""
agent = _target(frame).connect().frame
result = agent.agent("restart_steam", confirm=yes)
if result.get("confirmation_required"):
typer.confirm("A game is running. End it and restart Steam?", abort=True)
result = agent.agent("restart_steam", confirm=True)
typer.echo(json.dumps(result))
@frame_app.command("info")
def frame_info(frame: Optional[str] = typer.Option(None, help=FRAME_HELP)):
"""The Frame's SteamOS build, runtimes, storage and installed games (JSON)."""
@@ -755,31 +730,6 @@ def frame_trust_key(frame: Optional[str] = typer.Option(None, help=FRAME_HELP)):
typer.echo(f"connected: {info.get('hostname') or t.host} (new key saved)")
@frame_app.command("ssh-keys")
def frame_ssh_keys(add: list[str] = typer.Option([], "--add", help="a private key file to log in with too"),
remove: list[str] = typer.Option([], "--remove", help="stop using this key file (it stays)")):
"""Private SSH key files FramePort logs in with besides its own key (Settings → Installing → SSH keys): for a
Frame that accepts only your own key. The Frame connection and OpenSSH uploads both use them. Lists them."""
from .frame.connection import KeyFileError, add_extra_key, extra_key_status, remove_extra_key
failed = False
for path in remove:
typer.echo(f"removed {path}" if remove_extra_key(path) else f"not in the list: {path}")
for path in add:
try:
typer.echo(f"added {add_extra_key(path)}")
except KeyFileError as exc:
typer.echo(f"can't use {path}: {exc}", err=True)
failed = True
status = extra_key_status()
for path, problem in status:
typer.echo(f"{path}" + (f" (not usable: {problem})" if problem else ""))
if not status:
typer.echo("no extra keys: FramePort's own key and your SSH agent's keys only")
if failed:
raise typer.Exit(1)
@frame_app.command("usb-check")
def frame_usb_check(frame: Optional[str] = typer.Option(None, help=FRAME_HELP),
no_speed: bool = typer.Option(False, help="skip the upload speed test (2 × 128 MB)")):
+4 -100
View File
@@ -1,8 +1,8 @@
"""SSH connection to a Steam Frame and the remote agent protocol.
Authentication: FramePort's own keys first (<user data>/ssh/id_ed25519, installed by the bootstrap script, and
id_rsa, registered through Valve's devkit pairing, which only takes RSA keys), then key files the user added in
Settings (EXTRA_KEYS_SETTING), then the user's SSH agent/keys, then a password if given.
id_rsa, registered through Valve's devkit pairing, which only takes RSA keys), then the user's SSH agent/keys, then a
password if given.
"""
from __future__ import annotations
@@ -163,96 +163,6 @@ def app_keys() -> list[paramiko.PKey]:
return keys
EXTRA_KEYS_SETTING = "ssh.extra_keys" # library setting: private key files the user added (Settings → Installing)
class KeyFileError(ValueError):
"""A key file the user named can't be used (missing, not a private key, protected with a passphrase)."""
def load_key_file(path) -> paramiko.PKey:
"""A private key FramePort can log in with, or KeyFileError with a sentence saying why not."""
p = Path(path).expanduser()
if not p.is_file():
raise KeyFileError(f"{p}: file not found")
try:
return paramiko.PKey.from_path(p)
except (paramiko.SSHException, ValueError, OSError, UnicodeDecodeError, TypeError) as exc:
# paramiko says so with PasswordRequiredException (PEM) or a plain SSHException (OpenSSH format)
if isinstance(exc, paramiko.PasswordRequiredException) or "password" in str(exc).lower():
raise KeyFileError(f"{p.name} is protected with a passphrase, which FramePort can't ask for: add the "
"key to your SSH agent instead (FramePort also logs in with the agent's keys)") from None
raise KeyFileError(f"{p.name} isn't a private SSH key FramePort can read "
f"(OpenSSH or PEM format; a .pub file is the public half): {exc}") from None
def extra_key_paths() -> list[Path]:
"""The key files from Settings, as stored (each may be missing or unreadable by now: see extra_keys)."""
try:
from ..core import library
stored = library.peek_setting(EXTRA_KEYS_SETTING, [])
except Exception: # noqa: BLE001 - no library yet
return []
if isinstance(stored, str):
stored = [stored]
paths: list[Path] = []
for value in stored if isinstance(stored, list) else []:
if isinstance(value, str) and value.strip():
p = Path(value.strip()).expanduser()
if p not in paths:
paths.append(p)
return paths
def add_extra_key(path) -> Path:
"""Check a key file (KeyFileError if FramePort can't use it) and add it to Settings. Returns the stored path."""
p = Path(path).expanduser()
if p.name.endswith(".pub") and p.with_name(p.name[:-4]).is_file():
raise KeyFileError(f"{p.name} is the public half: pick {p.name[:-4]} (the file without .pub) instead")
load_key_file(p)
p = p.resolve()
from ..core import library
library.update_setting(EXTRA_KEYS_SETTING, lambda old: [v for v in (old if isinstance(old, list) else [])
if Path(v).expanduser() != p] + [str(p)], [])
return p
def remove_extra_key(path) -> bool:
"""Take a key file out of Settings (the file itself stays). False if it wasn't there."""
from ..core import library
p = Path(path).expanduser()
before = extra_key_paths()
library.update_setting(EXTRA_KEYS_SETTING, lambda old: [v for v in (old if isinstance(old, list) else [])
if Path(v).expanduser() != p], [])
return p in before
def extra_key_status() -> list[tuple[Path, str]]:
"""Each key file from Settings with "" when usable, else why not (for Settings and the CLI)."""
status = []
for path in extra_key_paths():
try:
load_key_file(path)
status.append((path, ""))
except KeyFileError as exc:
status.append((path, str(exc)))
return status
def extra_keys() -> list[tuple[Path, paramiko.PKey]]:
"""The usable keys from Settings; unusable ones are logged and skipped (a login still tries the others)."""
keys = []
for path in extra_key_paths():
try:
keys.append((path, load_key_file(path)))
except KeyFileError as exc:
log.warning("SSH key from Settings skipped: %s", exc)
return keys
@dataclass
class FrameTarget:
host: str
@@ -499,10 +409,6 @@ class Frame:
_video_codec_digest: str = "" # "<manifest digest>:<on|off>" handled on this connection (incl. a failed install)
_video_codec_lock: threading.Lock = field(default_factory=threading.Lock)
home: str = ""
# how the last login worked: "app_key" (FramePort's own key), "user_key" (a key file from Settings),
# "agent" (this PC's SSH agent / ~/.ssh keys) or "password"; OpenSSH uploads follow it (native_upload)
auth: str = ""
openssh_relaxed: bool | None = None # native_upload: True once OpenSSH needed this PC's own keys/agent
# ------------------------------------------------------------------ connect
def connect(self, timeout: float = 10) -> Frame:
@@ -553,8 +459,7 @@ class Frame:
kwargs = dict(hostname=self.target.host, port=self.target.port, username=self.target.user, timeout=timeout,
banner_timeout=timeout, auth_timeout=timeout)
errors = []
attempts = ([("app_key", k) for k in app_keys()] + [("user_key", k) for _, k in extra_keys()]
+ [("agent", None), ("password", None)])
attempts = [("app_key", k) for k in app_keys()] + [("agent", None), ("password", None)]
for attempt, pkey in attempts:
if attempt == "password" and not self.password:
continue
@@ -562,7 +467,7 @@ class Frame:
client.load_host_keys(str(known))
client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # trust on first use (pairing)
try:
if attempt in ("app_key", "user_key"):
if attempt == "app_key":
client.connect(pkey=pkey, allow_agent=False, look_for_keys=False, **kwargs)
elif attempt == "agent":
client.connect(allow_agent=True, look_for_keys=True, **kwargs)
@@ -587,7 +492,6 @@ class Frame:
raise
else:
raise FrameNotPaired(bool(self.password), errors)
self.auth = attempt
client.save_host_keys(str(known))
transport = client.get_transport()
transport.set_keepalive(15)
+29 -156
View File
@@ -2,9 +2,10 @@
from __future__ import annotations
import contextlib
import csv
import io
import os
import posixpath
import re
import shutil
import signal
import subprocess
@@ -12,30 +13,19 @@ import tarfile
import tempfile
import threading
import time
from pathlib import Path, PureWindowsPath
from pathlib import Path
from .connection import extra_keys, sh_quote, ssh_dir
from .connection import sh_quote, ssh_dir
def quote(value, windows=False) -> str:
"""One sftp batch argument, taken literally.
Inside double quotes sftp escapes glob characters (* ? [) itself and undoes that for put's destination, so
they must NOT be escaped again: an extra backslash became part of the name (GitHub #324: "[ENG]" in a folder
name made every OpenSSH upload fail, on Linux too). Only backslash and the quote are escaped. ``windows``: a
local Windows path goes with forward slashes; Win32-OpenSSH's sftp turns every backslash of a local path into
'/', escapes included ("C:\\\\Users" → "C://Users").
"""
def quote(value) -> str:
value = str(value)
if any(c in value for c in "\r\n\x00"):
raise ValueError("SFTP paths cannot contain newlines or NUL")
if windows:
value = PureWindowsPath(value).as_posix()
return '"' + value.replace("\\", "\\\\").replace('"', '\\"') + '"'
def quote_local(path) -> str:
return quote(path, windows=os.name == "nt")
escaped = value.replace("\\", "\\\\").replace('"', '\\"')
for char in "*?[":
escaped = escaped.replace(char, "\\" + char)
return '"' + escaped + '"'
def size_of(sftp, path):
@@ -45,74 +35,27 @@ def size_of(sftp, path):
return 0
def key_files(relaxed=False) -> list[Path]:
"""The private keys OpenSSH offers: FramePort's own (<data>/ssh) and the usable key files from Settings;
``relaxed`` also this PC's default keys (default_key_files)."""
keys = [ssh_dir() / name for name in ("id_ed25519", "id_rsa") if (ssh_dir() / name).exists()]
for path in [path for path, _ in extra_keys()] + (default_key_files() if relaxed else []):
if path not in keys:
keys.append(path)
return keys
def default_key_files() -> list[Path]:
"""This PC's own keys that Paramiko's "agent" login tries (look_for_keys: ~/.ssh/id_rsa, id_dsa, id_ecdsa,
id_ed25519; on Windows ~/ssh too), usable without a passphrase. OpenSSH needs them named: it skips its default
keys as soon as one -i is given, and Windows OpenSSH refuses a key file others can read (a private copy can't
be refused)."""
from .connection import KeyFileError, load_key_file
folders = [Path.home() / ".ssh"] + ([Path.home() / "ssh"] if os.name == "nt" else [])
found = []
for folder in folders:
for name in ("id_rsa", "id_dsa", "id_ecdsa", "id_ed25519"):
path = folder / name
if not path.is_file():
continue
try:
load_key_file(path)
except KeyFileError:
continue # passphrase-protected or not a key: only the agent can use it
found.append(path)
return found
def current_sid() -> str:
"""This Windows account's SID. whoami prints in the console code page: read bytes, so a user name with
accents can't break decoding (only the ASCII SID is used)."""
out = subprocess.check_output(["whoami", "/user", "/fo", "csv", "/nh"], **hidden())
match = re.search(rb"S-1-[0-9]+(?:-[0-9]+)+", out)
if not match:
raise OSError("cannot find this Windows account's SID for the key copies' permissions")
return match.group().decode()
@contextlib.contextmanager
def credentials(frame, port_flag="-P", relaxed=False):
"""OpenSSH arguments that log in like the Frame connection and trust only the host key it pinned.
Keys are offered as private temporary copies (that avoids modifying pairing keys, including their Windows
ACLs; Windows OpenSSH refuses key files others can read). Strict (default): FramePort's keys and the key
files from Settings only (IdentitiesOnly). ``relaxed``: also this PC's default ~/.ssh keys and SSH agent, the
way Paramiko's "agent" login does (GitHub #242: a Frame that only authorizes the user's own key). Verbose
(-v), so a refused login can say which keys were offered (failure()).
"""
key_paths = key_files(relaxed)
if not key_paths and not relaxed:
def credentials(frame, port_flag="-P"):
"""Private temporary copies avoid modifying pairing keys, including their Windows ACLs."""
key_paths = [ssh_dir() / name for name in ("id_ed25519", "id_rsa") if (ssh_dir() / name).exists()]
if not key_paths:
raise OSError("no FramePort key available for OpenSSH")
key = frame.client.get_transport().get_remote_server_key()
with tempfile.TemporaryDirectory(prefix="frameport-upload-") as directory:
directory = Path(directory)
sid = None
if os.name == "nt":
sid = current_sid()
row = next(csv.reader(io.StringIO(subprocess.check_output(
["whoami", "/user", "/fo", "csv", "/nh"], text=True, **hidden()))))
sid = row[-1]
subprocess.run(["icacls", str(directory), "/inheritance:r", "/grant:r", f"*{sid}:(OI)(CI)F"],
check=True, stdout=subprocess.DEVNULL, **hidden())
else:
directory.chmod(0o700)
copies = []
for n, path in enumerate(key_paths):
copy = directory / f"key{n}" # own names: a key from Settings may be called id_ed25519 too
for path in key_paths:
copy = directory / path.name
shutil.copyfile(path, copy)
if sid:
subprocess.run(["icacls", str(copy), "/inheritance:r", "/remove:g", "*S-1-3-4",
@@ -123,72 +66,13 @@ def credentials(frame, port_flag="-P", relaxed=False):
known = directory / "known_hosts"
host = frame.target.host if frame.target.port == 22 else f"[{frame.target.host}]:{frame.target.port}"
known.write_text(f"{host} {key.get_name()} {key.get_base64()}\n")
yield ["-F", os.devnull, "-v", *copies, "-o", "BatchMode=yes",
*([] if relaxed else ["-o", "IdentitiesOnly=yes"]),
yield ["-F", os.devnull, *copies, "-o", "BatchMode=yes", "-o", "IdentitiesOnly=yes",
"-o", "StrictHostKeyChecking=yes", "-o", f'UserKnownHostsFile="{known.as_posix()}"',
"-o", f"GlobalKnownHostsFile={os.devnull}", "-o", "ConnectTimeout=10",
"-o", "ServerAliveInterval=10", "-o", "ServerAliveCountMax=3",
port_flag, str(frame.target.port)]
class OpenSSHAuthFailed(OSError):
"""OpenSSH reached the Frame but the login was refused (the keys it offered aren't authorized there)."""
AUTH_REFUSED = ("Permission denied (", "Too many authentication failures", "No more authentication methods")
# debug lines (-v) worth keeping: which keys were found, offered, refused or unreadable
AUTH_DEBUG = ("identity file", "Offering public key", "Server accepts key", "Will attempt key",
"Authentications that can continue", "Authenticated to", "Load key", "no such identity",
"Skipping", "agent", "Next authentication method")
def failure(what: str, code, stderr: bytes) -> OSError:
"""The error for a failed OpenSSH run: OpenSSH's own messages (all non-debug lines: warnings such as
"UNPROTECTED PRIVATE KEY FILE" included) plus the -v lines about keys; OpenSSHAuthFailed for a refused login."""
text = stderr.decode(errors="replace").replace("\r\n", "\n")
lines = [line for line in text.splitlines() if line.strip() and (
not line.startswith("debug") or any(k in line for k in AUTH_DEBUG))]
detail = "\n".join(lines)
if len(detail) > 4000:
detail = "…" + detail[-4000:]
refused = code == 255 and any(marker in text for marker in AUTH_REFUSED)
return (OpenSSHAuthFailed if refused else OSError)(f"{what} failed ({code}): {detail}")
def login_modes(frame) -> list[bool]:
"""How OpenSSH logs in, in order (False = FramePort's keys only, True = also this PC's keys and agent).
A Frame connection that logged in with this PC's own keys/agent (Paramiko's "agent" attempt) goes straight to
relaxed: FramePort's key isn't authorized there. Else strict first, relaxed once more after a refused login.
A mode that worked is kept for the rest of the connection. FramePort doesn't add its key to the Frame for
this: it only does that after a password login, where the user typed the Frame's password for it."""
known = getattr(frame, "openssh_relaxed", None)
if known is not None:
return [bool(known)]
if getattr(frame, "auth", "") == "agent":
return [True]
return [False, True]
def with_login_modes(frame, reporter, run):
"""run(relaxed) in each login mode until one isn't refused (see login_modes)."""
modes = login_modes(frame)
if modes == [True] and getattr(frame, "openssh_relaxed", None) is None:
reporter.log("the Frame connection logged in with this PC's own SSH keys or agent: OpenSSH uses them too")
for n, relaxed in enumerate(modes):
try:
result = run(relaxed)
except OpenSSHAuthFailed as exc:
if n == len(modes) - 1:
raise
reporter.log(f"OpenSSH login with FramePort's SSH keys was refused; trying this PC's own SSH keys and "
f"agent too. {exc}")
continue
with contextlib.suppress(AttributeError):
frame.openssh_relaxed = relaxed
return result
def hidden():
return {"creationflags": subprocess.CREATE_NO_WINDOW} if os.name == "nt" else {}
@@ -215,11 +99,6 @@ def upload(frame, items, remote_root, reporter, total, sent, workers):
Only successful batches are promoted, after every process has exited successfully. All control operations
happen in the supervising thread, so Paramiko's SFTP client is never shared across threads.
"""
return with_login_modes(frame, reporter, lambda relaxed: _upload(
frame, items, remote_root, reporter, total, sent, workers, relaxed))
def _upload(frame, items, remote_root, reporter, total, sent, workers, relaxed):
executable = shutil.which("sftp")
if not executable:
raise OSError("system OpenSSH SFTP is unavailable")
@@ -232,7 +111,7 @@ def _upload(frame, items, remote_root, reporter, total, sent, workers, relaxed):
sizes, offsets, progress = {}, {}, {}
for path, rel, size in sorted(items, key=lambda item: item[2], reverse=True):
remote = posixpath.join(remote_root, rel)
quote_local(path)
quote(path)
quote(remote)
offset = size_of(frame.sftp, remote + ".part")
if offset > size:
@@ -248,7 +127,7 @@ def _upload(frame, items, remote_root, reporter, total, sent, workers, relaxed):
speed = Speed(total - sent - sum(offsets.values()))
reporter.log(f"uploading large files with OpenSSH SFTP ({len(groups)} workers)")
setup_started = time.monotonic()
with credentials(frame, relaxed=relaxed) as args, contextlib.ExitStack() as stack:
with credentials(frame) as args, contextlib.ExitStack() as stack:
monitor = stack.enter_context(frame.client.open_sftp())
monitor.get_channel().settimeout(2)
reporter.log(f"OpenSSH credentials and progress connection ready in {time.monotonic() - setup_started:.2f}s")
@@ -260,7 +139,7 @@ def _upload(frame, items, remote_root, reporter, total, sent, workers, relaxed):
for path, rel, _ in group:
remote = posixpath.join(remote_root, rel) + ".part"
command = "reput" if offsets[rel] else "put"
batch.write(f"{command} {quote_local(path)} {quote(remote)}\n".encode())
batch.write(f"{command} {quote(path)} {quote(remote)}\n".encode())
batch.seek(0)
errors = stack.enter_context(tempfile.TemporaryFile())
process = subprocess.Popen([executable, *args, "-b", "-",
@@ -273,7 +152,8 @@ def _upload(frame, items, remote_root, reporter, total, sent, workers, relaxed):
for process, errors in processes:
if process.poll() not in (None, 0):
errors.seek(0)
raise failure("OpenSSH SFTP", process.returncode, errors.read())
detail = errors.read().decode(errors="replace")[-1500:]
raise OSError(f"OpenSSH SFTP failed ({process.returncode}): {detail}")
for rel, size in sizes.items():
reporter.check_cancel()
progress[rel] = max(progress[rel], min(size, size_of(
@@ -307,16 +187,11 @@ def _upload(frame, items, remote_root, reporter, total, sent, workers, relaxed):
def put_tar(frame, files, remote_root, reporter, progress):
"""Stream a tar batch over paired OpenSSH; supervise writes so Cancel also stops a blocked pipe."""
return with_login_modes(frame, reporter,
lambda relaxed: _put_tar(frame, files, remote_root, reporter, progress, relaxed))
def _put_tar(frame, files, remote_root, reporter, progress, relaxed):
executable = shutil.which("ssh")
if not executable:
raise OSError("system OpenSSH SSH is unavailable")
reporter.check_cancel()
with credentials(frame, port_flag="-p", relaxed=relaxed) as args, tempfile.TemporaryFile() as errors:
with credentials(frame, port_flag="-p") as args, tempfile.TemporaryFile() as errors:
command = f"mkdir -p {sh_quote(remote_root)} && tar -xf - -C {sh_quote(remote_root)}"
process = subprocess.Popen([executable, *args, f"{frame.target.user}@{frame.target.host}", command],
stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=errors,
@@ -347,14 +222,12 @@ def _put_tar(frame, files, remote_root, reporter, progress, relaxed):
if not writer.is_alive() and process.poll() is None:
time.sleep(0.1)
reporter.check_cancel()
if failures and process.poll() is None: # a refused login shows as a broken pipe first
with contextlib.suppress(subprocess.TimeoutExpired):
process.wait(timeout=2)
if process.poll() not in (None, 0):
errors.seek(0)
raise failure("OpenSSH tar", process.returncode, errors.read())
if failures:
raise failures[0]
if process.poll() != 0:
errors.seek(0)
raise OSError(f"OpenSSH tar failed ({process.returncode}): "
+ errors.read().decode(errors="replace")[-1500:])
finally:
stop_process(process)
writer.join()
+1 -11
View File
@@ -817,15 +817,7 @@ def add_to_steam(frame: Frame, packages: list[str], reporter: Reporter, wait: fl
import time
reporter.stage("Add to Steam library")
from ..core import library
mode = library.setting("install.steam_library", "now")
frame.agent("library_mode", mode=mode)
submitted = frame.agent("shortcuts", packages=packages, restart=True, mode=mode)
if submitted.get("disabled") or submitted.get("state") == "pending":
reporter.check("Steam library", None, "disabled; use FramePort Play" if mode == "off" else
"queued for the next Steam start; you can keep installing")
return submitted
frame.agent("shortcuts", packages=packages, restart=True)
end = time.time() + wait
status = {}
while time.time() < end:
@@ -838,8 +830,6 @@ def add_to_steam(frame: Frame, packages: list[str], reporter: Reporter, wait: fl
break
if status.get("state") == "waiting": # Steam restarts later: after the game, or back in Gaming Mode
reporter.check("Steam library", None,
"added after FramePort on the Frame closes (Steam has to restart for it)"
if status.get("reason") == "frameport" else
"added when you're back in Gaming Mode (Steam has to restart for it)"
if status.get("reason") == "desktop" else
"added when the game that's running now is closed (Steam has to restart for it)")
-21
View File
@@ -66,7 +66,6 @@
"920 × 430": "",
"96 Hz": "",
"A folder with Quest, Android or PC VR games.": "",
"A game is running": "",
"A game is running on the Frame": "",
"A game is running on the Frame. Close it in the headset first, then try again.": "",
"a known blocker": "",
@@ -95,7 +94,6 @@
"AC Nexus: no AppSW at 72 Hz": "",
"AC Nexus: no AppSW at 90 Hz": "",
"Activity": "",
"Add a key file…": "",
"Add a Linux app folder…": "",
"Add a Linux app…": "",
"Add a PC game folder…": "",
@@ -277,7 +275,6 @@
"Connect by address…": "",
"Connect Frames in Developer Mode automatically": "",
"Connect the Frame's USB-C port to this PC with a data cable (not a charge-only one).": "",
"Connect to the Frame first.": "",
"Connect to your Steam Frame to browse its videos, downloads and each game's storage.": "",
"Connect to your Steam Frame to see its screenshots here.": "",
"Connect to your Steam Frame to stream its view and sound to this PC.": "",
@@ -560,7 +557,6 @@
"Frame OpenXR compatibility layer": "",
"FrameBridge OpenXR adapter": "",
"FramePort": "",
"FramePort also logs in with {name} from the next connection.": "",
"FramePort can't update itself in {value} (no permission) — opening the release page to download it": "",
"FramePort changelog": "",
"FramePort checks GitHub for a new version every few hours. Update now downloads and checks it, then restarts FramePort; your games and settings stay.": "",
@@ -572,7 +568,6 @@
"FramePort isn't sure which program starts this game. Open the game and use … → Change program… to pick it.": "",
"FramePort keeps its own copies; nothing is installed system-wide": "",
"FramePort live view": "",
"FramePort logs in to the Frame with its own key. If your Frame accepts only one of your own keys, add that private key file here; fast uploads use it too. A key with a passphrase: add it to your SSH agent instead.": "",
"FramePort looked at your last session of {n} game and has something to try.": [
"",
""
@@ -806,7 +801,6 @@
"Last launch test: {get} · got as far as: {value}": "",
"Last session · ended {ago}": "",
"late": "",
"Later — next Steam start": "",
"Launch log": "",
"Launch log · {title}": "",
"Launch options (SteamVR or OpenXR)": "",
@@ -1003,9 +997,6 @@
"Nothing to patch: it runs unchanged.": "",
"Nothing to see here.": "",
"nothing yet": "",
"Now (default)": "",
"Now waits until Steam can restart safely. Later saves shortcuts for the next Steam start. Off uses FramePort Play without Steam per-game integration; existing shortcuts stay.": "",
"Now waits while a game, Desktop Mode, or local FramePort is open. Later lets you keep installing without restarting Steam. Off uses FramePort Play without Steam per-game integration.": "",
"Now {scale:.0%}.": "",
"Now {scale:.0%}. Changes apply the next time FramePort starts.": "",
"Now {scale:.0%}; {new:.0%} after restarting FramePort.": "",
@@ -1017,7 +1008,6 @@
"Oculus OS telemetry class stubs": "",
"Oculus XR Plugin games render both eyes in one pass (multiview) on Android. If one eye shows only effects or gray (for example I Am Cat), rendering each eye in its own pass can fix it, at some GPU cost. Rewrites OculusSettings.GetStereoRenderingMode and its inlined read in OculusLoader.Initialize -> MultiPass in libil2cpp.so (found with Cpp2IL). Try it when one eye is wrong.": "",
"Off": "",
"Off — launch from FramePort": "",
"Off: these links open whatever app is set up for them.": "",
"off: {names}": "",
"Offline": "",
@@ -1039,7 +1029,6 @@
"On your Frame": "",
"on: {names}": "",
"One PC game folder": "",
"Only FramePort's own key, and your SSH agent's keys.": "",
"Only if 360° pictures show wrongly.": "",
"Only if 360° pictures show wrongly: 1 = upside down, 2 = mirrored, 4 = turned around (add values to combine).": "",
"Only install software from sites you trust. FramePort downloads it from {host} and installs it on your Frame.": "",
@@ -1152,7 +1141,6 @@
"Pretty smooth": "",
"Prevents a start-up crash in some Unreal games.": "",
"Previous": "",
"Private SSH key file (not the .pub file)": "",
"Problems and feedback": "",
"Processes": "",
"Processor": "",
@@ -1277,13 +1265,10 @@
"Reset {title}'s recipe?": "",
"Restart": "",
"Restart now": "",
"Restart Steam now": "",
"Restart Steam now?": "",
"Restart the Frame": "",
"Restart the Frame?": "",
"Restart the Frame…": "",
"Restarting": "",
"Restarting Steam ends the running game. Continue?": "",
"Resume": "",
"Resuming — copied files are skipped": "",
"Retry refused picture formats": "",
@@ -1431,7 +1416,6 @@
"Sound on": "",
"Source": "",
"square, 256 × 256": "",
"SSH keys": "",
"Stable (default)": "",
"Stand in for cube layers": "",
"Standard for every game": "",
@@ -1471,8 +1455,6 @@
"Steam Frame patches": "",
"Steam Frame: installed on the Frame, with an entry in its Steam library. This PC: a Steam shortcut that starts the game through Revive, for a headset connected to this PC.": "",
"Steam game": "",
"Steam is restarting. FramePort on the Frame will close.": "",
"Steam library": "",
"Steam on the Frame downloads Proton (about 1 GiB). Steam restarts once, which closes a running game.": "",
"Steam on the Frame isn't responding. Restart the Frame and try again.": "",
"SteamOS · Developer Mode": "",
@@ -1484,7 +1466,6 @@
"Stereo (3D) 360° layers: 0 = as the game sends them, 2 = flat (the left image to both eyes).": "",
"Stop": "",
"Stop objects popping in and out": "",
"Stop using this key (the file stays)": "",
"Stopped: {why}": "",
"Stops a black picture in Minecraft launchers (for example QuestCraft).": "",
"Stops a crash a few seconds after start in some Unreal games with anti-aliasing (for example Star Wars Pinball VR).": "",
@@ -1536,7 +1517,6 @@
"Test Proton on the Frame": "",
"Text and layout size": "",
"That APK is a different app, not {title}.": "",
"That key can't be used: {error}": "",
"That theme file can't be used: {error}": "",
"That's me!": "",
"The APK file is damaged or incomplete. Get the game again and rescan the folder.": "",
@@ -1613,7 +1593,6 @@
"They run on the Frame too.": "",
"They're deleted on the Frame for good. Steam's own list may show them until Steam restarts.": "",
"They're part of SteamOS. Ending them may restart Steam and stop the running game.": "",
"This applies pending library changes and closes Desktop Mode and FramePort on the Frame.": "",
"This deletes the {what} on the Frame. It can't be undone.": "",
"This folder contains an installer without a launchable Linux program. FramePort runs programs, not installers. Use the project's own install instructions.": "",
"This folder is empty. Upload files with the buttons above.": "",
+1 -4
View File
@@ -71,10 +71,7 @@ class FrameLeptonTarget(Target):
return self.connect().frame.agent("collect_diag", timeout=180, package=package)
def launch(self, package):
from ..core import library
return self.connect().frame.agent("launch", package=package, timeout=60,
mode=library.setting("install.steam_library", "now"))
return self.connect().frame.agent("launch", package=package, timeout=60)
def set_settings(self, package, settings):
from ..core import library
-5
View File
@@ -19,8 +19,6 @@ class _Translated(dict):
HELP: dict[str, str] = _Translated({
"steam_library": "Now waits until Steam can restart safely. Later saves shortcuts for the next Steam start. "
"Off uses FramePort Play without Steam per-game integration; existing shortcuts stay.",
# ---- game status / library
"status": "How well the game runs on the Steam Frame. \"Works\" and \"Works with issues\" were tested on a Frame; "
"\"Untested\" is a suggestion nobody has confirmed yet. \"Can't run\" means a known blocker.",
@@ -64,9 +62,6 @@ HELP: dict[str, str] = _Translated({
"hw_video_decode": "Games with the Hardware video decoding patch play their videos on the Frame's video hardware. "
"Turn it off if videos misbehave; games pick it up at their next start. For one game only, put "
"FRAMEPORT_NO_HW_VIDEO=1 before %command% in its Steam launch options.",
"ssh_keys": "FramePort logs in to the Frame with its own key. If your Frame accepts only one of your own keys, "
"add that private key file here; fast uploads use it too. A key with a passphrase: add it to your SSH "
"agent instead.",
"launch_test": "Starts the game on the Frame while nobody wears the headset and reads the log: did it start and "
"draw frames. It can't check the picture.",
"last_session": "After you play a game on the Frame, FramePort reads that session's log: crashes, frame rate and "
+2 -81
View File
@@ -96,35 +96,6 @@ class SettingsView:
from ...core import library
from ...install.installer import upload_threads
def steam_changed(e):
mode = e.control.value
library.set_setting("install.steam_library", mode)
if self.app.frame_state == "connected":
self.app.run_bg(lambda: self.app.target.connect().frame.agent("library_mode", mode=mode))
def restart(e):
app = self.app
if app.frame_state != "connected":
app.toast(tr("Connect to the Frame first."))
return
def work(confirm=False):
result = app.target.connect().frame.agent("restart_steam", confirm=confirm)
if result.get("confirmation_required"):
C.confirm(app.page, tr("A game is running"),
tr("Restarting Steam ends the running game. Continue?"), tr("Restart Steam now"),
lambda: app.run_bg(lambda: work(True)), danger=True)
else:
app.toast(tr("Steam is restarting. FramePort on the Frame will close."))
C.confirm(app.page, tr("Restart Steam now?"),
tr("This applies pending library changes and closes Desktop Mode and FramePort on the Frame."),
tr("Restart Steam now"), lambda: app.run_bg(work))
steam = ft.Row([C.dropdown(label=tr("Steam library"),
value=library.setting("install.steam_library", "now"), width=T.px(360),
options=[ft.DropdownOption("now", tr("Now (default)")),
ft.DropdownOption("later", tr("Later — next Steam start")),
ft.DropdownOption("off", tr("Off — launch from FramePort"))],
on_select=steam_changed), C.help_icon("steam_library")], spacing=T.S1)
def changed(e):
library.set_setting("install.launch_test", bool(e.control.value))
def keep_changed(e):
@@ -156,63 +127,13 @@ class SettingsView:
parallel = C.dropdown(label=tr("Parallel uploads"), value=str(upload_threads()), width=T.px(240),
options=[ft.DropdownOption(str(n), str(n)) for n in range(1, 9)],
on_select=threads_changed)
return ft.Column([steam, C.meta(tr("Now waits while a game, Desktop Mode, or local FramePort is open. "
"Later lets you keep installing without restarting Steam. "
"Off uses FramePort Play without Steam per-game integration.")),
C.ghost(tr("Restart Steam now"), ft.Icons.RESTART_ALT, restart),
launch, keep, video, parallel,
return ft.Column([launch, keep, video, parallel,
C.meta(tr("Large files upload together using OpenSSH when available. "
"Default: 3. Lower this on a busy network.")),
C.ghost(tr("Remove converted copies now"), ft.Icons.CLEANING_SERVICES_OUTLINED, clean,
tooltip=tr("Your own game files aren't touched.")),
ft.Container(height=T.S2), self.ssh_keys()],
tooltip=tr("Your own game files aren't touched."))],
spacing=T.S2, horizontal_alignment=ft.CrossAxisAlignment.START)
def ssh_keys(self) -> ft.Control:
"""Settings → Installing: private key files FramePort logs in with besides its own (frame.connection
EXTRA_KEYS_SETTING; the Frame connection and OpenSSH uploads both use them, GitHub #242)."""
from ...frame import connection
app = self.app
rows = ft.Column(spacing=T.S1)
def fill():
items = []
for path, problem in connection.extra_key_status():
items.append(ft.Row([
C.as_icon(ft.Icons.KEY_ROUNDED if not problem else ft.Icons.WARNING_AMBER_ROUNDED, T.px(18),
T.TEXT_2 if not problem else T.WARN),
ft.Column([C.body(path.name, T.TEXT), C.meta(problem or str(path), selectable=True)],
spacing=0, expand=True),
C.icon_btn(ft.Icons.DELETE_OUTLINE_ROUNDED, tr("Stop using this key (the file stays)"),
on_click=lambda e, p=path: remove(p)),
], spacing=T.S2, vertical_alignment=ft.CrossAxisAlignment.CENTER))
rows.controls = items or [C.meta(tr("Only FramePort's own key, and your SSH agent's keys."))]
C.update(rows)
def remove(path):
connection.remove_extra_key(path)
fill()
async def add(e):
for path in await C.pick_files(app.page, dialog_title=tr("Private SSH key file (not the .pub file)"),
multiple=True):
try:
stored = connection.add_extra_key(path)
except connection.KeyFileError as exc:
app.toast(tr("That key can't be used: {error}").format(error=exc), error=True)
continue
app.toast(tr("FramePort also logs in with {name} from the next connection.").format(name=stored.name))
fill()
fill()
return ft.Column([
ft.Row([C.body(tr("SSH keys"), T.TEXT, weight=ft.FontWeight.W_500), C.help_icon("ssh_keys")],
spacing=T.px(4), vertical_alignment=ft.CrossAxisAlignment.CENTER),
rows,
C.secondary(tr("Add a key file…"), ft.Icons.VPN_KEY_ROUNDED, add),
], spacing=T.S2, horizontal_alignment=ft.CrossAxisAlignment.START)
def updates_card(self) -> ft.Control:
"""Settings → Updates: FramePort's own updates (ui/updater.py, frameport/updates.py)."""
import time
-226
View File
@@ -2081,229 +2081,3 @@ def test_launcher_starts_lepton_again_once_when_the_game_restarts_itself(monkeyp
(tmp_path / "starts").unlink()
subprocess.run([str(launcher)], timeout=30, env={**env, "FRAMEPORT_NO_RESTART": "1"}, start_new_session=True)
assert (tmp_path / "starts").read_text().count("started") == 1
def test_local_frameport_hold_expires(monkeypatch, tmp_path):
a = load_agent(monkeypatch, tmp_path)
monkeypatch.delenv("XDG_DATA_HOME", raising=False)
monkeypatch.setattr(a, "game_running", lambda: False)
monkeypatch.setattr(a, "desktop_mode", lambda: False)
assert a.restart_hold() is None
heartbeat = tmp_path / ".local/share/frameport-app/gui.alive"
heartbeat.parent.mkdir(parents=True)
heartbeat.touch()
assert a.restart_hold() == "frameport"
os.utime(heartbeat, (a.time.time() - 11, a.time.time() - 11))
assert a.restart_hold() is None
monkeypatch.setattr(a, "game_running", lambda: True)
assert a.restart_hold() == "game"
def test_library_later_survives_steam_exit_and_next_start(monkeypatch, tmp_path):
a = load_agent(monkeypatch, tmp_path)
pkg = "com.x.y"
anchor = Path(a.ANCHORS) / pkg
anchor.mkdir(parents=True)
(anchor / "deployment.json").write_text(json.dumps({"title": "X", "appid": 123, "base": str(anchor)}))
cfg = Path(a.STEAM) / "userdata/42/config"
cfg.mkdir(parents=True)
monkeypatch.setattr(a, "library_users", lambda: ["42"])
monkeypatch.setattr(a, "run", lambda *args, **kw: SimpleNamespace(returncode=0, stdout="", stderr=""))
monkeypatch.setattr(a, "stop_steam", lambda: pytest.fail("later stopped Steam"))
monkeypatch.setattr(a, "start_steam", lambda _: pytest.fail("later started Steam"))
a.cmd_library_mode({"mode": "later"})
assert a.cmd_shortcuts({"packages": [pkg]})["state"] == "pending"
hook = tmp_path / ".config/systemd/user/steam.service.d/frameport-library.conf"
assert "ExecStartPre=" in hook.read_text() and "ExecStartPost=" in hook.read_text()
vdf = cfg / "shortcuts.vdf"
assert pkg in a.pending_library()["packages"]
vdf.write_bytes(a.vdf_encode({"shortcuts": {}})) # Steam saved its old in-memory copy at exit
a.cmd_library_pending({})
assert any(e["appname"] == "X" for e in a.vdf_decode(vdf.read_bytes())["shortcuts"].values())
monkeypatch.setattr(a.time, "sleep", lambda _: None)
a.cmd_library_pending_verify({})
assert not a.pending_library()["packages"]
def test_pending_retained_when_live_repair_fails(monkeypatch, tmp_path):
a = load_agent(monkeypatch, tmp_path)
a._write_json(a.PENDING_FILE, {"packages": ["com.x.y"], "remove": []})
monkeypatch.setattr(a, "deployment", lambda _: {"title": "X"})
monkeypatch.setattr(a, "library_users", lambda: ["42"])
monkeypatch.setattr(a, "shortcuts_lost", lambda *args: ["com.x.y"])
monkeypatch.setattr(a, "devkit_register", lambda _: (_ for _ in ()).throw(a.AgentError("test")))
assert a.cmd_library_pending_verify({})["errors"]
assert a.pending_library()["packages"] == ["com.x.y"]
def test_off_skips_shortcuts_and_play_uses_direct_launcher(monkeypatch, tmp_path):
a = load_agent(monkeypatch, tmp_path)
a.cmd_library_mode({"mode": "off"})
assert a.library_mode() == "off"
assert a.cmd_shortcuts({"packages": ["com.x.y"]})["disabled"]
calls = []
monkeypatch.setattr(a, "deployment", lambda _: {"title": "X", "appid": 123})
monkeypatch.setattr(a, "game_is_running", lambda _: False)
monkeypatch.setattr(a, "run", lambda cmd, **kw: calls.append(cmd)
or SimpleNamespace(returncode=3 if "is-active" in cmd else 0, stderr=""))
monkeypatch.setattr(a, "devkit_register", lambda _: pytest.fail("off registered a shortcut"))
result = a.cmd_launch({"package": "com.x.y"})
assert result["via"] == "direct"
assert calls[-1][0] == "systemd-run" and calls[-1][-1].endswith("com.x.y/launch.sh")
assert not any("rungameid" in str(c) for c in calls)
def test_manual_restart_requires_game_confirmation(monkeypatch, tmp_path):
a = load_agent(monkeypatch, tmp_path)
monkeypatch.setattr(a, "game_running", lambda: True)
assert a.cmd_restart_steam({}) == {"confirmation_required": True}
monkeypatch.setattr(a, "cmd_shortcuts", lambda args: args)
assert a.cmd_restart_steam({"confirm": True})["restart_now"]
def test_startup_hook_does_not_deadlock_active_worker(monkeypatch, tmp_path):
a = load_agent(monkeypatch, tmp_path)
Path(a.STATUS_FILE).parent.mkdir(parents=True)
with open(a.STATUS_FILE + ".lock", "w") as lock:
a.fcntl.flock(lock, a.fcntl.LOCK_EX)
assert a.cmd_library_pending({})["worker_active"]
assert a.cmd_library_pending_verify({})["worker_active"]
@pytest.mark.parametrize("hold", [None, "frameport"])
def test_shortcut_worker_holds_local_gui_until_closed(monkeypatch, tmp_path, hold):
a = load_agent(monkeypatch, tmp_path)
clock = [100.0]
events = []
monkeypatch.setattr(a.time, "time", lambda: clock[0])
def sleep(seconds):
status = a.cmd_shortcut_status({})
events.append(status.get("reason"))
clock[0] += seconds
monkeypatch.setattr(a, "restart_hold", lambda: None)
monkeypatch.setattr(a.time, "sleep", sleep)
monkeypatch.setattr(a, "refresh_desktop_entries", lambda: None)
monkeypatch.setattr(a, "library_users", lambda: [])
monkeypatch.setattr(a, "steam_users", lambda: [])
monkeypatch.setattr(a, "library_changes", lambda *args: True)
monkeypatch.setattr(a, "restart_hold", lambda: hold)
monkeypatch.setattr(a, "stop_steam", lambda: events.append("stop") or True)
monkeypatch.setattr(a, "start_steam", lambda _: events.append("start"))
monkeypatch.setattr(a, "shortcuts_lost", lambda *args: [])
a.shortcuts_worker(json.dumps({"packages": [], "remove": []}))
assert events == (["frameport"] if hold else []) + ["stop", "start"]
assert a.cmd_shortcut_status({})["state"] == "done"
def test_pending_later_play_never_registers_shortcut(monkeypatch, tmp_path):
a = load_agent(monkeypatch, tmp_path)
a._write_json(a.PENDING_FILE, {"packages": ["com.x.y"], "remove": []})
monkeypatch.setattr(a, "deployment", lambda _: {"appid": 123, "title": "X"})
monkeypatch.setattr(a, "game_is_running", lambda _: False)
monkeypatch.setattr(a, "run", lambda cmd, **kw: SimpleNamespace(returncode=3 if "is-active" in cmd else 0,
stderr=""))
monkeypatch.setattr(a, "devkit_register", lambda _: pytest.fail("pending Play added a devkit shortcut"))
assert a.cmd_launch({"package": "com.x.y", "mode": "later"})["via"] == "direct"
@pytest.mark.parametrize("action", ["restart", "later", "off", "cap"])
def test_waiting_worker_can_be_released_without_deadlock(monkeypatch, tmp_path, action):
a = load_agent(monkeypatch, tmp_path)
clock = [100.0]
stopped = []
monkeypatch.setattr(a.time, "time", lambda: clock[0])
monkeypatch.setattr(a, "refresh_desktop_entries", lambda: None)
monkeypatch.setattr(a, "library_users", lambda: [])
monkeypatch.setattr(a, "steam_users", lambda: [])
monkeypatch.setattr(a, "library_changes", lambda *args: True)
monkeypatch.setattr(a, "restart_hold", lambda: "frameport")
monkeypatch.setattr(a, "game_running", lambda: False)
monkeypatch.setattr(a, "ensure_library_hooks", lambda: None)
monkeypatch.setattr(a, "stop_steam", lambda: stopped.append(True) or True)
monkeypatch.setattr(a, "start_steam", lambda _: None)
monkeypatch.setattr(a, "shortcuts_lost", lambda *args: [])
def sleep(seconds):
if action == "restart":
assert a.cmd_restart_steam({})["waiting_worker"]
elif action in ("later", "off"):
a._write_json(a.LIBRARY_MODE_FILE, {"mode": action})
clock[0] += 12 * 3600 if action == "cap" else seconds
monkeypatch.setattr(a.time, "sleep", sleep)
a.shortcuts_worker(json.dumps({"packages": [], "remove": []}))
assert bool(stopped) == (action in ("restart", "cap"))
status = a.cmd_shortcut_status({})
assert status["state"] == ("pending" if action == "later" else "done")
def test_manual_restart_worker_wakes_existing_lock_holder(monkeypatch, tmp_path):
a = load_agent(monkeypatch, tmp_path)
Path(a.STATUS_FILE).parent.mkdir(parents=True)
with open(a.STATUS_FILE + ".lock", "w") as lock:
a.fcntl.flock(lock, a.fcntl.LOCK_EX)
a.shortcuts_worker(json.dumps({"restart_now": True, "packages": []}))
assert json.load(open(a.RESTART_REQUEST_FILE))["requested"] > 0
def test_library_hook_is_bounded_and_never_fails_steam(monkeypatch, tmp_path):
a = load_agent(monkeypatch, tmp_path)
text = a.library_hooks_text(python="/usr/bin/python3", agent="/home/u/100% $HOME/frameport_agent.py",
timeout_bin="/usr/bin/timeout")
lines = [line for line in text.splitlines() if line.startswith("Exec")]
assert len(lines) == 2
pre, post = lines
# '-' first (a non-zero exit, also 127 for a missing interpreter, never fails Steam), then timeout(1)
assert pre.startswith("ExecStartPre=-/usr/bin/timeout -k 5 20 ") and pre.endswith(" library_pending")
assert post.startswith("ExecStartPost=-/usr/bin/timeout -k 5 20 /usr/bin/systemd-run --user ")
assert "--no-block" in post and "RuntimeMaxSec=" in post and post.endswith(" library_pending_verify")
assert '"/home/u/100%% $$HOME/frameport_agent.py"' in pre # systemd specifiers/variables escaped
assert "[Service]" in text
assert "timeout" not in a.library_hooks_text(timeout_bin="") # internal alarm then
def test_library_hook_written_once_and_removed_when_idle(monkeypatch, tmp_path):
a = load_agent(monkeypatch, tmp_path)
calls = []
monkeypatch.setattr(a, "run", lambda cmd, **kw: calls.append(cmd) or SimpleNamespace(returncode=0))
hook = tmp_path / ".config/systemd/user/steam.service.d/frameport-library.conf"
a.cmd_library_mode({"mode": "later"})
a.ensure_library_hooks()
a.ensure_library_hooks()
assert hook.exists()
assert calls.count(["systemctl", "--user", "daemon-reload"]) == 1 # unchanged drop-in: no reload
# back to "now" with a game still waiting for Steam's start: the hook stays until it is applied
a._write_json(a.PENDING_FILE, {"packages": ["com.x.y"], "remove": []})
a.cmd_library_mode({"mode": "now"})
assert hook.exists()
monkeypatch.setattr(a, "deployment", lambda _: {"title": "X"})
monkeypatch.setattr(a, "library_users", lambda: ["42"])
monkeypatch.setattr(a, "shortcuts_lost", lambda *args: [])
a.cmd_library_pending_verify({})
assert not hook.exists() and not hook.parent.exists()
assert calls.count(["systemctl", "--user", "daemon-reload"]) == 2
# nothing pending: switching away from "later" removes it at once, the user's own drop-ins stay
a.cmd_library_mode({"mode": "later"})
a.ensure_library_hooks()
(hook.parent / "extra_args.conf").write_text("[Service]\n")
a.cmd_library_mode({"mode": "off"})
assert not hook.exists() and (hook.parent / "extra_args.conf").exists()
def test_library_pre_hook_leaves_vdf_alone_when_nothing_waits(monkeypatch, tmp_path):
a = load_agent(monkeypatch, tmp_path)
monkeypatch.setattr(a, "library_users", lambda: pytest.fail("touched the library"))
monkeypatch.setattr(a, "steam_users", lambda: pytest.fail("touched the library"))
assert a.cmd_library_pending({}) == {"added": [], "errors": []}
Path(a.PENDING_FILE).write_text("[]") # damaged journal: treated as empty, never a crash in Steam's start
assert a.cmd_library_pending({}) == {"added": [], "errors": []}
def test_off_play_refuses_while_launcher_unit_starts(monkeypatch, tmp_path):
a = load_agent(monkeypatch, tmp_path)
a.cmd_library_mode({"mode": "off"})
monkeypatch.setattr(a, "deployment", lambda _: {"title": "X", "appid": 123})
monkeypatch.setattr(a, "game_is_running", lambda _: False)
calls = []
monkeypatch.setattr(a, "run", lambda cmd, **kw: calls.append(cmd) or SimpleNamespace(returncode=0, stderr=""))
with pytest.raises(a.AgentError):
a.cmd_launch({"package": "com.x.y"})
assert not any(c[0] == "systemd-run" for c in calls)
-38
View File
@@ -19,41 +19,3 @@ def test_errors_are_one_line_on_stderr(monkeypatch, capsys):
monkeypatch.setenv("FRAMEPORT_DEBUG", "1")
with pytest.raises(NoValidConnectionsError):
cli.main()
@pytest.mark.parametrize("mode", ["now", "later", "off"])
def test_steam_library_setting_cli(monkeypatch, mode):
from types import SimpleNamespace
from typer.testing import CliRunner
from frameport import cli
from frameport.core import library
calls = []
frame = SimpleNamespace(agent=lambda command, **kw: calls.append((command, kw)) or {})
monkeypatch.setattr(cli, "_target", lambda _: SimpleNamespace(connect=lambda: SimpleNamespace(frame=frame)))
result = CliRunner().invoke(cli.app, ["frame", "steam-library", mode])
assert result.exit_code == 0, result.output
assert library.setting("install.steam_library") == mode
assert calls == [("library_mode", {"mode": mode})]
def test_restart_steam_cli_confirmation(monkeypatch):
from types import SimpleNamespace
from typer.testing import CliRunner
from frameport import cli
calls = []
def agent(command, **kw):
calls.append(kw)
return {} if kw.get("confirm") else {"confirmation_required": True}
frame = SimpleNamespace(agent=agent)
monkeypatch.setattr(cli, "_target", lambda _: SimpleNamespace(connect=lambda: SimpleNamespace(frame=frame)))
result = CliRunner().invoke(cli.app, ["frame", "restart-steam"], input="n\n")
assert result.exit_code != 0 and calls == [{"confirm": False}]
calls.clear()
result = CliRunner().invoke(cli.app, ["frame", "restart-steam"], input="y\n")
assert result.exit_code == 0 and calls == [{"confirm": False}, {"confirm": True}]
+6 -36
View File
@@ -38,36 +38,8 @@ def test_quote_refuses_batch_injection(value):
native.quote(value)
def test_quote_leaves_globs_to_sftp():
"""Inside double quotes sftp escapes * ? [ itself: an extra backslash became part of the name (GitHub #324)."""
assert native.quote('a *?["b') == '"a *?[\\"b"'
assert native.quote("/x/te*s?t [ENG] \\b+(1).apk") == '"/x/te*s?t [ENG] \\\\b+(1).apk"'
def test_quote_windows_local_path_uses_forward_slashes():
"""Win32-OpenSSH turns a local path's backslashes into '/', escapes included ("C://Users", "/[ENG]")."""
path = r"C:\Users\user_name\AppData\Local\FramePort\output\All-In-One - Sports VR [ENG] v100+1.9.0 (x)\a.apk"
assert native.quote(path, windows=True) == (
'"C:/Users/user_name/AppData/Local/FramePort/output/All-In-One - Sports VR [ENG] v100+1.9.0 (x)/a.apk"')
assert native.quote(r"\\server\share\*?[a].apk", windows=True) == '"//server/share/*?[a].apk"'
assert native.quote('C:\\odd "name"\\a.apk', windows=True) == '"C:/odd \\"name\\"/a.apk"'
@pytest.mark.parametrize("os_name,expected", [("nt", '"C:/games/[ENG] a/x.apk"'),
("posix", '"C:\\\\games\\\\[ENG] a\\\\x.apk"')])
def test_quote_local_follows_the_platform(monkeypatch, os_name, expected):
monkeypatch.setattr(native.os, "name", os_name)
assert native.quote_local(r"C:\games\[ENG] a\x.apk") == expected
def test_batch_line_for_bracketed_folder(tmp_path, monkeypatch):
folder = tmp_path / "All-In-One - Sports VR [ENG] v100+1.9.0"
folder.mkdir()
frame, items, files, commands, processes = setup_batch(folder, monkeypatch)
monkeypatch.setattr(native.os, "name", "posix")
native.upload(frame, items, "/incoming", Reporter(), 20, 0, 1)
assert sorted(commands[0].splitlines()) == [f'put "{folder}/patch.obb" "/incoming/patch.obb.part"',
f'reput "{folder}/main.obb" "/incoming/main.obb.part"']
def test_quote_protects_spaces_quotes_globs():
assert native.quote('a *?["b') == '"a \\*\\?\\[\\"b"'
def test_size_lookup_does_not_hide_connection_errors():
@@ -93,11 +65,10 @@ def setup_batch(tmp_path, monkeypatch, code=0):
monitor.stat.side_effect = stat
monitor.remove.side_effect = lambda path: files.pop(path)
frame = SimpleNamespace(sftp=monitor, client=SimpleNamespace(open_sftp=lambda: monitor),
target=FrameTarget("paired"), run=Mock(return_value=(0, "", "")), modes_seen=[])
target=FrameTarget("paired"), run=Mock(return_value=(0, "", "")))
monkeypatch.setattr(native.shutil, "which", lambda _: "sftp")
@contextlib.contextmanager
def creds(frame, relaxed=False):
frame.modes_seen.append(relaxed)
def creds(frame):
yield ["-o", "StrictHostKeyChecking=yes"]
monkeypatch.setattr(native, "credentials", creds)
commands, processes = [], []
@@ -239,7 +210,7 @@ def setup_tar(tmp_path, monkeypatch, code=0):
path = tmp_path / "small.bin"
path.write_bytes(b"payload")
frame = SimpleNamespace(target=FrameTarget("paired.example", port=2222), modes_seen=[])
frame = SimpleNamespace(target=FrameTarget("paired.example", port=2222))
pipe = io.BytesIO()
pipe.close = lambda: None
process = Mock(stdin=pipe, returncode=code)
@@ -248,9 +219,8 @@ def setup_tar(tmp_path, monkeypatch, code=0):
monkeypatch.setattr(native.subprocess, "Popen", popen)
monkeypatch.setattr(native.shutil, "which", lambda _: "ssh")
@contextlib.contextmanager
def creds(frame, port_flag, relaxed=False):
def creds(frame, port_flag):
assert port_flag == "-p"
frame.modes_seen.append(relaxed)
yield ["-o", "StrictHostKeyChecking=yes", port_flag, "2222"]
monkeypatch.setattr(native, "credentials", creds)
return frame, [(path, "nested/small.bin")], process, popen, pipe
-340
View File
@@ -1,340 +0,0 @@
"""SSH keys beyond FramePort's own (GitHub #242): key files from Settings, the login a connection used, and OpenSSH
uploads that fall back to this PC's own keys/agent when the Frame refuses FramePort's key."""
import contextlib
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import Mock
import paramiko
import pytest
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import ed25519
from frameport.core import library
from frameport.core.events import Reporter
from frameport.frame import connection as C
from frameport.frame import native_upload as native
REFUSED = (b"debug1: Reading configuration data nul\r\n"
b"debug1: identity file C:/Temp/frameport-upload-x/key0 type 3\r\n"
b"debug1: Connecting to 10.0.0.2 [10.0.0.2] port 22.\r\n"
b"@ WARNING: UNPROTECTED PRIVATE KEY FILE! @\r\n"
b"debug1: Offering public key: C:/Temp/frameport-upload-x/key0 ED25519 SHA256:abc explicit\r\n"
b"debug1: Authentications that can continue: publickey,password\r\n"
b"debug1: kex: algorithm: curve25519-sha256\r\n"
b"steamos@10.0.0.2: Permission denied (publickey,password).\r\n")
@pytest.fixture(autouse=True)
def no_real_home_keys(tmp_path, monkeypatch):
"""Never read the real ~/.ssh (relaxed mode looks there)."""
empty = tmp_path / "empty-home"
empty.mkdir()
monkeypatch.setattr(native.Path, "home", lambda: empty)
def write_key(path: Path, password: bytes | None = None) -> Path:
enc = serialization.BestAvailableEncryption(password) if password else serialization.NoEncryption()
key = ed25519.Ed25519PrivateKey.generate()
path.write_bytes(key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.OpenSSH, enc))
path.with_name(path.name + ".pub").write_bytes(key.public_key().public_bytes(
serialization.Encoding.OpenSSH, serialization.PublicFormat.OpenSSH))
return path
# ------------------------------------------------------------------------------------------- key files
def test_key_file_validation(tmp_path):
good = write_key(tmp_path / "id_ed25519")
assert isinstance(C.load_key_file(good), paramiko.PKey)
with pytest.raises(C.KeyFileError, match="passphrase"):
C.load_key_file(write_key(tmp_path / "locked", b"secret"))
with pytest.raises(C.KeyFileError, match="public half"):
C.load_key_file(tmp_path / "id_ed25519.pub")
with pytest.raises(C.KeyFileError, match="not found"):
C.load_key_file(tmp_path / "missing")
(tmp_path / "notes.txt").write_text("hello")
with pytest.raises(C.KeyFileError, match="isn't a private SSH key"):
C.load_key_file(tmp_path / "notes.txt")
def test_extra_keys_come_from_settings_and_skip_unusable_ones(tmp_path):
good = write_key(tmp_path / "mine")
locked = write_key(tmp_path / "locked", b"secret")
library.set_setting(C.EXTRA_KEYS_SETTING, [str(good), str(good), str(locked), str(tmp_path / "gone"), "", 3])
assert C.extra_key_paths() == [good, locked, tmp_path / "gone"]
assert [path for path, _ in C.extra_keys()] == [good]
library.set_setting(C.EXTRA_KEYS_SETTING, str(good)) # a single path, e.g. edited by hand
assert C.extra_key_paths() == [good]
class _Client:
"""paramiko.SSHClient stand-in: accepts the key `accepted` (or the agent when accepted == "agent")."""
accepted = None
tried: list = []
def load_host_keys(self, path):
pass
def set_missing_host_key_policy(self, policy):
pass
def close(self):
pass
def save_host_keys(self, path):
pass
def get_transport(self):
return Mock()
def connect(self, pkey=None, password=None, allow_agent=False, look_for_keys=False, **kw):
kind = "password" if password else "agent" if allow_agent else pkey
_Client.tried.append(kind)
if kind != _Client.accepted:
raise paramiko.AuthenticationException("Authentication failed.")
@pytest.mark.parametrize("accepted,auth", [("app", "app_key"), ("user", "user_key"), ("agent", "agent")])
def test_connection_records_the_login_that_worked(monkeypatch, accepted, auth):
monkeypatch.setattr(C.paramiko, "SSHClient", _Client)
monkeypatch.setattr(C, "app_keys", lambda: ["app"])
monkeypatch.setattr(C, "extra_keys", lambda: [(Path("/k"), "user")])
monkeypatch.setattr(C.Frame, "run", lambda self, cmd: (0, "/home/steamos", ""))
_Client.accepted, _Client.tried = accepted, []
frame = C.Frame(C.FrameTarget("10.0.0.2")).connect()
assert frame.auth == auth
assert _Client.tried == ["app", "user", "agent"][:["app", "user", "agent"].index(accepted) + 1]
# ------------------------------------------------------------------------------------------- OpenSSH arguments
def frame_with_key():
key = SimpleNamespace(get_name=lambda: "ssh-ed25519", get_base64=lambda: "PAIRED_KEY")
client = SimpleNamespace(get_transport=lambda: SimpleNamespace(get_remote_server_key=lambda: key))
return C.Frame(C.FrameTarget("paired.example"), client=client)
def test_credentials_offer_own_and_settings_keys_strict_or_relaxed(tmp_path, monkeypatch):
own = tmp_path / "ssh"
own.mkdir()
write_key(own / "id_ed25519")
mine = write_key(tmp_path / "id_ed25519") # same file name as FramePort's: copies get their own names
monkeypatch.setattr(native, "ssh_dir", lambda: own)
library.set_setting(C.EXTRA_KEYS_SETTING, [str(mine)])
with native.credentials(frame_with_key()) as args:
copies = [Path(args[i + 1]) for i, a in enumerate(args) if a == "-i"]
assert [c.read_bytes() for c in copies] == [(own / "id_ed25519").read_bytes(), mine.read_bytes()]
assert "IdentitiesOnly=yes" in args and "BatchMode=yes" in args and "-v" in args
assert all(oct(c.stat().st_mode & 0o777) == "0o600" for c in copies)
assert not any(c.exists() for c in copies)
with native.credentials(frame_with_key(), relaxed=True) as args:
assert "IdentitiesOnly=yes" not in args and args.count("-i") == 2
assert "StrictHostKeyChecking=yes" in args # host key still pinned
def test_relaxed_credentials_work_without_any_key_file(tmp_path, monkeypatch):
monkeypatch.setattr(native, "ssh_dir", lambda: tmp_path)
with pytest.raises(OSError, match="no FramePort key"):
with native.credentials(frame_with_key()):
pass
with native.credentials(frame_with_key(), relaxed=True) as args:
assert "-i" not in args
def test_windows_sid_survives_a_non_ascii_user_name(monkeypatch):
out = '"desktop-1\\josé müller","S-1-5-21-1004336348-1177238915-682003330-1001"\r\n'.encode("cp850")
monkeypatch.setattr(native.subprocess, "check_output", lambda *a, **k: out)
assert native.current_sid() == "S-1-5-21-1004336348-1177238915-682003330-1001"
monkeypatch.setattr(native.subprocess, "check_output", lambda *a, **k: b"nothing")
with pytest.raises(OSError):
native.current_sid()
# ------------------------------------------------------------------------------------------- failures and modes
def test_failure_keeps_openssh_messages_and_key_lines():
exc = native.failure("OpenSSH SFTP", 255, REFUSED)
assert isinstance(exc, native.OpenSSHAuthFailed)
text = str(exc)
assert "UNPROTECTED PRIVATE KEY FILE" in text and "Offering public key" in text
assert "identity file" in text and "Permission denied (publickey,password)" in text
assert "kex: algorithm" not in text and "Reading configuration" not in text
other = native.failure("OpenSSH SFTP", 1, b"stat x: No such file or directory\n")
assert type(other) is OSError and "No such file" in str(other)
assert type(native.failure("OpenSSH tar", 255, b"ssh: connect to host x port 22: Connection timed out")) is OSError
@pytest.mark.parametrize("auth,known,modes", [("app_key", None, [False, True]), ("user_key", None, [False, True]),
("password", None, [False, True]), ("agent", None, [True]),
("app_key", True, [True]), ("agent", False, [False])])
def test_login_modes(auth, known, modes):
assert native.login_modes(SimpleNamespace(auth=auth, openssh_relaxed=known)) == modes
assert native.login_modes(SimpleNamespace()) == [False, True] # stand-ins without the fields
def sftp_setup(tmp_path, monkeypatch, refuse_strict=True, refuse_relaxed=False, auth="app_key"):
"""Two .part-less files; strict/relaxed logins refused as asked; returns the frame and the Popen calls."""
paths = [tmp_path / "main.obb", tmp_path / "patch.obb"]
for path in paths:
path.write_bytes(b"0123456789")
items = [(path, path.name, 10) for path in paths]
files = {}
monitor = Mock()
monitor.__enter__ = Mock(return_value=monitor)
monitor.__exit__ = Mock(return_value=False)
def stat(path):
if path not in files:
raise FileNotFoundError(path)
return SimpleNamespace(st_size=files[path])
monitor.stat.side_effect = stat
frame = SimpleNamespace(sftp=monitor, client=SimpleNamespace(open_sftp=lambda: monitor), auth=auth,
openssh_relaxed=None, target=C.FrameTarget("paired"), run=Mock(return_value=(0, "", "")))
monkeypatch.setattr(native.shutil, "which", lambda _: "sftp")
mode = {}
@contextlib.contextmanager
def creds(frame, port_flag="-P", relaxed=False):
mode["relaxed"] = relaxed
yield ["relaxed" if relaxed else "strict"]
monkeypatch.setattr(native, "credentials", creds)
calls = []
def popen(args, **kwargs):
relaxed = mode["relaxed"]
calls.append(relaxed)
refused = refuse_relaxed if relaxed else refuse_strict
if refused:
kwargs["stderr"].write(REFUSED)
code = 255
else:
for _, rel, size in items:
files["/incoming/" + rel + ".part"] = size
code = 0
process = Mock(returncode=code)
process.poll.return_value = code
return process
monkeypatch.setattr(native.subprocess, "Popen", popen)
return frame, items, calls
def test_refused_strict_login_retries_with_this_pcs_keys(tmp_path, monkeypatch):
frame, items, calls = sftp_setup(tmp_path, monkeypatch)
logs = []
reporter = Reporter()
reporter.log = lambda message, **k: logs.append(message)
assert native.upload(frame, items, "/incoming", reporter, 20, 0, 2) == 20
assert calls == [False, False, True, True] # both strict workers are refused, then both run relaxed
assert frame.openssh_relaxed is True
assert any("trying this PC's own SSH keys" in m and "UNPROTECTED" in m for m in logs)
assert native.login_modes(frame) == [True] # the next upload starts in the mode that worked
def test_agent_login_goes_straight_to_relaxed(tmp_path, monkeypatch):
frame, items, calls = sftp_setup(tmp_path, monkeypatch, auth="agent")
assert native.upload(frame, items, "/incoming", Reporter(), 20, 0, 1) == 20
assert calls == [True]
def test_refused_in_both_modes_raises_the_auth_failure(tmp_path, monkeypatch):
frame, items, calls = sftp_setup(tmp_path, monkeypatch, refuse_relaxed=True)
with pytest.raises(native.OpenSSHAuthFailed, match="Permission denied"):
native.upload(frame, items, "/incoming", Reporter(), 20, 0, 1)
assert calls == [False, True] and frame.openssh_relaxed is None
assert not frame.run.called # nothing promoted
def test_tar_retries_a_refused_login(tmp_path, monkeypatch):
path = tmp_path / "small.bin"
path.write_bytes(b"abc")
frame = SimpleNamespace(target=C.FrameTarget("paired"), auth="app_key", openssh_relaxed=None)
monkeypatch.setattr(native.shutil, "which", lambda _: "ssh")
mode = {}
@contextlib.contextmanager
def creds(frame, port_flag="-P", relaxed=False):
mode["relaxed"] = relaxed
yield []
monkeypatch.setattr(native, "credentials", creds)
class Pipe:
def write(self, data):
if not mode["relaxed"]:
raise BrokenPipeError(32, "Broken pipe") # ssh already exited
return len(data)
def flush(self):
pass
def close(self):
pass
calls = []
def popen(args, **kwargs):
calls.append(mode["relaxed"])
code = 0 if mode["relaxed"] else 255
if code:
kwargs["stderr"].write(REFUSED)
process = Mock(stdin=Pipe(), returncode=code)
process.poll.return_value = code
return process
monkeypatch.setattr(native.subprocess, "Popen", popen)
native.put_tar(frame, [(path, "small.bin")], "/incoming", Reporter(), Mock())
assert calls == [False, True] and frame.openssh_relaxed is True
def test_azure_ad_sid(monkeypatch):
out = b'"azuread\\jmueller","S-1-12-1-1234567890-1234567890-1234567890-1234567890"\r\n'
monkeypatch.setattr(native.subprocess, "check_output", lambda *a, **k: out)
assert native.current_sid() == "S-1-12-1-1234567890-1234567890-1234567890-1234567890"
def test_relaxed_mode_names_this_pcs_default_keys(tmp_path, monkeypatch):
"""OpenSSH skips its default keys once any -i is given, so relaxed mode names the ones Paramiko tries."""
home = tmp_path / "home"
(home / ".ssh").mkdir(parents=True)
rsa = home / ".ssh" / "id_rsa"
from cryptography.hazmat.primitives.asymmetric import rsa as rsa_keys
rsa.write_bytes(rsa_keys.generate_private_key(65537, 2048).private_bytes(
serialization.Encoding.PEM, serialization.PrivateFormat.OpenSSH, serialization.NoEncryption()))
write_key(home / ".ssh" / "id_ecdsa", b"secret") # passphrase: only usable through the agent
(home / ".ssh" / "id_ed25519").write_text("garbage")
monkeypatch.setattr(native.Path, "home", lambda: home)
own = tmp_path / "own"
own.mkdir()
write_key(own / "id_ed25519")
monkeypatch.setattr(native, "ssh_dir", lambda: own)
assert native.default_key_files() == [rsa]
assert native.key_files() == [own / "id_ed25519"]
assert native.key_files(relaxed=True) == [own / "id_ed25519", rsa]
library.set_setting(C.EXTRA_KEYS_SETTING, [str(rsa)]) # a default key also named in Settings: offered once
assert native.key_files(relaxed=True) == [own / "id_ed25519", rsa]
def test_add_remove_and_status_of_settings_keys(tmp_path):
good = write_key(tmp_path / "frame key")
with pytest.raises(C.KeyFileError, match="public half"):
C.add_extra_key(tmp_path / "frame key.pub")
with pytest.raises(C.KeyFileError, match="passphrase"):
C.add_extra_key(write_key(tmp_path / "locked", b"pw"))
assert C.add_extra_key(good) == good.resolve()
C.add_extra_key(good) # once only
assert C.extra_key_paths() == [good.resolve()]
good.unlink()
[(path, problem)] = C.extra_key_status()
assert path == good.resolve() and "not found" in problem
assert C.remove_extra_key(good) is True and C.remove_extra_key(good) is False
assert C.extra_key_paths() == []
def test_cli_ssh_keys(tmp_path):
from typer.testing import CliRunner
from frameport.cli import app
good = write_key(tmp_path / "mine")
run = CliRunner().invoke(app, ["frame", "ssh-keys", "--add", str(good)])
assert run.exit_code == 0 and f"added {good.resolve()}" in run.output
run = CliRunner().invoke(app, ["frame", "ssh-keys", "--add", str(tmp_path / "nope")])
assert run.exit_code == 1 and str(good.resolve()) in run.output
run = CliRunner().invoke(app, ["frame", "ssh-keys", "--remove", str(good.resolve())])
assert run.exit_code == 0 and "no extra keys" in run.output