Files
omar 5d36fddd30
ci / static (push) Failing after 27s
ci / test-3.12 (push) Skipped
ci / test-3.13 (push) Skipped
ci / image (push) Skipped
ci / smoke (push) Skipped
ci / publish (push) Skipped
Add fetch MCP server with proxy routing, challenge solving and failure reports
Live reads go through an operator proxy pool (round-robin over the newest 100
entries, cooling on connect failures, no direct fallback); stored clearances are
replayed only on the exit that earned them. Identity, clearance, solver and
Turnstile rungs escalate automatically. fetch_pages reads up to 12 URLs four at
a time with per-item isolation. report/reports/reports_update keep a durable
queue of unreadable pages for the operator.

Ships a pinned multi-stage image (non-root 10001, data in /data), an ordered CI
with static gates, tests on 3.12 and 3.13 at 85% coverage, an offline image
smoke, and sha/latest publishing gated on main.
2026-11-28 19:29:46 +03:00

106 lines
3.7 KiB
Python

"""Browser identity that requests and clearance replay must share.
The identity comes from the solver's own profile so the TLS handshake, the
User-Agent and the stored cookies are one coherent browser. Cloudflare binds
clearance to the exact UA and IP, so a mixed identity silently fails.
"""
import json
import os
import subprocess
from dataclasses import dataclass
from pathlib import Path
from curl_cffi.requests.impersonate import DEFAULT_CHROME, DEFAULT_SAFARI, DEFAULT_SAFARI_IOS
_DEFAULT_PROFILE = "profiles/safari-26-ios.json"
_NO_WINDOW = 0x08000000 if os.name == "nt" else 0
# curl only accepts concrete targets, never the bare family name.
_TARGETS = {"safari": DEFAULT_SAFARI, "safari_ios": DEFAULT_SAFARI_IOS, "chrome": DEFAULT_CHROME}
_FALLBACK = (
"Mozilla/5.0 (iPhone; CPU iPhone OS 18_7 like Mac OS X) AppleWebKit/605.1.15 "
"(KHTML, like Gecko) Version/26.6.3 Mobile/15E148 Safari/604.1"
)
_NAVIGATION = (
"sec-fetch-dest: document",
"user-agent",
"accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"sec-fetch-site: none",
"sec-fetch-mode: navigate",
"accept-language: en-US,en;q=0.9",
"accept-encoding: gzip, deflate, br, zstd",
)
@dataclass(frozen=True, slots=True)
class Identity:
user_agent: str
tls: str
headers: tuple[str, ...]
def as_headers(self) -> dict[str, str]:
"""Ordered headers with the UA filled in and duplicates dropped."""
result: dict[str, str] = {}
for line in self.headers:
if line == "user-agent":
result["user-agent"] = self.user_agent
continue
name, _, value = line.partition(": ")
result[name.lower()] = value
return result
def _tls_for(profile: str) -> str:
override = os.environ.get("MCP_TLS_PROFILE", "").strip()
if override:
return override
lowered = profile.lower()
engine = lowered.partition("-")[0].partition("_")[0]
if "ios" in lowered or "iphone" in lowered:
return DEFAULT_SAFARI_IOS
return _TARGETS.get(engine, DEFAULT_SAFARI_IOS)
def _from_profile(raw: str) -> Identity:
data = json.loads(raw)
transport = data["transport"]
user_agent = transport["headers"]["User-Agent"]
navigation = transport["requests"]["headers"]["navigation"]
tls = _tls_for(str(transport.get("profile", "safari_ios")))
return Identity(user_agent=user_agent, tls=tls, headers=tuple(navigation))
def _read_profile(runner: list[str], path: str) -> str:
"""Read the profile file; a WSL runner needs a plain `cat`, not the solver."""
if runner and runner[0].lower().endswith("wsl"):
done = subprocess.run(
[runner[0], "-e", "bash", "-lc", 'cat "$@"', "cat", path],
capture_output=True,
text=True,
encoding="utf-8",
timeout=20,
check=True,
env={**os.environ, "WSL_UTF8": "1"},
stdin=subprocess.DEVNULL,
creationflags=_NO_WINDOW,
)
return done.stdout
return Path(path).read_text("utf-8")
def load(runner: list[str] | None) -> Identity:
"""Read the solver profile once; fall back to a built-in Safari iOS identity."""
path = os.environ.get("MCP_SOLVER_PROFILE", _DEFAULT_PROFILE)
try:
return _from_profile(_read_profile(runner or [], path))
except (OSError, subprocess.SubprocessError, ValueError, KeyError, TypeError):
return Identity(user_agent=_FALLBACK, tls=_tls_for(path), headers=_NAVIGATION)
DEFAULT = Identity(user_agent=_FALLBACK, tls=_tls_for("safari_ios"), headers=_NAVIGATION)
def fallback() -> Identity:
"""Identity used when no solver profile can be read."""
return DEFAULT