# scan.py - sweep of every script this handle (maxime-fleury) has shipped, across all its returns. # Part 1 runs the platform's own detector (src/lib/files.ts portabilityNotes, ported line for line) so the # server's judgment is the control. Part 2 is a wider scan for the same class the user named: anything a # script sends to stdout that is not a function of its input. import io, json, os, re, sys, time, urllib.request, urllib.error S = "https://solveathome.org" H = {"Authorization": "Bearer " + os.environ["SAH"], "X-Model": "deepseek-v4.1-flash", "X-Session": "266d9746eb765060ee1faaa9", "Accept": "application/json"} # ---------------------------------------------------------------- platform detector (verbatim port) SCRIPT_EXT = {"js", "mjs", "cjs", "ts", "py", "sh", "c", "h", "cpp", "rs", "go", "java", "jl", "r", "sql", "lean"} STDOUT_PRINT = re.compile(r"(console\.log|process\.stdout\.write|\bprint\s*\(|\bprintf?\b|\becho\b|\bputs\b|println!?\s*\(|System\.out\.print|fmt\.Print|@printf|\bcat\b)") PROGRESS_WORDS = re.compile(r"(elapsed|\btook\b|time\.time\(|perf_counter|monotonic\(|Date\.now|performance\.now|hrtime|Instant::now|time\.Now\(|datetime\.now|wall[- ]?clock|\bprogress[:=]|per second|\bit/s\b|[\d}]\s*/s(?=[\s\"'`)\],]|$)|%\s*(done|complete)|\btick(s|ing)?\b|throughput|\brate[:=]\s*[\d{$(]|\bremaining[:=]?\s*[\d{$(])", re.I) ETA = re.compile(r"\bETA\b") LITERAL_ONLY = re.compile(r"(console\.log|process\.stdout\.write|\bprint|\bputs|println!?|System\.out\.print(ln)?|fmt\.Print(ln)?)\s*\(\s*(['\"])(?:(?!\3)[^\\\n]|\\.)*\3\s*\)\s*;?\s*(//.*|#.*)?$") RNG_CALL = { "js": re.compile(r"Math\.random\s*\("), "mjs": re.compile(r"Math\.random\s*\("), "cjs": re.compile(r"Math\.random\s*\("), "ts": re.compile(r"Math\.random\s*\("), "py": re.compile(r"\b(random\.(random|randint|randrange|choice|choices|sample|shuffle|uniform|gauss)|np\.random\.(rand|randn|randint|random|choice|shuffle|permutation|uniform|normal)|numpy\.random\.\w+)\s*\("), "go": re.compile(r"\brand\.(Int|Intn|Int63|Float64|Perm|Shuffle)\s*\("), "rs": re.compile(r"\b(thread_rng|rand::random)\s*\("), "jl": re.compile(r"\brand(n)?\s*\("), } RNG_SEEDED = re.compile(r"(random\.seed\s*\(|Random\s*\(\s*\d|np\.random\.seed\s*\(|default_rng\s*\(\s*[^)\s]|RandomState\s*\(\s*\d|rand\.Seed\s*\(|rand\.New\s*\(|seed_from_u64|from_seed|StdRng|Random\.seed!|MersenneTwister\s*\(\s*\d|mulberry32|splitmix|xorshift|xoshiro|\bseed\b)", re.I) COMMENT = re.compile(r"^\s*(//|#|/\*|\*)") HOME_PATH = re.compile(r"(?:^|[\s\"'(=:])((?:/Users|/home|C:\\Users)[/\\][A-Za-z0-9._-]+[/\\][^\s\"')]{0,80})") def platform_notes(name, content): ext = (str(name or "").split(".")[-1] or "").lower() notes = [] m = HOME_PATH.search(content or "") if m: line = content[:m.start()].count("\n") + 1 notes.append(("home-path", line, m.group(1)[:70], "carries a hard-coded home directory")) if ext not in SCRIPT_EXT: return notes lines = (content or "").split("\n") prints = False for i, l in enumerate(lines): if COMMENT.match(l): continue to_stdout = bool(STDOUT_PRINT.search(l)) and not re.search(r"stderr|console\.error|>&2|file=sys\.stderr|eprint", l) prints = prints or to_stdout if to_stdout and (PROGRESS_WORDS.search(l) or ETA.search(l)) and not LITERAL_ONLY.search(l): notes.append(("progress/timing-to-stdout", i + 1, l.strip()[:80], "prints what looks like progress or timing to stdout")) break rng = RNG_CALL.get(ext) if rng and prints and not RNG_SEEDED.search(content or ""): at = next((i for i, l in enumerate(lines) if not COMMENT.match(l) and rng.search(l)), -1) if at >= 0: notes.append(("unseeded-rng-to-stdout", at + 1, lines[at].strip()[:80], "draws unseeded random numbers and prints to stdout")) return notes # ---------------------------------------------------------------- wider scan (my own class definition) # Any stdout-producing statement whose text is not a function of the input. TIMER = re.compile(r"(time\.time\(|perf_counter|monotonic\(|Date\.now|performance\.now|hrtime|Instant::now|time\.Now\(|datetime\.(now|utcnow)|clock\(\)|getrusage|\btimeit\b|new Date\(|\bdate\b\s*\+|\$\(date\)|`date`)") HOSTY = re.compile(r"(process\.memoryUsage|memoryUsage\(\)|psutil|memory_info|max_rss|resource\.getrusage|/proc/self/status|os\.getpid\(\)|platform\.node\(|socket\.gethostname|os\.uname|sys\.platform|platform\.platform|sys\.version|\bnproc\b|os\.cpu_count|\blscpu\b|Get-CimInstance)") ABS_PATH = re.compile(r"([A-Za-z]:\\\\|[A-Za-z]:/|/tmp/|/var/tmp|/opt/|\\\\\\\\)") PATHY_PRINT = re.compile(r"(os\.getcwd|__file__|os\.path\.dirname|os\.path\.abspath|process\.cwd|__dirname|realpath|abspath|sys\.argv\[0\]|Path\(__file__)") ORDER = re.compile(r"(os\.listdir|glob\.glob|\bglob\(|os\.walk|set\(|\.set\(\)|frozenset|os\.scandir|opendir|readdir)") STDOUTISH = re.compile(r"(console\.log|console\.info|console\.debug|console\.table|console\.dir|process\.stdout\.write|sys\.stdout\.write|sys\.stdout\.print|\bprint\s*\(|\bprintf?\b|\becho\b|\bputs\b|println!?\s*\(|System\.out\.print|fmt\.Print|@printf|\bcat\b)") NOT_STDOUT = re.compile(r"(stderr|console\.error|console\.warn|>&2|file=sys\.stderr|eprint|2>\s*&1)") def line_prints(line): return bool(STDOUTISH.search(line)) and not NOT_STDOUT.search(line) def wider(name, content): """Returns findings the platform detector does not report: (cat, line, snippet, why).""" ext = (str(name or "").split(".")[-1] or "").lower() out = [] for i, l in enumerate((content or "").split("\n"), 1): if COMMENT.match(l): continue if ABS_PATH.search(l) and not line_prints(l): m = ABS_PATH.search(l) out.append(("abs-path-literal", i, l.strip()[:90], "hard-codes an absolute path (%s); the platform's home-path check only looks at /Users, /home and C:\\Users" % m.group(1))) if not line_prints(l): continue if TIMER.search(l) and not LITERAL_ONLY.search(l): out.append(("timer-to-stdout", i, l.strip()[:90], "prints a wall-clock or timer value")) if HOSTY.search(l) and not LITERAL_ONLY.search(l): out.append(("host-or-memory-to-stdout", i, l.strip()[:90], "prints a host, memory or process figure")) if PATHY_PRINT.search(l) and not LITERAL_ONLY.search(l): out.append(("cwd-or-file-to-stdout", i, l.strip()[:90], "prints the working directory or the script's own path")) if ORDER.search(l) and not LITERAL_ONLY.search(l) and not re.search(r"sorted\s*\(", l): out.append(("order-to-stdout", i, l.strip()[:90], "prints set or filesystem iteration order, which is not stable across runs or machines")) if ext == "sh" and re.search(r"\$\(date\)|`date`|\bhostname\b|\buname\b|\bwhoami\b", l): out.append(("shell-environment-to-stdout", i, l.strip()[:90], "prints a clock, host or user value")) return out # ---------------------------------------------------------------- gather and run def fetch(sha, cache="cache"): os.makedirs(cache, exist_ok=True) p = os.path.join(cache, sha) if os.path.exists(p): return io.open(p, encoding="utf-8", errors="replace").read() for _ in range(3): try: r = urllib.request.urlopen(urllib.request.Request(S + "/files/" + sha, headers=H), timeout=90) t = r.read().decode("utf-8", "replace") io.open(p, "w", encoding="utf-8").write(t) return t except Exception as e: time.sleep(2) return None returns = json.load(io.open("returns.json", encoding="utf-8")) idx = {} for rid, r in returns.items(): for f in r["files"]: d = idx.setdefault(f["sha256"], {"names": set(), "returns": set()}) d["names"].add(f["name"]) d["returns"].add(rid) scripts = {sha: v for sha, v in idx.items() if any((n.split(".")[-1] or "").lower() in SCRIPT_EXT for n in v["names"])} print("returns:", len(returns), "| distinct files:", len(idx), "| distinct scripts:", len(scripts)) print() rows, miss = [], 0 for sha, v in sorted(scripts.items(), key=lambda kv: sorted(kv[1]["returns"])[0], reverse=True): name = sorted(v["names"])[0] c = fetch(sha) if c is None: miss += 1 print("FETCH FAIL", sha[:12], name) continue pn = platform_notes(name, c) wn = wider(name, c) recorded = [] for rid in v["returns"]: for note in (returns[rid]["file_notes"] or []): if note.get("sha") == sha: recorded += note.get("notes", []) rows.append({"sha": sha, "name": name, "ext": name.split(".")[-1].lower(), "bytes": len(c), "returns": sorted(v["returns"], key=int), "platform": pn, "wider": wn, "server_recorded": recorded, "lines": len(c.split("\n"))}) io.open("scan.json", "w", encoding="utf-8").write(json.dumps(rows, indent=1)) print("fetched %d scripts (failures %d)" % (len(rows), miss)) print() print("=== A. platform detector ===") for r in rows: if r["platform"]: print(" %s (r#%s) %s" % (r["name"], ",".join(r["returns"]), r["sha"][:12])) for cat, ln, snip, why in r["platform"]: print(" L%-5d %-24s %s" % (ln, cat, why)) print(" %s" % snip) print(" flagged files: %d ; server recorded notes on %d of them" % (sum(1 for r in rows if r["platform"]), sum(1 for r in rows if r["server_recorded"]))) print() print("=== B. wider scan (findings the platform detector does not report) ===") bycat = {} for r in rows: if r["wider"]: print(" %s (r#%s) %s" % (r["name"], ",".join(r["returns"]), r["sha"][:12])) for cat, ln, snip, why in r["wider"]: bycat[cat] = bycat.get(cat, 0) + 1 print(" L%-5d %-28s %s" % (ln, cat, snip)) print() print("files with wider findings: %d ; by category: %s" % (sum(1 for r in rows if r["wider"]), json.dumps(bycat)))