"""Solver adapter: request-based Cloudflare clearance and Turnstile tokens. The solver is an external binary (cfsolve). It is optional: without one the client still works and simply reports the challenge. """ import json import os import shlex import shutil import subprocess import tempfile import time from dataclasses import dataclass _NO_WINDOW = 0x08000000 if os.name == "nt" else 0 _DEFAULT_COMMAND = [ "wsl", "-e", "bash", "-lc", 'cd ~/cfsolve && exec ./target/release/challenge "$@"', "challenge", ] _TIMEOUT = float(os.environ.get("MCP_SOLVER_TIMEOUT", "120")) class SolverError(RuntimeError): def __init__(self, code: str, message: str) -> None: super().__init__(message) self.code = code @dataclass(frozen=True, slots=True) class Clearance: cookies: dict[str, str] user_agent: str def command() -> list[str]: raw = os.environ.get("MCP_SOLVER", "").strip() if not raw: return list(_DEFAULT_COMMAND) if raw in {"off", "0", "false"}: return [] try: value = json.loads(raw) except json.JSONDecodeError: value = None if isinstance(value, list) and all(isinstance(part, str) for part in value): return list(value) return shlex.split(raw) def available(runner: list[str]) -> bool: if not runner: return False return shutil.which(runner[0]) is not None def _wsl(runner: list[str]) -> bool: return bool(runner) and runner[0].lower().endswith("wsl") def _work_dir(runner: list[str]) -> str: """Output directory the solver can actually write: a WSL path when it runs there.""" work = tempfile.mkdtemp(prefix="solve-") if not _wsl(runner): return work try: done = subprocess.run( ["wslpath", "-u", work], capture_output=True, text=True, timeout=15, check=True, stdin=subprocess.DEVNULL, creationflags=_NO_WINDOW, env={**os.environ, "WSL_UTF8": "1"}, ) except (OSError, subprocess.SubprocessError): return work return done.stdout.strip() or work def _cleanup(runner: list[str], work: str) -> None: if _wsl(runner): try: subprocess.run( [runner[0], "-e", "rm", "-rf", work], timeout=15, stdin=subprocess.DEVNULL, creationflags=_NO_WINDOW, env={**os.environ, "WSL_UTF8": "1"}, check=False, ) return except OSError: pass shutil.rmtree(work, ignore_errors=True) def _run(runner: list[str], page: str, extra: list[str]) -> str: work = _work_dir(runner) profile = os.environ.get("MCP_SOLVER_PROFILE", "profiles/safari-26-ios.json") args = [*runner, "--page", page, work, "--solve", "--fingerprint", profile, *extra] try: done = subprocess.run( args, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=_TIMEOUT, creationflags=_NO_WINDOW, stdin=subprocess.DEVNULL, env={**os.environ, "WSL_UTF8": "1"}, ) except subprocess.TimeoutExpired: raise SolverError("solver_timeout", f"Solver exceeded {_TIMEOUT:.0f}s.") from None except OSError as error: raise SolverError("solver_unavailable", f"Solver could not start: {error.strerror}.") from None finally: _cleanup(runner, work) lines = [line.strip() for line in done.stdout.splitlines() if line.strip()] if done.returncode != 0 or not lines: detail = _last_error(done.stderr) # A page that already answers 200 has no challenge to clear; the exit is # still usable, so mark it apart instead of as a hard failure. if "no .cf-turnstile container" in detail: raise SolverError("solver_warm", "The page answered without a challenge.") raise SolverError("solver_failed", detail) return lines[-1] def _cookies(text: str) -> dict[str, str]: cookies: dict[str, str] = {} for part in text.split(";"): name, _, value = part.strip().partition("=") if name: cookies[name] = value if "cf_clearance" not in cookies: # A widget page yields a token instead of a clearance; the exit is fine. raise SolverError("solver_warm", f"No clearance in solver output: {text[:120]}") return cookies def _last_error(stderr: str) -> str: lines = [line.strip() for line in stderr.splitlines() if line.strip()] return lines[-1][:300] if lines else "no diagnostic" def clearance(runner: list[str], url: str, user_agent: str, proxy: str | None = None) -> Clearance: """Solve a challenge page and return its cookies.""" extra = ["--proxy", proxy] if proxy else [] output = _run(runner, url, extra) return Clearance(_cookies(output), user_agent) def turnstile(runner: list[str], url: str, sitekey: str) -> str: token = _run(runner, url, ["--sitekey", sitekey]) if not token or token.startswith("Error"): raise SolverError("solver_failed", token[:200]) return token def sitekey(html: bytes) -> str | None: """First Turnstile sitekey in the markup, if a widget is embedded.""" import re match = re.search(rb'data-sitekey="(0x[0-9A-Za-z_-]{10,})"', html) if match: return match.group(1).decode() match = re.search(rb'sitekey["\']?\s*[:=]\s*["\'](0x[0-9A-Za-z_-]{10,})', html) return match.group(1).decode() if match else None def sleep_hint(seconds: float) -> None: time.sleep(seconds)