#!/usr/bin/env python3 """Client for a local Cloudflare Turnstile solver sidecar. Sidecar contract (see /openapi.json on your solver): GET /health POST /solve {"type":"turnstile","sitekey":"0x...","url":"","real_page":true,"timeout_s":180} → {"token": ""} real_page=True is REQUIRED for apiclaw.biz — tokens solved against a blank page are rejected server-side (siteverify binds the token to the live page). Usage: python turnstile_client.py [sitekey] (sitekey omitted → fetched from https://apiclaw.biz/public/auth-config) """ import json import os import sys import urllib.request SIDECAR = os.environ.get("SIDECAR_URL", "http://127.0.0.1:8877").rstrip("/") BASE = os.environ.get("APICLAW_BASE", "https://apiclaw.biz").rstrip("/") def _post(path: str, payload: dict, timeout: int = 240) -> dict: req = urllib.request.Request(SIDECAR + path, data=json.dumps(payload).encode(), method="POST", headers={"Content-Type": "application/json"}) with urllib.request.urlopen(req, timeout=timeout) as r: return json.loads(r.read().decode()) def fetch_sitekey() -> str: with urllib.request.urlopen(BASE + "/public/auth-config", timeout=30) as r: cfg = json.loads(r.read().decode()) def find(o): if isinstance(o, dict): for k, v in o.items(): if "site" in k.lower() and isinstance(v, str) and v.startswith("0x"): return v r = find(v) if r: return r elif isinstance(o, list): for v in o: r = find(v) if r: return r return None key = find(cfg) if not key: raise RuntimeError("sitekey not found in auth-config") return key def solve(page_url: str, sitekey: str | None = None, timeout_s: int = 180) -> str: sitekey = sitekey or fetch_sitekey() d = _post("/solve", {"type": "turnstile", "sitekey": sitekey, "url": page_url, "real_page": True, "timeout_s": timeout_s}, timeout=timeout_s + 30) tok = d.get("token") or d.get("solution") or "" if not tok: raise RuntimeError(f"no token in sidecar response: {json.dumps(d)[:200]}") return tok if __name__ == "__main__": if len(sys.argv) < 2: print(__doc__) sys.exit(1) url = sys.argv[1] sk = sys.argv[2] if len(sys.argv) > 2 else None print(solve(url, sk))