Metadata-Version: 2.5
Name: frequest
Version: 1.0.0
Summary: High-concurrency async HTTP client for Red Team reconnaissance, probing, and network automation
Project-URL: Homepage, https://github.com/fareed1-ataf/frequest.git
Project-URL: Repository, https://github.com/fareed1-ataf/frequest.git
Project-URL: Bug Tracker, https://github.com/fareed1-ataf/frequest/issues
License: MIT
License-File: LICENSE
Keywords: async,asyncio,http-client,penetration-testing,reconnaissance,red-team,security,socks5,tor,web-scraping
Classifier: Development Status :: 4 - Beta
Classifier: Framework :: AsyncIO
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Information Technology
Classifier: License :: OSI Approved :: MIT License
Classifier: Natural Language :: English
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Internet :: WWW/HTTP
Classifier: Topic :: Security
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.8
Description-Content-Type: text/markdown

<div align="center">

# frequest

**High-concurrency Async HTTP Client for Red Team Reconnaissance, Probing, and Network Automation**

`v1.0.0` &nbsp;|&nbsp; Python `≥ 3.8` &nbsp;|&nbsp; Zero Dependencies &nbsp;|&nbsp; MIT License

</div>

---

`frequest` is a pure-Python async HTTP/1.1 client built entirely on the standard library. No `httpx`, no `aiohttp`, no `requests` — just raw `asyncio`, `ssl`, and `socket`. It was built for high-concurrency workloads where you need precise control over every layer of the HTTP stack: connection limits, proxy tunneling, header construction, and TLS fingerprinting.

## Features

- **Dual-Semaphore Concurrency Control** — Independent global and per-host `asyncio.Semaphore` limits. Scan 1000 hosts at 50 concurrent connections while capping each host at 3 to avoid triggering rate-limiting.
- **Zero-DNS-Leak SOCKS5** — Full RFC 1928 implementation. Hostnames are forwarded to the proxy as domain strings (ATYP `0x03`), so DNS resolution never happens on your machine. Essential for Tor usage.
- **Red Team Header Control** — Raw header construction with opt-in CRLF/NUL injection testing (`strict_headers=False` by default). Test for request smuggling and header injection without the client sanitizing your payloads.
- **SSRF Protection** — Validates resolved IPs against private ranges (`10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16`, loopback, link-local) during redirects. Performs actual DNS resolution, not just string matching.
- **Low-Level HTTP/1.1 Engine** — Chunked transfer encoding decoder, `gzip`/`deflate` auto-decompression, keep-alive connection pooling, and streaming for large downloads.
- **TLS Fingerprint Spoofing** — Swap cipher suite profiles (`"chrome"`, `"firefox"`, `"default"`) to pass basic JA3-based bot detection.
- **Exponential Backoff Retry** — Configurable retry count and backoff multiplier for unstable targets.

---

## Installation

```bash
pip install frequest
```

Since `frequest` has zero external dependencies, you can also drop the `frequest/` directory directly into any project.

---

## Quick Start

### GET Request

```python
import asyncio
from frequest import AsyncHTTPClient

async def main():
    async with AsyncHTTPClient() as client:
        resp = await client.get("https://httpbin.org/get", timeout=10.0)
        print(resp.status_code)   # 200
        print(resp.json())        # parsed JSON dict

asyncio.run(main())
```

### POST with JSON Payload

```python
async def post_example():
    async with AsyncHTTPClient() as client:
        resp = await client.post(
            "https://httpbin.org/post",
            body={"username": "admin", "password": "hunter2"},
            headers={"X-Custom-Header": "value"},
        )
        print(resp.ok, resp.json()["json"])
```

### File Upload (Multipart)

```python
from frequest.models import MultipartData

async def upload():
    async with AsyncHTTPClient() as client:
        payload = MultipartData(
            fields={"description": "recon report"},
            files={"archive": ("loot.zip", open("loot.zip", "rb").read())},
        )
        resp = await client.post("https://target.internal/upload", body=payload)
```

---

## SOCKS5 Proxy & Tor

`frequest` never resolves the target hostname locally when using SOCKS5. The raw domain string is passed to the proxy (ATYP=`0x03`), so DNS queries exit from the proxy/exit-node — not from your machine.

```python
from frequest import AsyncHTTPClient, SOCKS5Transport

async def via_tor():
    tor = SOCKS5Transport(proxy_host="127.0.0.1", proxy_port=9050)

    async with AsyncHTTPClient(transport=tor) as client:
        # Verify Tor is working
        resp = await client.get("https://check.torproject.org")
        print("Using Tor:", "Congratulations" in resp.text)

        # Dark web .onion access (HTTP — no cert to verify)
        resp2 = await client.get("http://duskgytldkxiuqc6.onion/", verify_ssl=False)
```

### SOCKS5 with Authentication (RFC 1929)

```python
transport = SOCKS5Transport(
    proxy_host="proxy.example.com",
    proxy_port=1080,
    username="user",
    password="secret",
)
```

---

## High-Concurrency Domain Scanner

```python
import asyncio
from frequest import AsyncHTTPClient, RequestConfig
from frequest.exceptions import HTTPClientError

TARGETS = [
    "https://admin.target.com",
    "https://api.target.com",
    "https://staging.target.com",
    "https://internal.target.com",
    # ... hundreds more
]

async def probe(client: AsyncHTTPClient, url: str) -> dict:
    try:
        config = RequestConfig(
            url=url,
            timeout=5.0,
            verify_ssl=False,        # many internal hosts have self-signed certs
            allow_redirects=False,   # catch 301/302 as signals, don't follow
            retry_count=1,
            tls_profile="chrome",    # bypass simple TLS fingerprint detection
        )
        resp = await client.request(config)
        return {"url": url, "status": resp.status_code, "length": len(resp.body)}
    except HTTPClientError as e:
        return {"url": url, "error": str(e)}

async def scan(targets: list[str]):
    async with AsyncHTTPClient(
        max_concurrent=50,           # global cap: 50 in-flight requests
        max_concurrent_per_host=3,   # per-host cap: avoid triggering rate limits
    ) as client:
        results = await asyncio.gather(*[probe(client, t) for t in targets])

    for r in results:
        if "error" not in r:
            print(f"[{r['status']}] {r['url']}  ({r['length']} bytes)")

asyncio.run(scan(TARGETS))
```

---

## Sessions & Cookie Persistence

```python
from frequest import AsyncSession

async def authenticated_flow():
    async with AsyncSession() as session:
        # Cookies from Set-Cookie are stored and re-sent automatically
        await session.post("https://target.com/login", body={
            "username": "admin",
            "password": "Password1!",
        })
        dashboard = await session.get("https://target.com/dashboard")
        print(dashboard.status_code)  # 200 if auth worked
```

---

## Streaming Large Downloads

```python
async def stream_download(url: str, dest: str):
    async with AsyncHTTPClient() as client:
        resp = await client.get(url, stream=True, timeout=120.0)

        with open(dest, "wb") as f:
            async for chunk in resp.iter_content(chunk_size=65536):
                f.write(chunk)

        await resp.close()   # always close a streamed response
```

---

## API Reference

### `RequestConfig`

All `client.get()`, `client.post()` etc. accept `**kwargs` that map directly to `RequestConfig` fields.

| Field | Type | Default | Description |
|---|---|---|---|
| `url` | `str` | *(required)* | Target URL (`http://` or `https://`) |
| `method` | `str` | `"GET"` | HTTP method |
| `headers` | `dict` | `None` | Extra request headers, merged with `default_headers` |
| `cookies` | `dict` | `None` | Cookies serialized into the `Cookie` header |
| `body` | `any` | `None` | `dict`/`list` → JSON, `bytes` → raw, `MultipartData` → multipart |
| `timeout` | `float` | `10.0` | Total request timeout in seconds (connect + read) |
| `verify_ssl` | `bool` | `True` | Verify TLS certificate chain and hostname |
| `allow_redirects` | `bool` | `True` | Follow `3xx` redirects automatically |
| `max_redirects` | `int` | `None` | Per-request redirect cap (falls back to client-level `max_redirects=5`) |
| `ssrf_protection` | `bool` | `False` | Block requests that resolve to private/loopback IPs |
| `retry_count` | `int` | `0` | Number of retries on transient failures |
| `retry_backoff` | `float` | `1.0` | Base for exponential backoff: `backoff * 2^(attempt-1)` seconds |
| `strict_headers` | `bool` | `False` | Raise `HeaderInjectionError` on `\r\n`/`\x00` in headers |
| `tls_profile` | `str` | `"chrome"` | Cipher suite preset: `"chrome"`, `"firefox"`, `"default"` |
| `stream` | `bool` | `False` | Don't buffer body; use `.iter_content()` instead |
| `jitter` | `float` | `0.0` | Max random delay (seconds) added before acquiring the semaphore |
| `randomize_user_agent` | `bool` | `True` | Pick a random `User-Agent` if none is provided |
| `max_body_size` | `int` | `10485760` | Max response body in bytes (10 MB default) |

---

### `HTTPResponse`

| Attribute / Method | Type | Description |
|---|---|---|
| `status_code` | `int` | HTTP status code (e.g. `200`, `404`) |
| `headers` | `dict[str, str]` | Case-lowered headers; first value only per key |
| `raw_headers` | `list[tuple[str, str]]` | All header occurrences in order (use for `Set-Cookie`) |
| `body` | `bytes` | Full response body (after decompression). Empty when `stream=True` |
| `url` | `str` | Final URL after redirects |
| `history` | `list[HTTPResponse]` | Redirect chain, oldest first |
| `.text` | `str` | `body` decoded as UTF-8 |
| `.json()` | `any` | `json.loads(self.text)` |
| `.ok` | `bool` | `True` if `200 ≤ status_code < 300` |
| `.get_all(name)` | `list[str]` | All values for a header name — essential for `Set-Cookie` |
| `.iter_content(chunk_size)` | async generator | Yields `bytes` chunks. Only valid when `stream=True` |
| `.close()` | coroutine | Closes the underlying socket. Call after streaming |

---

### `AsyncHTTPClient`

```python
AsyncHTTPClient(
    transport=None,              # Transport instance (default: DirectTransport)
    default_headers=None,        # dict merged into every request
    max_redirects=5,             # client-level redirect cap
    max_concurrent=5,            # global asyncio.Semaphore value
    max_concurrent_per_host=None,# per-host asyncio.Semaphore value
    max_body_size=10*1024*1024,  # default 10 MB body cap
)
```

---

## Exception Hierarchy

```
HTTPClientError
├── URLParseError
├── HeaderInjectionError
├── TooManyRedirectsError
├── ResponseTimeoutError
├── MalformedResponseError
├── ProxyError
├── TLSError
└── ConnectionFailedError
    ├── DNSResolutionError
    └── TCPConnectionRefusedError
```

All exceptions inherit from `HTTPClientError`, so a single `except HTTPClientError` catches everything the library raises.

---

## Legal Disclaimer

`frequest` is intended for **authorized security testing, research, and network automation only**. You are solely responsible for ensuring that your use of this tool complies with all applicable laws and that you have explicit written permission from the owner of any system you interact with. The authors accept no liability for misuse.

---

## License

MIT License — see [`LICENSE`](LICENSE) for details.
