diff --git a/plugin/main.py b/plugin/main.py index 05238fd..fd390f6 100644 --- a/plugin/main.py +++ b/plugin/main.py @@ -83,6 +83,8 @@ async def _main(self): s["schema"] = 1 self._write_settings(s) decky.logger.info("Continue?: старт, данные в %s", DATA) + import reader_sandbox + decky.logger.info("Continue?: reader sandbox %s", reader_sandbox.status()) async def _unload(self): manager = getattr(self, "_standalone_media", None) @@ -140,6 +142,11 @@ def _steam_root(self): from ddsaves._common import deck_home return str(deck_home() / ".local/share/Steam") + def _theme_music_dir(self): + """Game Theme Music plugin cache; lives under the Steam user's homebrew, not necessarily /home/deck.""" + from ddsaves._common import deck_home + return str(deck_home() / "homebrew/data/SDH-GameThemeMusic/music") + async def ensure_blank_movie(self): """Положить assets/gh_no_startup.webm (0,2 с чёрного) в config/uioverrides/movies Steam; путь для настройки — /uioverrides/movies/gh_no_startup.webm (так его видит SteamClient.Customization.GetLocalStartupMovies).""" @@ -464,7 +471,7 @@ async def get_music_map(self): for appid, c in (self._hub_index().get("cards") or {}).items(): tid = (c.get("media") or {}).get("theme_id") if (isinstance(tid, str) and re.fullmatch(r"[A-Za-z0-9_-]{1,128}", tid) - and glob.glob(f"/home/deck/homebrew/data/SDH-GameThemeMusic/music/{glob.escape(tid)}.*")): + and glob.glob(f"{self._theme_music_dir()}/{glob.escape(tid)}.*")): out[appid] = tid return out @@ -474,7 +481,7 @@ async def get_music_files(self): return await asyncio.get_running_loop().run_in_executor(None, self._media().music_files) out = {} for appid, tid in (await self.get_music_map()).items(): - f = sorted(glob.glob(f"/home/deck/homebrew/data/SDH-GameThemeMusic/music/{glob.escape(tid)}.*")) + f = sorted(glob.glob(f"{self._theme_music_dir()}/{glob.escape(tid)}.*")) if f: out[appid] = os.path.basename(f[0]) return out @@ -608,6 +615,11 @@ async def set_lang(self, steam_lang): os.environ["CONTINUE_LANG"] = code return code + async def get_sandbox_status(self): + """Whether save readers run inside bubblewrap, and how often the sandbox fell back in-process.""" + import reader_sandbox + return reader_sandbox.status() + async def get_card(self, appid, name=""): appid = int(appid) hub = None if self._is_standalone() else (self._hub_index().get("cards") or {}).get(str(appid)) diff --git a/plugin/py_modules/ddsaves/_common.py b/plugin/py_modules/ddsaves/_common.py index 2186e4a..118bc94 100644 --- a/plugin/py_modules/ddsaves/_common.py +++ b/plugin/py_modules/ddsaves/_common.py @@ -290,9 +290,26 @@ def finish(out: Dict[str, Any], path: Path) -> Dict[str, Any]: def deck_home() -> Path: - """Домашняя папка Деки: Decky может запускать бэкенд от root (HOME=/root), а сейвы лежат у deck.""" + """Домашняя папка Деки: Decky может запускать бэкенд от root (HOME=/root), а сейвы лежат у deck. + + Desktop Linux (non-Deck): Decky still runs the backend as root, but the Steam user is not + ``deck``. Fall back to the invoking sudo user, then to the single ``/home/*`` account that owns + a Steam installation, and only then to ``$HOME``.""" + explicit = os.environ.get("CONTINUE_HOME") + if explicit: # set by reader_sandbox for its child, and by tests + return Path(explicit) if Path("/home/deck").is_dir(): return Path("/home/deck") + sudo_user = os.environ.get("SUDO_USER") + if sudo_user and sudo_user != "root" and Path("/home", sudo_user).is_dir(): + return Path("/home", sudo_user) + try: + owners = [h for h in Path("/home").iterdir() + if h.is_dir() and ((h / ".steam/steam/steamapps").is_dir() or (h / ".local/share/Steam/steamapps").is_dir())] + except OSError: + owners = [] + if len(owners) == 1: + return owners[0] return Path(os.environ.get("HOME") or "/home/deck") diff --git a/plugin/py_modules/deck_saves.py b/plugin/py_modules/deck_saves.py index f0810d9..07f0986 100644 --- a/plugin/py_modules/deck_saves.py +++ b/plugin/py_modules/deck_saves.py @@ -37,15 +37,16 @@ def inscryption(data_dir): # Та же копия, что в хабе (GameHub/ddsaves → py_modules/ddsaves, копирует deck_sync.py). Названия — только из данных # игр; прежние таблицы по памяти (царства Odyssey вперемешку, «Плато Начала», «Деревня персиковых цветов») удалены. +_CURRENT = {"appid": None} # appid of the card being read; lets the sandbox bind only that game's folders + + def _dd(slug, sub=""): - import importlib - try: - mod = importlib.import_module(f"ddsaves.{slug}") - except ModuleNotFoundError as e: # публичная сборка: недоказанных разборов в ней нет - if e.name == f"ddsaves.{slug}": - return None - raise - r = mod.read(None) + import reader_sandbox + r = reader_sandbox.read_card(slug, _CURRENT.get("appid")) # None: публичная сборка без этого разбора + if r is None: + return None + if r.get("error"): + raise RuntimeError(r["error"]) if not r.get("source_path"): return None observed = r.get("observed_at") @@ -152,6 +153,7 @@ def read(appid, data_dir): fn = READERS.get(int(appid)) if not fn: return None + _CURRENT["appid"] = int(appid) try: return fn(data_dir) except Exception as e: # битый сейв не должен ронять страницу игры diff --git a/plugin/py_modules/reader_sandbox.py b/plugin/py_modules/reader_sandbox.py new file mode 100644 index 0000000..61c7a64 --- /dev/null +++ b/plugin/py_modules/reader_sandbox.py @@ -0,0 +1,246 @@ +"""Run a ddsaves reader in a bubblewrap sandbox (Linux), in-process fallback elsewhere. + +Readers are plain Python modules; in-process they can do whatever the backend user can. +Here each read() runs in a short-lived child that sees only: + +- /usr (read-only) for the system Python and openssl, +- plugin/py_modules (read-only) for the reader code and its tables, +- the save locations this reader may legitimately use (read-only): Proton prefixes, Steam + userdata and the game's install folder for its appid(s), plus libraryfolders.vdf, +- an empty tmpfs /tmp, no network, no other home content, no write access to any of the above. + +The child prints one JSON card; this module validates its shape and size before it is used. +If bwrap or a system Python is missing, or the sandbox itself cannot start (user namespaces +disabled), the reader runs in-process exactly as before and status() says why. +""" +from __future__ import annotations +import ast +import importlib +import json +import os +import re +import shutil +import subprocess +from pathlib import Path +from typing import Any, Dict, List, Optional, Tuple + +from ddsaves import _common + +PY_MODULES = Path(__file__).resolve().parent +RUNNER = PY_MODULES / "reader_sandbox_runner.py" +SLUG = re.compile(r"[a-z][a-z0-9]*(?:_[a-z0-9]+)*") +APPID_NAME = re.compile(r"^APPIDS?(?:_[A-Z0-9]+)?$") +MAX_OUTPUT = 2 * 1024 * 1024 +MAX_STRING = 4096 +MAX_DEPTH = 6 +TIMEOUT = 10.0 +CARD_KEYS = {"place", "chapter", "objective", "progress", "facts", "proven", "unproven", + "observed_at", "source_path", "reason", "play_seconds", "fact_sources", "nonmonotonic"} + +_state: Dict[str, Any] = {"checked": False, "bwrap": None, "python": None, "reason": None, "fallbacks": 0} + + +def _probe() -> None: + if _state["checked"]: + return + _state["checked"] = True + if os.name == "nt": + _state["reason"] = "windows: no bubblewrap" + return + bwrap = shutil.which("bwrap") or ("/usr/bin/bwrap" if os.access("/usr/bin/bwrap", os.X_OK) else None) + if not bwrap: + _state["reason"] = "bwrap not installed" + return + python = next((p for p in ("/usr/bin/python3", shutil.which("python3")) if p and os.access(p, os.X_OK)), None) + if not python: + _state["reason"] = "no system python3 for the sandbox" + return + _state["bwrap"], _state["python"] = bwrap, python + + +def status() -> Dict[str, Any]: + _probe() + return {"sandboxed": bool(_state["bwrap"]), "bwrap": _state["bwrap"], "python": _state["python"], + "reason": _state["reason"], "fallbacks": _state["fallbacks"]} + + +def disable(reason: str) -> None: + """Fall back to in-process reads from now on (sandbox start failure).""" + _probe() + _state["bwrap"], _state["reason"] = None, reason + _state["fallbacks"] += 1 + + +def _module_file(slug: str) -> Optional[Path]: + if not SLUG.fullmatch(slug): + return None + path = PY_MODULES / "ddsaves" / f"{slug}.py" + return path if path.is_file() else None + + +def reader_appids(slug: str) -> List[int]: + """APPID constants declared by the reader and its sibling `_ag__reader.py`, parsed without importing.""" + out: List[int] = [] + files = [PY_MODULES / "ddsaves" / name for name in (f"{slug}.py", f"_ag_{slug}_reader.py", f"_{slug}_reader.py")] + for path in files: + if not path.is_file(): + continue + try: + tree = ast.parse(path.read_text(encoding="utf-8")) + except (SyntaxError, OSError, UnicodeDecodeError): + continue + for node in tree.body: + if not isinstance(node, ast.Assign): + continue + names = [t.id for t in node.targets if isinstance(t, ast.Name) and APPID_NAME.match(t.id)] + if not names: + continue + values = node.value.elts if isinstance(node.value, (ast.List, ast.Tuple, ast.Set)) else [node.value] + for v in values: + if isinstance(v, ast.Constant) and isinstance(v.value, int) and not isinstance(v.value, bool) and 0 < v.value < 2 ** 32: + out.append(v.value) + return sorted(set(out)) + + +def _installdir(appid: int) -> Optional[str]: + for lib in _common.steam_libraries(): + manifest = lib / "steamapps" / f"appmanifest_{appid}.acf" + try: + text = manifest.read_text(encoding="utf-8", errors="replace") + except OSError: + continue + m = re.search(r'"installdir"\s+"([^"\n]+)"', text) + if m: + return m.group(1) + return None + + +def bind_targets(appids: List[int]) -> Tuple[List[Path], List[Path]]: + """Directories and files the sandbox may read for these appids (existing ones only).""" + dirs: List[Path] = [] + files: List[Path] = [] + for appid in appids: + try: + dirs += [p for p in _common.proton_user(appid) if p.is_dir()] + dirs += [p for p in _common.steam_userdata(appid) if p.is_dir()] + inst = _installdir(appid) + if inst: + dirs += _common.game_dirs(inst) + except (ValueError, OSError): + continue + for root in _common.steam_roots(): + vdf = root / "steamapps/libraryfolders.vdf" + if vdf.is_file(): + files.append(vdf) + return _common._uniq(dirs), _common._uniq(files) + + +def sandbox_argv(argv: List[str], dirs: List[Path], files: List[Path], env: Dict[str, str]) -> List[str]: + _probe() + cmd = [_state["bwrap"], "--unshare-all", "--die-with-parent", "--new-session", "--clearenv", + "--ro-bind", "/usr", "/usr", "--symlink", "usr/lib", "/lib", "--symlink", "usr/lib64", "/lib64", + "--symlink", "usr/bin", "/bin", "--proc", "/proc", "--dev", "/dev", "--tmpfs", "/tmp", + "--ro-bind-try", "/etc/localtime", "/etc/localtime", # local time for save timestamps + "--ro-bind", str(PY_MODULES), str(PY_MODULES)] + for d in dirs: + cmd += ["--ro-bind", str(d), str(d)] + for f in files: + cmd += ["--ro-bind-try", str(f), str(f)] + for key, value in env.items(): + cmd += ["--setenv", key, value] + return cmd + ["--"] + argv + + +def sandbox_exec(argv: List[str], dirs: List[Path], files: List[Path], env: Dict[str, str], timeout: float = TIMEOUT) -> subprocess.CompletedProcess: + """Run argv inside the sandbox; raises OSError/TimeoutExpired like subprocess.run.""" + return subprocess.run(sandbox_argv(argv, dirs, files, env), capture_output=True, timeout=timeout, + stdin=subprocess.DEVNULL) + + +def _clean(value: Any, depth: int = 0) -> Any: + if depth > MAX_DEPTH: + return None + if isinstance(value, str): + return value[:MAX_STRING] + if isinstance(value, bool) or value is None: + return value + if isinstance(value, (int, float)): + return value if value == value and abs(value) < 1e18 else None + if isinstance(value, list): + return [_clean(v, depth + 1) for v in value[:512]] + if isinstance(value, dict): + return {str(k)[:128]: _clean(v, depth + 1) for k, v in list(value.items())[:256]} + return str(value)[:MAX_STRING] + + +def validate_card(raw: Any) -> Optional[Dict[str, Any]]: + """Shape-check a card that came from the child; unknown keys are dropped, texts are capped.""" + if not isinstance(raw, dict): + return None + card: Dict[str, Any] = {} + for key in ("place", "chapter", "objective", "source_path", "reason"): + v = raw.get(key) + card[key] = v[:MAX_STRING] if isinstance(v, str) else None + obs = raw.get("observed_at") + card["observed_at"] = float(obs) if isinstance(obs, (int, float)) and not isinstance(obs, bool) else None + play = raw.get("play_seconds") + card["play_seconds"] = float(play) if isinstance(play, (int, float)) and not isinstance(play, bool) else None + progress = raw.get("progress") + card["progress"] = _clean(progress) if isinstance(progress, dict) else {} + facts = [] + for f in raw.get("facts") or []: + if isinstance(f, dict): + facts.append({k: str(f.get(k, ""))[:MAX_STRING] for k in ("id", "icon", "label", "value")}) + card["facts"] = facts[:64] + for key in ("proven", "unproven"): + card[key] = [str(x)[:128] for x in (raw.get(key) or []) if isinstance(x, str)][:256] + for key in ("fact_sources", "nonmonotonic"): + v = raw.get(key) + if isinstance(v, dict): + card[key] = {str(k)[:128]: str(x)[:128] for k, x in list(v.items())[:128]} + return card + + +def _in_process(slug: str) -> Optional[Dict[str, Any]]: + mod = importlib.import_module(f"ddsaves.{slug}") + return mod.read(None) + + +def read_card(slug: str, appid: Optional[int] = None, lang: Optional[str] = None) -> Optional[Dict[str, Any]]: + """Card dict from the reader `ddsaves.`, sandboxed when possible. None when the reader is absent.""" + if _module_file(slug) is None: + return None + _probe() + if not _state["bwrap"]: + return _in_process(slug) + appids = reader_appids(slug) + if isinstance(appid, int) and not isinstance(appid, bool) and 0 < appid < 2 ** 32: + appids = sorted(set(appids) | {appid}) + dirs, files = bind_targets(appids) + home = str(_common.deck_home()) + env = {"HOME": home, "CONTINUE_HOME": home, "PATH": "/usr/bin:/bin", "LANG": "C.UTF-8", + "PYTHONDONTWRITEBYTECODE": "1", "CONTINUE_LANG": lang or os.environ.get("CONTINUE_LANG", "en")} + try: + proc = sandbox_exec([_state["python"], "-I", "-B", str(RUNNER), slug], dirs, files, env) + except subprocess.TimeoutExpired: + return {"error": f"reader timeout after {TIMEOUT:g}s (sandbox)"} + except OSError as error: + disable(f"bwrap could not start: {type(error).__name__}") + return _in_process(slug) + out = proc.stdout[:MAX_OUTPUT + 1] + if proc.returncode != 0 and not out.strip(): + err = proc.stderr.decode("utf-8", "replace").strip() + if err.startswith("bwrap:"): # the sandbox itself failed (no user namespaces, missing mount) -> fallback + disable(err.splitlines()[0][:200]) + return _in_process(slug) + return {"error": f"sandbox exit {proc.returncode}: {err[-300:]}"} + if len(out) > MAX_OUTPUT: + return {"error": "reader output exceeds the sandbox limit"} + try: + raw = json.loads(out.decode("utf-8", "replace") or "null") + except ValueError: + return {"error": "reader returned no JSON card"} + if isinstance(raw, dict) and isinstance(raw.get("error"), str) and len(raw) == 1: + return {"error": raw["error"][:300]} + card = validate_card(raw) + return card if card is not None else {"error": "reader returned no card"} diff --git a/plugin/py_modules/reader_sandbox_runner.py b/plugin/py_modules/reader_sandbox_runner.py new file mode 100644 index 0000000..fd0b071 --- /dev/null +++ b/plugin/py_modules/reader_sandbox_runner.py @@ -0,0 +1,35 @@ +"""Child side of reader_sandbox: import one ddsaves reader, run read(None), print one JSON card.""" +import json +import os +import re +import sys + +MAX_MEMORY = 512 * 1024 ** 2 + + +def main() -> int: + slug = sys.argv[1] if len(sys.argv) > 1 else "" + if not re.fullmatch(r"[a-z][a-z0-9]*(?:_[a-z0-9]+)*", slug): + sys.stdout.write(json.dumps({"error": "invalid reader slug"})) + return 2 + try: + import resource + resource.setrlimit(resource.RLIMIT_AS, (MAX_MEMORY, MAX_MEMORY)) + except (ImportError, OSError, ValueError): + pass + sys.dont_write_bytecode = True + sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + try: + import importlib + module = importlib.import_module(f"ddsaves.{slug}") + card = module.read(None) + payload = json.dumps(card, ensure_ascii=False, default=str, allow_nan=False) + except Exception as error: # the reader's failure is reported, never the traceback of the host + payload = json.dumps({"error": f"{type(error).__name__}: {error}"[:300]}) + sys.stdout.buffer.write(payload.encode("utf-8")) + sys.stdout.flush() + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/test_reader_sandbox.py b/tests/test_reader_sandbox.py new file mode 100644 index 0000000..e9dfc7b --- /dev/null +++ b/tests/test_reader_sandbox.py @@ -0,0 +1,134 @@ +"""reader_sandbox: appid discovery, card validation, and (where bubblewrap exists) real isolation.""" +from __future__ import annotations +import json +import os +import shutil +import sys +import tempfile +import types +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +PY_MODULES = ROOT / "plugin" / "py_modules" +sys.path.insert(0, str(PY_MODULES)) +sys.modules.setdefault("decky", types.SimpleNamespace(DECKY_PLUGIN_RUNTIME_DIR=tempfile.gettempdir(), logger=None)) + +import reader_sandbox # noqa: E402 + +HAVE_BWRAP = reader_sandbox.status()["sandboxed"] +PROBE_APPID = 4000000001 +PROBE_SUB = f"steamapps/compatdata/{PROBE_APPID}/pfx/drive_c/users/steamuser/AppData/LocalLow/Probe" +PROBE_READER = f'''"""Synthetic reader used only by the sandbox tests.""" +import json +from pathlib import Path +from ddsaves._common import empty, fact, finish, newest, proton_user +APPID = {PROBE_APPID} +def read(path_or_dir=None): + path = next((p for d in proton_user(APPID) for p in [newest(Path(d, "AppData/LocalLow/Probe").glob("*.json"))] if p), None) + if path is None: + return empty("no probe save") + try: + data = json.loads(path.read_text(encoding="utf-8")) + except (OSError, ValueError): + return empty("bad probe save") + return finish({{"place": None, "chapter": None, "objective": None, "progress": {{"day": data["day"]}}, + "facts": [fact("sun", "День", data["day"], id="day")], "proven": ["day"], "unproven": []}}, path) +''' + + +class StaticTests(unittest.TestCase): + def test_reader_appids_parsed_without_import(self): + self.assertEqual(reader_sandbox.reader_appids("hollow_knight"), [367520]) + self.assertEqual(reader_sandbox.reader_appids("silent_hill_2"), [2124490]) # declared in the sibling _ag_ reader too + self.assertEqual(reader_sandbox.reader_appids("no_such_reader"), []) + self.assertEqual(reader_sandbox.reader_appids("../etc"), []) + + def test_validate_card_caps_and_drops(self): + raw = {"place": "x" * 10000, "facts": [{"id": "day", "value": 5, "extra": 1}, "junk"], "proven": ["day", 3], + "progress": {"deep": {"a": {"b": {"c": {"d": {"e": {"f": {"g": 1}}}}}}}, "n": float("inf")}, + "observed_at": "nope", "unknown_key": 1} + card = reader_sandbox.validate_card(raw) + self.assertEqual(len(card["place"]), reader_sandbox.MAX_STRING) + self.assertEqual(card["facts"], [{"id": "day", "icon": "", "label": "", "value": "5"}]) + self.assertEqual(card["proven"], ["day"]) + self.assertIsNone(card["observed_at"]) + self.assertNotIn("unknown_key", card) + self.assertIsNone(card["progress"]["n"]) + self.assertIsNone(reader_sandbox.validate_card(["not", "a", "dict"])) + + def test_unknown_reader_is_none(self): + self.assertIsNone(reader_sandbox.read_card("no_such_reader", 1)) + self.assertIsNone(reader_sandbox.read_card("../../etc/passwd", 1)) + + +@unittest.skipUnless(HAVE_BWRAP, "bubblewrap not available") +class SandboxTests(unittest.TestCase): + def setUp(self): + self.tmp = Path(tempfile.mkdtemp(prefix="continue-sandbox-")) + self.home = self.tmp / "home" + (self.home / ".local/share/Steam/steamapps").mkdir(parents=True) + self.save_dir = self.home / ".local/share/Steam" / PROBE_SUB + self.save_dir.mkdir(parents=True) + (self.save_dir / "probe.json").write_text(json.dumps({"day": 42}), encoding="utf-8") + (self.home / ".ssh").mkdir() + (self.home / ".ssh/canary").write_text("secret", encoding="utf-8") + # a private py_modules copy with the probe reader, so no shipped game reader is needed + modules = self.tmp / "py_modules" + shutil.copytree(PY_MODULES / "ddsaves", modules / "ddsaves", ignore=shutil.ignore_patterns("__pycache__")) + shutil.copy2(PY_MODULES / "reader_sandbox_runner.py", modules / "reader_sandbox_runner.py") + (modules / "ddsaves/sandbox_probe.py").write_text(PROBE_READER, encoding="utf-8") + self._saved = (reader_sandbox.PY_MODULES, reader_sandbox.RUNNER, os.environ.get("CONTINUE_HOME")) + reader_sandbox.PY_MODULES, reader_sandbox.RUNNER = modules, modules / "reader_sandbox_runner.py" + os.environ["CONTINUE_HOME"] = str(self.home) + import ddsaves._common as common + common._LIBS = None # library cache must not leak between homes + + def tearDown(self): + reader_sandbox.PY_MODULES, reader_sandbox.RUNNER, old = self._saved + if old is None: + os.environ.pop("CONTINUE_HOME", None) + else: + os.environ["CONTINUE_HOME"] = old + shutil.rmtree(self.tmp, ignore_errors=True) + + def test_reader_runs_sandboxed_and_sees_only_its_save(self): + card = reader_sandbox.read_card("sandbox_probe", PROBE_APPID) + self.assertEqual(card["facts"][0]["value"], "42", card) + self.assertIn("day", card["proven"]) + self.assertTrue(card["source_path"].endswith("probe.json")) + self.assertEqual(reader_sandbox.status()["fallbacks"], 0) + + def test_child_has_no_network_home_or_write_access(self): + dirs, files = reader_sandbox.bind_targets([PROBE_APPID]) + probe = ( + "import os, socket, json\n" + "r = {}\n" + "r['home'] = sorted(os.listdir(os.environ['HOME']))\n" + "r['canary'] = os.path.exists(os.path.join(os.environ['HOME'], '.ssh', 'canary'))\n" + "try:\n socket.create_connection(('1.1.1.1', 53), timeout=1); r['net'] = 'open'\n" + "except OSError: r['net'] = 'blocked'\n" + "p = os.path.join(os.environ['HOME'], '.local/share/Steam/%s/x')\n" + "try:\n open(p, 'w'); r['write'] = 'allowed'\n" + "except OSError: r['write'] = 'blocked'\n" + "r['root'] = sorted(os.listdir('/'))\n" + "print(json.dumps(r))\n" % PROBE_SUB) + env = {"HOME": str(self.home), "PATH": "/usr/bin:/bin"} + proc = reader_sandbox.sandbox_exec([reader_sandbox.status()["python"], "-I", "-c", probe], dirs, files, env) + self.assertEqual(proc.returncode, 0, proc.stderr) + r = json.loads(proc.stdout) + self.assertEqual(r["home"], [".local"]) # only the bound Steam path exists, no .ssh + self.assertFalse(r["canary"]) + self.assertEqual(r["net"], "blocked") + self.assertEqual(r["write"], "blocked") + self.assertFalse({"root", "var", "opt", "srv", "boot"} & set(r["root"]), r["root"]) # /etc exists only as the localtime mount point + + def test_reader_error_is_reported_not_raised(self): + (self.save_dir / "probe.json").write_text("{not json", encoding="utf-8") + card = reader_sandbox.read_card("sandbox_probe", PROBE_APPID) + self.assertEqual(card["facts"], []) + self.assertIsNone(card["place"]) + + +if __name__ == "__main__": + unittest.main()