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.
101 lines
3.4 KiB
Python
101 lines
3.4 KiB
Python
"""Short-lived clearance cookies, bound to host and the exit that earned them.
|
|
|
|
cf_clearance is only valid from the IP and User-Agent that earned it, so the
|
|
entry keeps the proxy URL that produced it and replay is pinned there. Values
|
|
live in a JSON file so a restart does not force a new solve.
|
|
"""
|
|
|
|
import json
|
|
import os
|
|
import threading
|
|
from dataclasses import dataclass
|
|
from pathlib import Path
|
|
from time import time
|
|
|
|
_TTL = min(max(float(os.environ.get("MCP_CLEARANCE_TTL", "1800")), 60.0), 14400.0)
|
|
_FILE = Path(os.environ.get("MCP_CLEARANCE_FILE", Path(__file__).with_name(".clearance.json")))
|
|
|
|
|
|
@dataclass(frozen=True, slots=True)
|
|
class Entry:
|
|
cookies: dict[str, str]
|
|
proxy: str | None
|
|
expires: float
|
|
|
|
def header(self) -> str:
|
|
return "; ".join(f"{name}={value}" for name, value in self.cookies.items())
|
|
|
|
|
|
class Store:
|
|
def __init__(self, path: Path = _FILE) -> None:
|
|
self._path = path
|
|
self._lock = threading.Lock()
|
|
self._data: dict[str, Entry] = self._load()
|
|
|
|
def _load(self) -> dict[str, Entry]:
|
|
try:
|
|
raw = json.loads(self._path.read_text("utf-8"))
|
|
except (OSError, ValueError):
|
|
return {}
|
|
now = time()
|
|
|
|
def read(host: str, value: object) -> tuple[str, Entry] | None:
|
|
if not isinstance(value, dict) or not isinstance(value.get("cookies"), dict):
|
|
return None
|
|
try:
|
|
expires = float(value.get("expires", 0))
|
|
cookies = {str(k): str(v) for k, v in value["cookies"].items()}
|
|
except (TypeError, ValueError, AttributeError):
|
|
return None
|
|
entry = Entry(cookies, value.get("proxy"), expires)
|
|
return (host, entry) if entry.expires > now else None
|
|
|
|
data: dict[str, Entry] = {}
|
|
for host, value in raw.items() if isinstance(raw, dict) else ():
|
|
kept = read(host, value)
|
|
if kept:
|
|
data[kept[0]] = kept[1]
|
|
return data
|
|
|
|
def _save(self) -> None:
|
|
now = time()
|
|
self._data = {host: entry for host, entry in self._data.items() if entry.expires > now}
|
|
temporary = self._path.with_suffix(".tmp")
|
|
try:
|
|
temporary.write_text(
|
|
json.dumps(
|
|
{
|
|
host: {"cookies": entry.cookies, "proxy": entry.proxy, "expires": entry.expires}
|
|
for host, entry in self._data.items()
|
|
}
|
|
),
|
|
"utf-8",
|
|
)
|
|
os.replace(temporary, self._path)
|
|
except OSError:
|
|
pass
|
|
|
|
def lookup(self, host: str) -> tuple[str | None, str | None]:
|
|
"""Proxy to pin and the Cookie header for ``host``, or Nones."""
|
|
with self._lock:
|
|
entry = self._data.get(host)
|
|
if entry is None or entry.expires <= time():
|
|
return None, None
|
|
return entry.proxy, entry.header()
|
|
|
|
def put(self, host: str, proxy: str | None, cookies: dict[str, str]) -> None:
|
|
if not cookies:
|
|
return
|
|
with self._lock:
|
|
self._data[host] = Entry(dict(cookies), proxy, time() + _TTL)
|
|
self._save()
|
|
|
|
def drop(self, host: str) -> None:
|
|
with self._lock:
|
|
if self._data.pop(host, None) is not None:
|
|
self._save()
|
|
|
|
def __len__(self) -> int:
|
|
with self._lock:
|
|
return len(self._data)
|