"""A fake Mac for luoke-scan's `--fixture` mode: a folder (home/, tmp/, ...) and the fakes.json beside it. The layout and the keys of fakes.json are luoke-scan's (its internal/core/fixture.go); nothing is imported from it. """ from __future__ import annotations import datetime import json import os import random UTC = datetime.timezone.utc LOCAL = datetime.timezone(datetime.timedelta(hours=8)) T0 = datetime.datetime(2026, 10, 20, 12, 0, tzinfo=UTC) # the fake Macs' "now" def iso(t: datetime.datetime) -> str: return t.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ") def ago(**kw) -> datetime.datetime: return T0 - datetime.timedelta(**kw) def quiet_fakes() -> dict: """A Mac with nothing wrong (the keys are the ones luoke-scan's Fakes reads; every key is written).""" return { "version": 1, "processes": [{"pid": 400, "ppid": 1, "uid": os.getuid(), "path": "/Applications/Safari.app/Contents/MacOS/Safari", "started": iso(ago(days=1))}], "launchdPIDs": [], "commands": [ {"tool": "/usr/bin/defaults", "args": ["autoLoginUser"], "status": 1, "output": ""}, {"tool": "/usr/bin/defaults", "args": ["GuestEnabled"], "status": 0, "output": "0\n"}, {"tool": "/usr/bin/defaults", "args": ["DiscoverableMode"], "status": 0, "output": "Contacts Only\n"}, {"tool": "/bin/launchctl", "args": [], "status": 0, "output": "disabled services = {\n\t\"com.openssh.sshd\" => disabled\n}\n"}, {"tool": "/usr/bin/security", "args": [], "status": 1, "output": "SecTrustSettings: No Trust Settings were found.\n"}, {"tool": "/usr/bin/fdesetup", "args": [], "status": 0, "output": "FileVault is On.\n"}, {"tool": "/usr/libexec/ApplicationFirewall/socketfilterfw", "args": [], "status": 0, "output": "Firewall is enabled. (State = 1)\n"}, {"tool": "/usr/bin/csrutil", "args": [], "status": 0, "output": "System Integrity Protection status: enabled.\n"}, {"tool": "/usr/sbin/spctl", "args": [], "status": 0, "output": "assessments enabled\n"}, {"tool": "/bin/sh", "args": [], "status": 0, "output": "sysadminctl[1:2] screenLock delay is immediate\n"}, ], "otherCommands": {"status": 0, "output": "1\n"}, "bootTime": iso(ago(days=3)), "pendingUpdates": 0, "xprotectUpdated": iso(ago(days=3)), "signatures": [], "otherSignature": "developer:FIXTURE000", "eventTaps": [], "snapshots": [], "appleSilicon": True, "running": [], "commandLines": [], "attachedImages": [], "crontab": "", "installedCommands": [], "volume": None, "staleFiles": [], "downloaded": [], "appsAdded": {}, "codesign": {}, "appTrust": {}, "onBattery": False, "lowPower": False, "memoryPressure": 1, "vitals": {"cpu": {}, "sampleSeconds": 3, "footprint": {}, "memTotal": 16 * 1024 ** 3, "pressure": 1, "swap": 0, "battery": None, "batteryUnknown": False, "thermal": [0, 0]}, } class Fixture: """One fake Mac. Paths: `~/...` under the fake home, `$TMPDIR/...` under the fake temporary folder, anything else under the root (`Applications/...`, `opt-homebrew/...`).""" def __init__(self, root: str, user: str, rng: random.Random): os.makedirs(root) self.root = os.path.realpath(root) self.user = user self.home, self.tmp = os.path.join(self.root, "home"), os.path.join(self.root, "tmp") for d in (self.home, self.tmp, os.path.join(self.home, "Projects")): os.makedirs(d) letters = "bcdfghjklmnpqrstvwxyz0123456789_" self.tmp_shown = "/private/var/folders/" + "".join(rng.choice(letters) for _ in range(2)) + "/" + \ "".join(rng.choice(letters) for _ in range(30)) + "/T" self.fakes = quiet_fakes() def p(self, rel: str) -> str: if rel == "~" or rel.startswith("~/"): return os.path.join(self.home, rel[2:]) if rel != "~" else self.home if rel.startswith("$TMPDIR/"): return os.path.join(self.tmp, rel[len("$TMPDIR/"):]) return rel if os.path.isabs(rel) else os.path.join(self.root, rel) def file(self, rel: str, text: str = "", mode: int | None = None) -> str: path = self.p(rel) os.makedirs(os.path.dirname(path), exist_ok=True) with open(path, "w", encoding="utf-8") as f: f.write(text) if mode is not None: os.chmod(path, mode) return path def program(self, rel: str) -> str: """A program that exists (the rules ask the file system whether a process's program is still there).""" path = self.p(rel) return path if os.path.exists(path) else self.file(rel, "#!/bin/sh\nexit 0\n", 0o755) def shown(self, text: str) -> str: """`text` as the model (and anyone reading the set) sees it: the fake Mac's folders under the names they stand for. Nothing of where the fake Mac was built is left.""" roots = [self.root] if self.root.startswith("/private/"): roots.append(self.root[len("/private"):]) for root in roots: for sub, name in (("home", "/Users/" + self.user), ("tmp", self.tmp_shown), ("opt-homebrew", "/opt/homebrew"), ("usr-local", "/usr/local"), ("Applications", "/Applications")): text = text.replace(os.path.join(root, sub), name) for root in roots: if root in text: raise ValueError(f"a path outside the fake Mac's named folders would be shown: {text[:200]}") return text def save(self) -> None: with open(os.path.join(self.root, "fakes.json"), "w", encoding="utf-8") as f: json.dump(self.fakes, f, ensure_ascii=False, indent=1)