Python में HTTP2 Fingerprint: हर Client असल में क्या भेजता है

http2 fingerprint in python - HTTP2 Fingerprint in Python: What Each Client Really Sends

Python में अपना http2 fingerprint पढ़ने के लिए, उस कनेक्शन पर client के भेजे पहले frames record करें जिसे आप नियंत्रित करते हैं और उन्हें Akamai के सुझाए format में लिखें: भेजे गए क्रम में SETTINGS values, WINDOW_UPDATE increment, कोई भी PRIORITY frames और pseudo-headers का क्रम। Windows 11 पर, HTTP/2 चालू वाले httpx ने Chrome की string से अलग string भेजी, curl_cffi ने ठीक Chrome की string भेजी, और requests ने HTTP/2 बिल्कुल नहीं भेजा। नीचे recorder, नतीजे, Python का कोई option क्या बदल सकता है, और वह जगह है जहाँ CapSkip आता है: आपका client निकल जाने के बाद जो CAPTCHA आपको परोसा जाए, वह उसे हल करता है, और कोई frame कभी नहीं बदलता।

आपको क्या चाहिए

  • Python 3.10 या नया: capskip 1.8.0, h2 4.4.1, hpack 4.2.0, requests 2.34.2 और curl_cffi 0.17.0 सब python_requires में 3.10 घोषित करते हैं, जबकि httpx 0.28.1 3.8 और cryptography 50.0.2 3.9 घोषित करता है। मैंने हर Python ब्लॉक 3.11.7, 3.13.7 और 3.14.0 पर चलाया और 3.10 पर कोई नहीं।
  • एक virtual environment जिसमें नीचे के पैकेज हों।
  • listener चलाने वाली मशीन पर Chrome, ब्राउज़र माप के लिए। मेरी copy 157.0.8103.78 थी, नए headless mode में शुरू की गई।
  • सिर्फ़ आख़िरी step के लिए CapSkip 5.7.0, जैसा सेटअप गाइड बताती है वैसे Windows PC पर चलता हुआ। नीचे CapSkip का हर नतीजा in.php और res.php के उस mock से आया है जो मैंने उसके अपने port पर लिखा। मैंने असली app को कोई task नहीं भेजा और किसी असली साइट को भी नहीं।
  • CapSkip के लिए एक पता। Local mode उसे loopback पते पर रखता है, जिस तक सिर्फ़ वही PC पहुँच सकता है। Server mode एक नेटवर्क पते पर सुनता है ताकि दूसरी मशीनें API कॉल कर सकें, जैसा कि सेटअप गाइड के कनेक्शन सेटिंग्स सेक्शन में बताया गया है।
# In PowerShell, in a new empty folder
python -m venv .venv
.\.venv\Scripts\Activate.ps1
python -m pip install capskip "httpx[http2]" curl_cffi requests cryptography

इस गाइड के allow और block नियम मेरे हैं, जो किसी असली साइट के संभावित व्यवहार की जगह लिखे गए हैं। यहाँ कुछ भी नहीं कहता कि कोई असली vendor दिखाई गई किसी value पर block करता है। इन frames से पहले आने वाला TLS handshake एक अलग परत है, जिसे Python में TLS fingerprinting गाइड सँभालती है।

Step 1: कोई भी HTTP code चलने से पहले पहले frames record करें

HTTP library frames को parse करती है और उन्हें आपसे छिपाकर रखती है, इसलिए पहले bytes पढ़ें। string में pipe से जुड़े चार हिस्से हैं। पहला SETTINGS को भेजे गए क्रम में id:value जोड़ों के रूप में सूचीबद्ध करता है, दूसरा WINDOW_UPDATE increment है, तीसरा PRIORITY frames को stream:exclusive:depends-on:weight के रूप में सूचीबद्ध करता है, और चौथा pseudo-headers के पहले अक्षर भेजे गए क्रम में देता है। मैंने जिसका पालन किया वह है Akamai white paper, जो पहले तीन हिस्से परिभाषित करता है और चौथा जोड़ता है। paper गायब WINDOW_UPDATE के लिए 00 लिखता है, और मैं भी वही करता हूँ।

इस ब्लॉक को fp.py नाम से सेव करें।

# fp.py: read the first HTTP/2 frames of a connection and build an Akamai-style fingerprint.
from hpack import Decoder

PREFACE = b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n"


class Frames:
    """Feed it the raw bytes a client sends. It records and never answers."""

    def __init__(self):
        self.buf, self.ok = b"", None  # ok: did the 24 byte preface arrive?
        self.settings, self.update, self.priority = None, None, []
        self.names = None  # header names of the first request, in wire order
        self.block, self.decoder = b"", Decoder()

    def feed(self, data):
        self.buf += data
        if self.ok is None and len(self.buf) >= 24:
            self.ok = self.buf.startswith(PREFACE)
            self.buf = self.buf[24:]
        while self.ok and len(self.buf) >= 9:
            size, kind, flags = int.from_bytes(self.buf[:3], "big"), self.buf[3], self.buf[4]
            stream = int.from_bytes(self.buf[5:9], "big") & 0x7FFFFFFF
            if len(self.buf) < 9 + size:
                return
            body, self.buf = self.buf[9 : 9 + size], self.buf[9 + size :]
            self.frame(kind, flags, stream, body)

    def frame(self, kind, flags, stream, body):
        if self.names is not None:
            return  # only the frames before the first request count
        if kind == 4 and not flags & 1 and self.settings is None:  # SETTINGS, not an ack
            self.settings = [(int.from_bytes(body[i : i + 2], "big"), int.from_bytes(body[i + 2 : i + 6], "big")) for i in range(0, len(body), 6)]
        elif kind == 8 and stream == 0 and self.update is None:  # WINDOW_UPDATE on the connection
            self.update = int.from_bytes(body[:4], "big") & 0x7FFFFFFF
        elif kind == 2:  # PRIORITY: stream, exclusive bit, depends on, weight (the wire byte plus one)
            dep = int.from_bytes(body[:4], "big")
            self.priority.append((stream, dep >> 31, dep & 0x7FFFFFFF, body[4] + 1))
        elif kind == 1 or kind == 9:  # HEADERS, then CONTINUATION
            if kind == 1:
                if flags & 8:
                    body = body[1 : len(body) - body[0]]  # padding
                if flags & 0x20:  # a priority carried inside HEADERS is not part of the string
                    body = body[5:]
            self.block += body
            if flags & 4:  # END_HEADERS
                self.names = [n.decode("latin-1") for n, _ in self.decoder.decode(self.block, raw=True)]

    def akamai(self):
        s = ";".join("%d:%d" % kv for kv in self.settings or [])
        wu = "00" if self.update is None else str(self.update)  # the paper writes 00 for no frame
        p = ",".join("%d:%d:%d:%d" % t for t in self.priority) or "0"
        ps = ",".join(n[1] for n in self.names or [] if n.startswith(":"))
        return "|".join([s, wu, p, ps])

मैंने इसे paper से मिलाकर जाँचा। उसमें दर्ज frame sequences (Mac और Android पर Firefox 53, Chrome 58, Edge 14, OkHttp 3.6, एक Go client, curl 7.54 और nghttp2 1.22) को 7-byte chunks में replay करने पर छपी हुई आठों strings दोबारा बन गईं। इससे साबित होता है कि code paper का पालन करता है, यह नहीं कि मौजूदा clients अब भी वही frames भेजते हैं, जिसके लिए ये माप हैं।

listener site.py के लिए तीन ब्लॉक है, क्रम से। उसका नियम सिर्फ़ उस कनेक्शन को अंदर आने देता है जिसके frames step 2 में मापी गई Chrome string से मेल खाएँ, और path /fp वह दोहराता है जो कोई भी client भेजे।

# site.py (part 1 of 3): imports, the mock rule and the mock pages.
import datetime, ipaddress, json, os, pathlib, socket, ssl, threading
import h2.config, h2.connection, h2.events, h2.exceptions
from cryptography import x509
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.x509.oid import NameOID
from fp import Frames

PORT = 12860
# The mock rule: only a connection whose first frames match this string gets the page.
ALLOW = {"1:65536;2:0;4:6291456;6:262144|15663105|0|m,a,s,p"}
PAGE = '<form method="post" action="/login"><input name="email"><div class="g-recaptcha" data-sitekey="6LeMOCKMOCKMOCKMOCKMOCKMOCKMOCKMOCKMOCK0"></div></form>'
spent = set()  # tokens this site has already accepted


def make_cert():
    key = ec.generate_private_key(ec.SECP256R1())
    name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "localhost")])
    now = datetime.datetime.now(datetime.timezone.utc)
    cert = (x509.CertificateBuilder().subject_name(name).issuer_name(name).public_key(key.public_key())
            .serial_number(x509.random_serial_number()).not_valid_before(now - datetime.timedelta(minutes=5))
            .not_valid_after(now + datetime.timedelta(days=30))
            .add_extension(x509.SubjectAlternativeName([x509.DNSName("localhost"), x509.IPAddress(ipaddress.ip_address("127.0.0.1"))]), False)
            .add_extension(x509.BasicConstraints(ca=True, path_length=None), True)
            .add_extension(x509.KeyUsage(True, False, False, False, False, True, True, False, False), True)
            .sign(key, hashes.SHA256()))
    pathlib.Path("cert.pem").write_bytes(cert.public_bytes(serialization.Encoding.PEM))
    pathlib.Path("key.pem").write_bytes(key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.NoEncryption()))


def answer(method, path, headers, body, fp, names):
    """Return (status, content type, text). The rule runs first, except on /fp, which only echoes."""
    verdict = "ALLOWED" if fp in ALLOW else "BLOCKED"
    print(verdict, method, path, "|", fp, "|", " ".join(names), flush=True)
    if path == "/fp":
        return 200, "application/json", json.dumps({"fp": fp, "names": names})
    if verdict == "BLOCKED":
        return 403, "text/plain", ""
    if method == "GET" and path == "/signup":
        return 200, "text/html", PAGE
    if method == "POST" and path == "/login":
        if not headers.get("referer", "").startswith("https://127.0.0.1:%d/" % PORT):
            return 403, "text/plain", "no referer"
        token = dict(p.split("=", 1) for p in body.split("&") if "=" in p).get("g-recaptcha-response", "")
        if token and token not in spent:
            spent.add(token)
            return 200, "text/html", "<p>saved</p>"
        return 200, "text/html", "<p>captcha check failed</p>"
    return 404, "text/plain", ""
# site.py (part 2 of 3, same file): serve one connection over HTTP/2, or over HTTP/1.1 when the client asks for it.
def serve_h2(tls):
    frames = Frames()
    conn = h2.connection.H2Connection(h2.config.H2Configuration(client_side=False, header_encoding="utf-8"))
    conn.initiate_connection()
    tls.sendall(conn.data_to_send())
    reqs = {}
    while True:
        data = tls.recv(65535)
        if not data:
            return
        frames.feed(data)  # record first, then let the h2 package see the same bytes
        for ev in conn.receive_data(data):
            if isinstance(ev, h2.events.RequestReceived):
                reqs[ev.stream_id] = [dict(ev.headers), b"", [n for n, _ in ev.headers]]
            elif isinstance(ev, h2.events.DataReceived):
                reqs[ev.stream_id][1] += ev.data
                conn.acknowledge_received_data(ev.flow_controlled_length, ev.stream_id)
            elif isinstance(ev, h2.events.StreamEnded):
                headers, body, names = reqs[ev.stream_id]
                if ev.stream_id == 1:
                    names = frames.names  # the first request, straight from the wire
                status, ctype, text = answer(headers[":method"], headers[":path"], headers, body.decode(), frames.akamai(), names)
                raw = text.encode()
                conn.send_headers(ev.stream_id, [(":status", str(status)), ("content-type", ctype), ("content-length", str(len(raw)))])
                conn.send_data(ev.stream_id, raw, end_stream=True)
        tls.sendall(conn.data_to_send())


def serve_h1(tls):
    buf = b""
    while b"\r\n\r\n" not in buf:
        chunk = tls.recv(65535)
        if not chunk:
            return
        buf += chunk
    head, _, rest = buf.partition(b"\r\n\r\n")
    lines = head.decode("latin-1").split("\r\n")
    method, path, _ = lines[0].split(" ", 2)
    pairs = [l.split(":", 1) for l in lines[1:]]
    headers = {k.strip().lower(): v.strip() for k, v in pairs}
    while len(rest) < int(headers.get("content-length", 0)):
        rest += tls.recv(65535)
    status, ctype, text = answer(method, path, headers, rest.decode(), "http/1.1", [k.strip().lower() for k, _ in pairs])
    raw = text.encode()
    tls.sendall(("HTTP/1.1 %d X\r\ncontent-type: %s\r\ncontent-length: %d\r\nconnection: close\r\n\r\n" % (status, ctype, len(raw))).encode() + raw)
# site.py (part 3 of 3, same file): accept connections and start the listener.
def handle(sock):
    tls = None
    try:
        tls = CTX.wrap_socket(sock, server_side=True)
        (serve_h2 if tls.selected_alpn_protocol() == "h2" else serve_h1)(tls)
    except (OSError, ssl.SSLError, h2.exceptions.ProtocolError):
        pass
    finally:
        (tls or sock).close()


if __name__ == "__main__":
    if not os.path.exists("cert.pem"):
        make_cert()
    CTX = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
    CTX.load_cert_chain("cert.pem", "key.pem")
    CTX.set_alpn_protocols(["h2", "http/1.1"])
    server = socket.create_server(("127.0.0.1", PORT))
    print("listening on", PORT, flush=True)
    while True:
        threading.Thread(target=handle, args=(server.accept()[0],), daemon=True).start()

Step 2: हर client के साथ वही request भेजें

listener को एक विंडो में python site.py से शुरू करें। अगला ब्लॉक clients.py नाम से सेव करें और दूसरी में चलाएँ। हर client दस नए कनेक्शन बनाता है, इसलिए बदलता fingerprint एक से ज़्यादा अलग string के रूप में दिखेगा।

# clients.py: ten new connections per client to the mock site, then print what it recorded.
import ssl

import httpx
import requests
from curl_cffi import requests as curl

URL = "https://127.0.0.1:12860/fp"
CA = "cert.pem"  # the certificate site.py wrote
CTX = ssl.create_default_context(cafile=CA)  # httpx 0.28.1 warns about verify given as a path


def httpx_h2():
    with httpx.Client(http2=True, verify=CTX) as c:  # http2=True needs the h2 package
        return c.get(URL)


clients = {
    "requests": lambda: requests.get(URL, verify=CA),
    "httpx, http2=True": httpx_h2,
    "curl_cffi, impersonate=chrome": lambda: curl.get(URL, impersonate="chrome", verify=CA),
}
for name, send in clients.items():
    seen = [send().json() for _ in range(10)]
    distinct = {s["fp"] for s in seen}
    print(name.ljust(32), len(distinct), "distinct in 10", seen[0]["fp"])
    print(" " * 32, "headers:", " ".join(seen[0]["names"]))

Chrome के लिए, listener को उसके output के सेव होने के साथ चलता रखें: पहली विंडो में python site.py > frames.txt। नीचे का ब्लॉक, दूसरी PowerShell विंडो में, Chrome को हर बार नई profile के साथ आठ बार शुरू करता है और path /fp के लिए अलग-अलग strings गिनता है।

# Eight separate Chrome starts against the listener, then a count of the strings it saw.
$chrome = "C:\Program Files\Google\Chrome\Application\chrome.exe"
1..8 | ForEach-Object {
  $dir = Join-Path $env:TEMP "h2fp-profile-$_"  # a new profile each time
  $p = Start-Process $chrome -ArgumentList "--headless=new", "--ignore-certificate-errors", "--user-data-dir=$dir", "https://127.0.0.1:12860/fp" -PassThru
  Start-Sleep -Seconds 6
  taskkill /PID $p.Id /T /F 2>$null | Out-Null
}
$seen = Get-Content frames.txt | Where-Object { $_ -match " /fp \|" } | ForEach-Object { ($_ -split " \| ")[1] }
"{0} requests, {1} distinct string(s)" -f $seen.Count, ($seen | Sort-Object -Unique).Count

हर client ने अपने दस कनेक्शन में एक string दी (Windows 11, Python 3.11.7, 3.13.7 और 3.14.0 में एक जैसा)। Chrome ने आठ शुरुआतों में एक string दी, एक header क्रम के साथ।

# What the listener recorded (Windows 11, Python 3.14.0)
requests 2.34.2                 no HTTP/2: an HTTP/1.1 request
httpx 0.28.1, http2=True        1:4096;2:0;4:65535;5:16384;3:100;6:65536|16777216|0|m,a,s,p
curl_cffi 0.17.0, chrome        1:65536;2:0;4:6291456;6:262144|15663105|0|m,a,s,p
Chrome 157.0.8103.78, headless  1:65536;2:0;4:6291456;6:262144|15663105|0|m,a,s,p

चार बातें ध्यान खींचती हैं। पहली, requests ने कभी h2 माँगा ही नहीं, इसलिए मेरे listener ने HTTP/1.1 पर जवाब दिया और fingerprint करने को कोई frame नहीं है। दूसरी, http2=True वाला httpx अपने SETTINGS और WINDOW_UPDATE में Chrome से अलग है: 65536 के सामने 4096 की header table, 6291456 के सामने 65535 की initial window, 262144 के सामने 65536 की header list limit, एक maximum frame size और एक stream limit जिन्हें Chrome छोड़ देता है, और 15663105 के सामने 16777216 का WINDOW_UPDATE। तीसरी, impersonate को chrome पर सेट करके curl_cffi ने ठीक Chrome 157 की string भेजी, और उसके headers Chrome की page request के क्रम में थे, सिवाय अंत में एक अतिरिक्त cache-control के।

चौथी, string एक brand नहीं, एक build को बताती है। Edge 158.0.4370.33 और Playwright के Chromium 159.0.8154.6 ने Chrome 157 की string भेजी। Playwright के Chromium 145.0.7632.6 और 147.0.7727.15 ने पाँचवीं setting जोड़ी जिसकी id GREASE के आकार की थी (हर दूसरा hex digit a) और जिसकी value हर कनेक्शन पर बदली, तीन captures में तीन अलग जोड़े। मेरा exact-string नियम उन दोनों builds को ठुकरा देता। उसी Chrome ने अपनी favicon request के headers को page request से अलग क्रम में भी रखा, तीन में से तीन शुरुआतों में, इसलिए header क्रम client के साथ-साथ request के type का भी होता है।

Step 3: Python का कोई option कौन सी values बदल सकता है

हर client एक अलग परत तक पहुँचता है। मैंने एक बार में एक option बदला और listener पर नतीजा पढ़ा (Python 3.14.0, requests 2.34.2, httpx 0.28.1, curl_cffi 0.17.0 अपने bundled curl-impersonate 2.3.1 के साथ)। requests के लिए, headers साफ़ किए गए session ने मेरा दिया क्रम रखा, सिवाय इसके कि urllib3 ने host और accept-encoding आगे जोड़ दिए, और जब मेरी सूची में user-agent नहीं था तो उसे भी।

# What each client lets you change (httpx 0.28.1, curl_cffi 0.17.0)
part of the string         httpx                                      curl_cffi
HTTP version               http2=True, with the h2 package            http_version, or the profile
SETTINGS, WINDOW_UPDATE    no option that I found                     the profile, or the akamai string
PRIORITY frames            none sent                                  none sent, even from my akamai string
pseudo-header order        always m,a,s,p                             the profile, or the akamai string
header order               yes, if the list has accept-encoding       set by the profile

curl_cffi की profiles बराबर ताज़ा नहीं हैं, इसलिए profile की तुलना उस browser से करें जिसकी आप नक़ल कर रहे हैं। listener ने उन profiles के लिए ये strings record कीं जो मैंने आज़माईं, और Edge 158 ने Chrome की string भेजी, edge profile वाली नहीं।

# curl_cffi 0.17.0 profiles as the listener recorded them (Python 3.14.0)
edge (edge101)        1:65536;3:1000;4:6291456;6:262144|15663105|0|m,a,s,p
firefox (firefox155)  1:65536;2:0;4:131072;5:16384|12517377|0|m,p,a,s
safari (safari270)    2:0;3:100;4:2097152;9:1|10420225|0|m,s,a,p

Firefox profile में कोई PRIORITY frames नहीं हैं, जबकि paper वाले Firefox 53 ने पाँच भेजे, और मैंने कोई live Firefox capture नहीं किया जो बताए कि मौजूदा वाला क्या भेजता है। akamai argument खुद string लेता है। paper की Firefox 53 string के साथ और बिना किसी profile के, listener ने settings, WINDOW_UPDATE और pseudo-header क्रम जैसा दिया गया वैसा ही record किया, लेकिन पाँच PRIORITY frames 0 बनकर लौटे, इसलिए यह build string के उस हिस्से को अनदेखा करता है। impersonate chrome जोड़ने पर वही string मिली और यह warning आई: Akamai fingerprint was altered after impersonated version was set. बिना किसी impersonate के भी curl_cffi ने Chrome की string भेजी, और उसकी low-level Curl class ने भी, इसलिए default bundled libcurl में बैठा है।

httpx में SETTINGS और WINDOW_UPDATE वाली पंक्तियों के लिए कोई option नहीं है, क्योंकि httpcore उन्हें लिखता है। अगला ब्लॉक एक private httpcore method को ऐसे method से बदल देता है जो Chrome की values भेजता है। यह httpcore 1.0.9 पर चला।

# chrome_h2.py: give httpx the Chrome connection start. This replaces a private httpcore method.
import collections
import ssl

import h2.settings
import httpcore._sync.http2 as http2
import httpx
from h2.settings import SettingCodes as S


def chrome_init(self, request):
    settings = h2.settings.Settings(client=True, initial_values={
        S.HEADER_TABLE_SIZE: 65536, S.ENABLE_PUSH: 0, S.INITIAL_WINDOW_SIZE: 6291456, S.MAX_HEADER_LIST_SIZE: 262144})
    del settings[S.MAX_FRAME_SIZE], settings[S.ENABLE_CONNECT_PROTOCOL]  # Chrome sends neither
    self._h2_state.local_settings = settings
    self._h2_state.initiate_connection()
    self._h2_state.decoder.max_allowed_table_size = 65536  # the table size we just announced
    self._h2_state.increment_flow_control_window(15663105)  # the Chrome WINDOW_UPDATE
    self._write_outgoing_data(request)
    # httpcore wants a stream limit afterwards, and Chrome does not send one
    settings._settings[S.MAX_CONCURRENT_STREAMS] = collections.deque([100])


http2.HTTP2Connection._send_connection_init = chrome_init

if __name__ == "__main__":
    with httpx.Client(http2=True, verify=ssl.create_default_context(cafile="cert.pem")) as client:
        seen = client.get("https://127.0.0.1:12860/fp").json()
    print(seen["fp"])

इसके साथ, httpx ने ठीक Chrome की string भेजी। decoder line के बिना पहला response httpx की LocalProtocolError के साथ फेल हुआ, जो कहती थी कि encoder ने maximum table size पार कर दी, क्योंकि मेरे listener ने वह 65536 table इस्तेमाल की जिसकी patch ने घोषणा की थी। Chrome के headers, accept-encoding सहित, को Client के headers argument के रूप में पास करने से Chrome का header क्रम दोबारा बन गया। patch को सीखने का तरीका समझें, dependency नहीं: यह एक private method बदलता है, h2 के internals को छूता है, सिर्फ़ synchronous client को ढकता है और किसी भी release में टूट सकता है।

Step 4: जो client पास हो, उसी से block, solve और submit करें

अब नियम CapSkip से मिलता है। मेरी साइट हर उस कनेक्शन को ठुकराती है जिसकी string Chrome की string से अलग हो, इसलिए पेज, solve और फ़ॉर्म पोस्ट सब impersonate के chrome पर सेट एक curl_cffi session से जाते हैं। पहला ब्लॉक sitekey को उस पेज के widget div की data-sitekey attribute से खोजता है जो इस session ने अभी fetch किया। script से बनाए गए widget के लिए दूसरा तरीका चाहिए जिसे मैंने परखा नहीं। कोई library अपने आप फ़ॉर्म पोस्ट पर Referer नहीं भेजती, इसलिए helper एक सेट करता है, क्योंकि मेरा mock Referer के बिना फ़ॉर्म पोस्ट ठुकराता है। timeout constructor का है: recaptcha को timeout पास करने पर मेरे रन में TypeError आई, इसलिए ब्लॉक recaptchaTimeout सेट करता है। मेरे mock पेज की sitekey नकली है, इसलिए इसे असली CapSkip के सामने चलाने से पहले SITE को ऐसे पेज पर रखें जिसे आप test कर सकते हैं।

# signup.py (part 1 of 2): one passing client for the page, the solve and the form post.
import os
import re
import ssl
import sys
import time

import httpx
from curl_cffi import requests as curl
from capskip import ApiException, CapSkip, NetworkException, TimeoutException, ValidationException

SITE = os.environ.get("SITE", "https://127.0.0.1:12860")
# CapSkip listens on 8080 by default. In Server mode, use the address of that machine as host.
solver = CapSkip(host="127.0.0.1", port=int(os.environ.get("CAPSKIP_PORT", "8080")), recaptchaTimeout=120)
# The same client carries the page, and later the form post.
# verify=cert.pem trusts only the mock listener: drop it for a site with a real certificate.
client = curl.Session(impersonate="chrome", verify="cert.pem")


def read_sitekey():
    page = client.get(SITE + "/signup")
    if page.status_code == 403 and not page.text:
        raise RuntimeError("blocked before any HTML: check the connection first")
    found = re.search(r"data-sitekey=[\"']([^\"']+)[\"']", page.text)
    if not found:
        raise RuntimeError("no data-sitekey on the page (HTTP %d)" % page.status_code)
    return found.group(1)


def submit(sender, token):
    # a browser sends Referer on a form post, and neither library adds it for you
    return sender.post(SITE + "/login", data={"email": "[email protected]", "g-recaptcha-response": token},
                       headers={"referer": SITE + "/signup"})
# signup.py (part 2 of 2, same file): read the sitekey, solve once, post right away.
try:
    sitekey = read_sitekey()
    started = time.time()
    result = solver.recaptcha(sitekey, SITE + "/signup")
    print("token of %d characters after %.1f s" % (len(result["code"]), time.time() - started))
    if os.environ.get("TRY_FIRST") == "httpx":  # the wrong way, to see what the rule does
        with httpx.Client(http2=True, verify=ssl.create_default_context(cafile="cert.pem")) as plain:
            wrong = submit(plain, result["code"])
        print("httpx form post:", wrong.status_code, repr(wrong.text))
    reply = submit(client, result["code"])
    print("curl_cffi form post:", reply.status_code, reply.text)
except ValidationException as err:
    print("refused before sending:", err)
    sys.exit(1)
except ApiException as err:
    print("CapSkip answered:", err)
    sys.exit(1)
except TimeoutException as err:
    print("no token in time:", err)
    sys.exit(1)
except NetworkException as err:
    print("CapSkip not reachable:", err)
    sys.exit(1)
except RuntimeError as err:
    print("failed:", err)
    sys.exit(1)
# PowerShell: run the flow once, then once with the form post tried through httpx first
python signup.py
$env:TRY_FIRST = "httpx"
python signup.py

signup.py का Part 2 CapSkip से एक token माँगता है और उसे तुरंत इस्तेमाल करता है। कॉल capskip 1.8.0 की recaptcha(sitekey, url) है। यह एक dict लौटाती है जिसका token इसके नीचे रहता है: result["code"], और वह value g-recaptcha-response field में जाती है।

मेरा CapSkip का mock 2 सेकंड के solve पर सेट था। कॉल ने Python 3.11.7, 3.13.7 और 3.14.0 में से हर एक पर 3.8 सेकंड बाद 128 characters का token लौटाया, क्योंकि SDK बढ़ते अंतराल पर poll करता है। curl_cffi से फ़ॉर्म पोस्ट को HTTP 200 मिला और मेरी साइट ने उसे सेव किया। TRY_FIRST सेट होने पर, httpx से फ़ॉर्म पोस्ट को 403 और खाली body मिली, क्योंकि मेरा नियम फ़ॉर्म पढ़ने से पहले कनेक्शन को ठुकरा देता है। मेरे mock ने token खर्च नहीं किया था, इसलिए उसके बाद के curl_cffi फ़ॉर्म पोस्ट ने उसे सेव कर दिया। असली साइट token को हर उस फ़ॉर्म पोस्ट के बाद इस्तेमाल हुआ मान सकती है जो उस तक पहुँचे, इसीलिए solve सबसे आख़िर में आता है।

मैंने SDK को एक ऐसा mock भी दिया जो कभी जवाब नहीं देता। 4 के recaptchaTimeout ने 7.76 सेकंड बाद TimeoutException पर और 12 के ने 12.76 बाद खत्म किया, क्योंकि deadline की तुलना clock से हर sleep के बाद ही होती है। जो parameter reCAPTCHA v2 नहीं लेता, जैसे userAgent, कुछ भी भेजे जाने से पहले ValidationException के साथ ठुकरा दिया जाता है। SDK अपने कनेक्शन पर सादे HTTP/1.1 से CapSkip तक पहुँचता है, जो फ़ॉर्म पोस्ट के frames को कभी नहीं छूता।

FAQ

क्या CapSkip मेरी script के भेजे frames बदलता है?

नहीं। CapSkip CAPTCHA widget पर काम करता है और एक token लौटाता है, और आपका client कनेक्शन कैसे खोलता है उसमें उसका कोई हिस्सा नहीं है। फ़ॉर्म पोस्ट के frames सिर्फ़ आपके client के हैं।

क्या CapSkip मेरी script से अलग मशीन पर चल सकता है?

हाँ, Server mode में। तब आपके नियंत्रण वाली Windows मशीन दूसरी मशीनों के लिए API का जवाब देती है, और आपकी script उस मशीन को host के रूप में पास करती है। Server mode शुरू करने से port किसी भी पते के लिए पहुँच में भी रह जाता है, इसलिए संकरा allow rule कुछ हासिल नहीं करता। जिस हर range पर आप भरोसा नहीं करते उसके लिए Windows Firewall का block rule लगाकर उसे घेरें, क्योंकि Windows Firewall block rules को पहले लागू करता है, जो मैंने यहाँ test नहीं किया, और port को अपने router पर बंद रखें। मेरे रनों में कोई दूसरी मशीन शामिल नहीं थी।

कनेक्शन की मेल खाती शुरुआत क्या ठीक नहीं करती?

आपका IP address, जिसे कैप्चा सॉल्वर प्रॉक्सी गाइड कवर करती है, और connection शुरू होने के बाद आपकी script क्या करती है। खाली 403, जो मेरा mock लौटाता है, किसी भी पेज के बनने से पहले का इनकार है, इसलिए CapSkip के solve करने के लिए वहाँ कोई widget नहीं है। CAPTCHA या ब्लॉक गाइड बताती है कि उसे challenge से कैसे अलग पहचानें। मैंने कोई TLS capture नहीं किया, कोई live Firefox या Safari नहीं चलाया और कोई असली साइट नहीं परखी।

जब आपके connection की शुरुआत पास हो जाए और साइट कोई widget दिखाए, तो फ़्लैट लाइसेंस पर आपके अपने PC पर चलने वाला कैप्चा सॉल्वर उसे token में बदल देता है, और ठुकराए गए फ़ॉर्म पोस्ट पर कुछ सेकंड लगते हैं, प्रति-solve कोई शुल्क नहीं। Python में reCAPTCHA v2 गाइड उस solve को विस्तार से कवर करती है। आपका PC हर type के लिए वही कॉल चलाता है, और Python कैप्चा सॉल्वर पेज उन types की सूची देता है जिन्हें वह support करता है।