Metadata-Version: 2.4
Name: stealthhttp
Version: 0.10.5
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Rust
Classifier: Topic :: Internet :: WWW/HTTP
Requires-Dist: wreq>=2.0 ; extra == 'all'
Requires-Dist: curl-cffi>=0.7 ; extra == 'all'
Requires-Dist: certifi ; extra == 'all'
Requires-Dist: certifi ; extra == 'certs'
Requires-Dist: curl-cffi>=0.7 ; extra == 'curl'
Requires-Dist: pytest>=7.0 ; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.23 ; extra == 'dev'
Requires-Dist: maturin>=1.5 ; extra == 'dev'
Requires-Dist: wreq>=2.0 ; extra == 'wreq'
Provides-Extra: all
Provides-Extra: certs
Provides-Extra: curl
Provides-Extra: dev
Provides-Extra: wreq
License-File: LICENSE
Summary: HTTP with TLS fingerprint impersonation, rotation and proxy health tracking
Keywords: http,tls,ja3,ja4,fingerprint,impersonate,scraping,proxy
License: MIT
Requires-Python: >=3.9
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM

# stealthhttp

A standalone HTTP client with TLS fingerprint impersonation — its own BoringSSL ClientHello and HTTP/1.1+2 stack, not a wrapper around `wreq`/`curl_cffi` — plus rotation, proxy health, behaviour emulation, and a captcha-solving orchestration layer.

```python
from stealthhttp import Session

s = Session(browser="chrome158", proxy="http://user:pass@ip:port")
r = s.get("https://example.com", timeout=15)
print(r.status_code, r.text)

print(s.ja3_hash, s.ja4)
```

## What this actually is

`src/transport/` builds the ClientHello from a `Profile` directly against BoringSSL (`boring` 5), runs HTTP/1.1 and HTTP/2 over `hyper`, and drives everything on a Tokio runtime with its own connection pool — the layer reqwest and curl occupy. wreq and curl_cffi are optional fallbacks for the handful of things the native engine doesn't implement yet (streaming bodies, WebSocket, SOCKS5, HTTP/3); the capability router picks them automatically and nothing degrades silently.

| Layer | Owner |
|---|---|
| ClientHello, HTTP/1.1+2, connection pool, batch execution | native engine (Rust: `boring` + `hyper` + Tokio) |
| Profile database, JA3/JA4, header consistency | stealthhttp core (Rust, pure-Python fallback) |
| Rotation, proxy health, pacing, retries, cookies, behaviour, captcha orchestration | stealthhttp (Python) |
| Streaming, WebSocket, SOCKS5, HTTP/3 | wreq / curl_cffi (fallback only) |

### Byte-exact against a live capture

Chrome ≤151:
```
observed  t13d1516h2_8daaf6152771_d8a2da3f94cd
expected  t13d1516h2_8daaf6152771_d8a2da3f94cd
```

Chrome 152+ (trust_anchors extension added):
```
observed  t13d1517h2_8daaf6152771_cb7bf5808d99
expected  t13d1517h2_8daaf6152771_cb7bf5808d99
missing [] extra []
groups: GREASE, X25519MLKEM768 (4588), X25519, P-256, P-384
```

15 ciphers, 17 extensions (16 prior to Chrome 152), GREASE, BoringSSL's per-connection extension permutation, ALPS at codepoint 17613, ECH GREASE, brotli certificate compression, trust_anchors (51764, Chrome 152+), ML-DSA post-quantum signature algorithms (Chrome 155+) — all from a ClientHello this library builds.

### Measured, not claimed

Batch of 60 requests, 12 Python threads for the thread-based comparisons:

| client | wall | req/s | |
|---|---|---|---|
| **native engine (raw batch)** | 0.11s | 539.7 | best |
| **`Session.fetch_many`** (full pipeline) | 0.14s | 437.9 | 1.23x |
| wreq + 12 threads | 0.44s | 134.9 | 4.0x slower |
| curl_cffi + 12 threads | 1.47s | 40.9 | 13.2x slower |
| curl_cffi sequential | 5.25s | 11.4 | 47.2x slower |
| wreq sequential | 5.46s | 11.0 | 49.1x slower |

All 60 requests in the batch rode a single pooled HTTP/2 connection. The win isn't a faster socket — one request is one round trip, and every client ties there. It's that a whole batch crosses into Rust once: one GIL release, with concurrency, connection reuse and stream multiplexing decided in Rust rather than N round trips with the interpreter scheduling each one. `curl_cffi` gains nothing from threads because libcurl handles aren't thread-safe, so correct usage means a session — and a TLS handshake — per thread.

Run it yourself: `python benchmarks/bench_native.py --n 80 --workers 16`.

### Live test results (v0.9.3-dev, 2026-11-19)

Tested against 18 real sites, datacenter IP, no proxy, native engine:

| Target | WAF | Status | Result |
|---|---|---|---|
| cloudflare.com | Cloudflare | 200 | pass |
| discord.com | Cloudflare | 200 | pass |
| nowsecure.nl | Cloudflare | 200 | pass |
| shopify.com | Cloudflare | 200 | pass |
| nike.com | Akamai Bot Manager | 200 | pass |
| twitch.tv | Akamai | 200 | pass |
| linkedin.com | Akamai | 200 | pass |
| ebay.com | Akamai Bot Manager | 200 | pass (bypass engine) |
| footlocker.com | DataDome | 200 | pass |
| vinted.com | DataDome | 200 | pass |
| leboncoin.fr | DataDome | 200 | pass |
| alltrails.com | DataDome | 200 | pass |
| zillow.com | PerimeterX/HUMAN | 200 | pass |
| walmart.com | PerimeterX/HUMAN | 200 | pass |
| incapsula.com | Imperva | 200 | pass |
| amazon.com | — | 200 | pass |
| x.com | — | 200 | pass |
| hermes.com | DataDome | 403 | DC IP reputation block |

**17/18 (94%)** on a datacenter IP with no proxy or solver. hermes.com is an infrastructure-level IP reputation block (DataDome `x-dd-b=1`), not a fingerprint or sensor failure — it passes on residential IPs.

Fingerprint verification (tls.peet.ws): JA4 exact match, TLS 1.3, HTTP/2, correct Akamai H2 fingerprint `1:65536;2:0;4:6291456;6:262144|15663105|...|m,a,s,p`.

### Known gaps, stated rather than hidden

- Safari JA4 `c`-segment does not match a live capture — the sig_alg order hasn't been fully recovered. Marked `derived-known-gap`.
- Firefox lacks `record_size_limit` (28) and `delegated_credentials` (34) — `boring` exposes no API for either.
- Kasada's WASM-based PoW runs inside an obfuscated VM — native solving requires a JS runtime (QuickJS or similar). Only vendor still classified as `Solvability.BROWSER`.
- Arkose/FunCaptcha (3D rotation puzzles) requires a trained ML model — not solvable natively.
- Streaming responses, WebSocket, SOCKS5 and HTTP/3 aren't implemented natively; the router falls back to wreq/curl_cffi for those.

## Install

```bash
pip install maturin
maturin develop --release          # builds the native transport
python -c "import stealthhttp._core as c; print(c.HAS_TRANSPORT)"   # True
```

Building needs a Rust toolchain and `cmake` (`pip install cmake` is enough — no Go, no system BoringSSL). Without a compiled core the package still runs on a pure-Python fingerprint mirror plus wreq/curl_cffi if either is installed — `stealthhttp.NATIVE` and `available_backends()` report what's active.

## Features

### Fingerprint consistency engine

Everything visible at the HTTP layer is *derived from the same profile* that drives TLS, so the two can never disagree. This is the most common way a scraper gives itself away: a Chrome 136 ClientHello paired with a Chrome 120 `sec-ch-ua`, or a Firefox JA3 sending client hints at all (Firefox doesn't implement them).

```python
>>> from stealthhttp import resolve_profile
>>> resolve_profile("chrome158").sec_ch_ua
'"Not:A;Brand";v="8", "Chromium";v="158", "Google Chrome";v="158"'
>>> resolve_profile("firefox150").sec_ch_ua      # correctly sends none
None
```

The Chromium `sec-ch-ua` GREASE algorithm — brand permutation, GREASE punctuation, GREASE version — is derived from the major version, verified byte-for-byte against live Chrome 131–158, so it produces correct hints for versions no library ships yet.

### Request kinds: fetch metadata that matches what's being fetched

A browser sends a different `sec-fetch-*`/`accept`/`priority` group for a navigation than for an XHR. Sending the navigation set on an API call is a common, easily-filtered mistake.

```python
s.get(api_url, kind="xhr")       # sec-fetch-mode: cors, accept: */*, no upgrade-insecure-requests
s.get(img_url, kind="image")     # sec-fetch-dest: image, image accept list, priority: u=2, i
s.browse(page_url)               # fetches the document, then its stylesheets/scripts/images/favicon
```

`Session.browse()` exists because a "browser" that fetches HTML and never a stylesheet, script, font, image or favicon is the loudest behavioural signal there is.

### Offline JA3/JA4 self-check

```python
>>> from stealthhttp import predict, verify
>>> predict("chrome158").ja4
't13d1517h2_8daaf6152771_cb7bf5808d99'   # no network
>>> verify("chrome158").ok                # compares against a live capture
True
```

> Chrome has shuffled its ClientHello extension order since v110, so its JA3 hash legitimately changes per connection — a *fixed* JA3 is the anomaly. JA4 sorts its inputs and stays stable; prefer it.

### Rotation, proxy health, pacing, retries

```python
s = Session(
    browser=["chrome158", "firefox150", "edge158"], rotate="sticky_per_domain",
    proxy_pool=["http://p1", "http://p2", "http://p3"],
    delay=(0.4, 1.8), jitter_distribution="lognormal",
    retries=3, circuit_breaker=True,
)
```

Sticky rotation keeps one browser and one proxy per host, since a clearance cookie is bound to the IP and User-Agent that earned it — `ChallengeTracker` pins that pair once a `cf_clearance`/`datadome`/etc. cookie shows up and refuses to rotate it away. Consecutive proxy failures bench it for a doubling cooldown; a detected ban takes it out until `revive_all()`. Retries respect `Retry-After`, skip POST by default, and a circuit breaker stops hammering a host that's down.

### Batch execution

```python
responses = s.fetch_many([url1, url2, ..., url100])   # one GIL crossing, one pooled connection
```

Each request still goes through rotation, coherent headers, cookies and proxy selection — the whole batch just crosses into Rust once instead of once per request.

### DNS pinning

```python
s = Session(resolve={"example.com": "1.2.3.4"})   # connects there; SNI/Host still say example.com
```

Owning the TCP connect makes this possible. `wreq` accepts `resolve=` and silently ignores it — this was measured, not assumed, and is why `CapabilityUnsupported` exists rather than a request that quietly goes to the wrong place.

### Identity: persistent, and importable from a real browser

```python
from stealthhttp import Identity

ident = Identity.from_storage_state("cookies_export.json", browser="chrome158", proxy=proxy)
s = Session(identity=ident)
...
s.save_identity("account-42.json")   # cookies + clearance pins, ready to resume
```

`from_storage_state` and `from_cookies_txt` are browser-agnostic — they read a cookie export, not caring whether it came from Playwright, plain Chrome, or an antidetect browser. That's the hand-off this is built for: solve an interactive challenge once, for real, then keep going at HTTP speed with the identity that earned clearance.

### Humanization: session-level timing and travel plausibility

`Jitter` paces gaps *within* a session. Antifraud engines (Sift, Forter, Stripe Radar) also watch what only shows up *across* sessions — what hours an account is normally active, and whether it appears somewhere travel couldn't explain in the time available. Neither piece here is wired into the request path automatically; both are tools you consult explicitly when scheduling work, not a hook that could silently make `Session.get()` block for hours.

```python
from stealthhttp import ActivityClock, FlowStep, check_travel

clock = ActivityClock.for_country("DE")
if not clock.is_plausible_now():
    time.sleep(clock.wait_seconds())          # 3am in Berlin is a quiet hour, not a good time to run a batch

check = ident.check_travel("RU")               # before reusing an identity with a different proxy
if not check.plausible:
    ident = store.get("a-different-account")   # this one was just in the US an hour ago

s.visit_flow([                                  # realistic dwell time per page, not just inter-request jitter
    FlowStep("https://shop.example/", dwell=(5, 15)),
    FlowStep("https://shop.example/product/42", dwell=(10, 40)),
    FlowStep("https://shop.example/cart", dwell=(3, 10)),
])
```

`check_travel` is centroid-distance-based and, measured directly, that alone falsely flags the single most common real proxy-pool pairing: US↔Canada within an hour computed as "1898 km/h needed" because a country's geometric centroid can be thousands of km from its own border. Fixed with an explicit `ADJACENT_COUNTRIES` table (US-CA, US-MX, and two dozen other confirmed-adjacent pairs) that bypasses the distance check for bordering countries, while genuinely impossible jumps (US↔Russia, GB↔Australia within an hour) are still caught at 15,000+ km/h.

### JS environment emulation and sensor data

An HTTP client can't execute JavaScript, but it can generate the same *data* that JS collectors send. `stealthhttp` emulates the observable effects of a browser's JS environment:

```python
from stealthhttp import JsEnvironment, InteractionSequence
from stealthhttp.collectors import AkamaiSensor, PerimeterXCollector

# Real device fingerprint — 10K records from actual Chrome instances, zero synthetic data
env = JsEnvironment.from_real_device("chrome158")
print(env.webgl.renderer)     # "ANGLE (Intel, Intel(R) UHD Graphics 730 Direct3D11 vs_5_0 ps_5_0, ...)"

# Or derive from a profile spec (deterministic per seed, coherent with HTTP headers)
env = JsEnvironment.derive("chrome158", platform="macos", seed=42)

# Natural mouse movement, keyboard timing, scroll behavior
events = InteractionSequence.generate(seed=42, viewport=(env.window.inner_width, env.window.inner_height))

# Antibot sensor payloads for Akamai, PerimeterX, DataDome, Imperva
sensor = AkamaiSensor(abck_cookie=resp.cookies.get("_abck", ""))
payload = sensor.generate(env, events, page_url)
s.post(sensor.post_url(page_url), data=sensor.form_body(payload))
```

What this covers:
- **`JsEnvironment`**: complete navigator/screen/window/WebGL/canvas/audio/font property sets, deterministic per seed, coherent with HTTP headers. Database of real hardware configs (Apple Silicon, NVIDIA/AMD/Intel GPUs, screen resolutions per platform).
- **`InteractionSequence`**: mouse trajectories (Bezier curves, Fitts's law timing, overshoot-and-correct), keystroke timing (right-skewed, bigram-aware), touch gestures (tap/swipe/scroll with realistic pressure), scroll behavior (wheel steps or trackpad momentum).
- **Collectors**: sensor payload generators for **Akamai Bot Manager**, **PerimeterX/HUMAN**, **DataDome**, and **Imperva/Incapsula** — each targeting a documented format version.
- **`HintStore`**: Client Hints negotiation — Chrome sends low-entropy hints always, high-entropy only after Accept-CH, Critical-CH triggers automatic retry. Firefox/Safari correctly send none.
- **`HstsStore`**: HSTS preload enforcement (~80 top domains) + learned policies — no plain HTTP to google.com.
- **Cookie `SameSite`**: enforcement of Strict/Lax/None, `__Secure-`/`__Host-` prefix validation.
- **`solve_sha256()`**: SHA-256/HMAC/double-SHA proof-of-work solver for computational challenges.

### Automatic antibot bypass

`auto_bypass=True` makes the session automatically detect and bypass antibot challenges without a real browser:

```python
s = Session(browser="chrome158", proxy=proxy, auto_bypass=True)
r = s.get("https://akamai-protected-site.com")   # _abck sensor submitted automatically
r = s.get("https://datadome-site.com")            # device fingerprint sent to api-js.datadome.co
r = s.get("https://cloudflare-site.com")          # PoW solved and submitted
print(s.bypass.report())                          # per-vendor success stats
```

What the engine handles natively (no browser, no external API):
- **Cloudflare managed PoW**: extracts challenge params, solves SHA-256/double-SHA, submits solution, gets `cf_clearance`
- **Akamai Bot Manager**: extracts `bmak.ver` from live script, generates sensor_data with real device fingerprint, POSTs to `/_sec/cp_challenge/verify`, validates `_abck` state markers (`~-1~` / `~0~`)
- **DataDome**: detects `x-datadome-cid`, submits device fingerprint (ddv 5.11.5) to `api-js.datadome.co/js/`, gets `datadome` cookie
- **PerimeterX/HUMAN**: Edge identity swap (lower PX risk score) + collector payload to `/_px/xhr/api/v2/collector`
- **Imperva/Incapsula**: generates reese84 token from device fingerprint + timing

What still needs external help:
- DataDome DC IP reputation block (`x-dd-b=1`) → residential proxy
- Kasada WASM PoW → needs a JS runtime
- Arkose/FunCaptcha 3D rotation → needs trained ML model

The engine reports what it encountered:
```python
s.bypass.stats()    # [{"vendor": "akamai", "attempted": 3, "succeeded": 2, ...}]
s.bypass.report()   # human-readable summary
```

### Captcha identification and solving orchestration

Native-first captcha solving — no external APIs, no browser, no paid services:

```python
from stealthhttp import identify
from stealthhttp.solving import (
    SolverPool, NativeRecaptchaV2Solver, NativeRecaptchaV3Solver,
    NativeHCaptchaSolver, NativeTurnstileSolver, SlideSolver,
)
from stealthhttp.solving.audio import vosk_engine

engine = vosk_engine("/path/to/vosk-model-small-en-us-0.15")
pool = SolverPool([
    NativeRecaptchaV3Solver(),                    # pure HTTP, no audio needed
    NativeRecaptchaV2Solver(engine=engine),        # audio accessibility path
    NativeHCaptchaSolver(audio_engine=engine),     # HSL PoW + audio + CLIP grid
    NativeTurnstileSolver(),                       # local SHA-256 PoW
    SlideSolver(),                                 # image differencing, no model
])

challenge = identify(resp.status_code, resp.headers, resp.content, resp.url)
result = pool.solve_challenge(challenge, proxy=resp.proxy, user_agent=s.user_agent)
```

11 of 16 vendors are solvable natively (`Solvability.NATIVE` or `NATIVE_BYPASS`). Only Kasada (WASM PoW) needs a JS runtime.

- **reCAPTCHA v3** (`NativeRecaptchaV3Solver`): pure HTTP — anchor → reload → token. No audio, no image, no user interaction.
- **reCAPTCHA v2** (`NativeRecaptchaV2Solver`): audio accessibility path — downloads MP3 (decoded via ffmpeg/pydub/miniaudio), runs offline ASR (Vosk, 60-67% measured), submits transcription. Retries compound: 60% single-shot → 84% in 2 → 94% in 3.
- **hCaptcha** (`NativeHCaptchaSolver`): checks for passthrough, solves HSL SHA-1 hashcash PoW, then audio or CLIP image grid.
- **Turnstile** (`NativeTurnstileSolver`): extracts PoW challenge from widget, solves SHA-256/HMAC locally via Rust-accelerated `pow.py`.
- **Slide puzzles** (`SlideSolver`): image differencing, 100% precision when cut-out contrasts with background (measured), plus human-plausible drag trajectory.
- **Image grids** (`ImageGridSolver`): CLIP zero-shot, 88% on synthetic calibration set.
- **Text-arithmetic** (`MathCaptchaSolver`): fully deterministic, no model.
- **Audio** (`AudioSolver`): pluggable ASR, MP3/OGG decode built in, Vosk offline adapter included.
- Provider adapters for Capsolver / 2captcha / anti-captcha remain available as optional fallback.
- `BrowserBridge` (optional) for Kasada and sessions requiring a real engine.

### Stealth audit and profile comparison (v0.2)

Score your configuration against known detection vectors, compare fingerprint profiles side-by-side:

```python
from stealthhttp import StealthScore, FingerprintDiff, format_diff

scorer = StealthScore()
result = scorer.score("chrome158")
print(result.total, result.grade)       # 66.25 C — TLS/HTTP/TCP/JS/timing/behavioral breakdown

diff = FingerprintDiff()
summary = diff.diff("chrome158", "firefox150")
print(format_diff(summary))             # field-by-field comparison with importance weighting
```

### Automatic WAF-aware profile selection (v0.2)

The engine picks the best profile for a target domain — factoring in WAF vendor, country, and failure history:

```python
from stealthhttp import AutoProfileSelector

selector = AutoProfileSelector()
rec = selector.select("cloudflare.com", waf_vendor="cloudflare")
print(rec.profile_name, rec.score)      # chrome158 0.40
```

### Header canonicalization (v0.2)

Exact browser header order and casing per Chrome/Firefox/Safari — the second most common tell after TLS is sending headers in the wrong order:

```python
from stealthhttp import HeaderCanonicalizer

headers = HeaderCanonicalizer.canonicalize(
    {"accept": "text/html", "user-agent": "...", "accept-encoding": "gzip, br"},
    browser_family="chrome",
)
```

### Additional modules

`stealthhttp` includes modules for TLS/MITM detection (`CertAnalyzer`, `MitmDetector`), response body intelligence (`BodyIntelligence`, `CookieClassifier`), network simulation (`NetworkSimulator`), DNS leak prevention (`DnsLeakChecker`), CDN detection (`CdnDetector`), advanced proxy scoring (`ProxyScorer`), request dependency graphs (`build_graph_from_html`), response decoding (gzip/br/zstd + charset), redirect intelligence, error classification, multi-session coordination (`SessionPool`, `SharedRateLimiter`), health monitoring (`HealthMonitor`), and concurrency/throttling middleware. See the module docstrings for usage.

### Detection vector catalogue and self-audit

```python
from stealthhttp import audit
from stealthhttp.detection import report

print(report())          # every vector this library is aware of, and its status
a = audit(session=s)     # checks the measurable ones against a live echo service
print(a.report())
```

Listing the vectors this can't address (JS fingerprinting, the TCP/IP stack fingerprint, proof-of-work) next to the ones it does is deliberate — a partial defence advertised as complete just tells you to stop looking.
## Building the Rust core

```bash
pip install maturin cmake
maturin develop --release
python -c "import stealthhttp; print(stealthhttp.NATIVE)"                    # fingerprint core
python -c "import stealthhttp._core as c; print(c.HAS_TRANSPORT)"            # native transport
```

The test suite asserts the native core and the Python fallback produce identical output, so they cannot silently diverge.

## Tests

```bash
pytest -m "not network"   # offline
pytest -m network         # live fingerprint/transport verification
cargo test --lib          # Rust unit tests
```

## Layout

```
src/                             Rust core: PyO3 bindings, fingerprint DB, JA3/JA4, native transport
python/stealthhttp/              151 Python modules (44K lines)
  backends/                      native / wreq / curl_cffi, capability routing
  solving/                       native captcha solvers (reCAPTCHA, hCaptcha, Turnstile, slide, audio, vision)
  bypasses/                      auto antibot bypass (CF, Akamai, DD, PX, Imperva, Kasada, Shape)
  collectors/                    sensor payload generators (Akamai, PX, DataDome, Imperva, Kasada, Shape)
  jsenv.py, jsenv_real.py        JS environment emulation + real device fingerprints (10K records)
  device_db.py                   real device database (screen, WebGL, audio, fonts, keyboard)
  sensors.py                     mouse/keyboard/touch/scroll event generation
  pow.py                         proof-of-work solver (SHA-256, HMAC, double-SHA, Rust-accelerated)
  _fallback.py                   pure-Python mirror of the Rust fingerprint core
benchmarks/                      performance benchmarks
tests/                           1090 Python + 25 Rust tests
```

## Legal

For authorised testing, research, and accessing services you have the right to access. Respect `robots.txt`, terms of service, and rate limits. MIT.

