| FazBrowse GitHub Viewer | Trending | | Home |
| Tools: [Download Repo ZIP] [Original HTTPS Page] |
| Name | Name | Last commit date | ||
|---|---|---|---|---|
English | فارسی | 🚀 راهاندازی سریع
BatProxy is a sophisticated, high-performance proxy solution that combines the power of Cloudflare Workers with an intelligent Python client. It creates a resilient, self-healing tunnel network that automatically adapts to network conditions, provides automatic failover, and delivers exceptional throughput through intelligent request routing and data coalescing.
⚠️ Important Security Note: For enhanced privacy, we strongly recommend using disposable email addresses (such as ProtonMail or temporary email services) when creating Cloudflare accounts for this project.
╔════════════════════════════════════════════════════════════════╗ ║ BATPROXY ║ ║ Intelligent Proxy Tunnel for the Modern Web ║ ╠════════════════════════════════════════════════════════════════╣ ║ HTTP/HTTPS │ SOCKS5 │ Auto-Failover │ Load Balancing ║ ║ Circuit Breaker │ Health Checks │ Real-time Dashboard ║ ╚════════════════════════════════════════════════════════════════╝
BatProxy is not just another proxy tool—it's a complete traffic routing ecosystem designed for reliability, performance, and ease of use. Whether you're a developer needing to bypass geographic restrictions, a security researcher testing network configurations, or simply someone who values privacy, BatProxy provides enterprise-grade features in a lightweight, easy-to-deploy package.
The system leverages Cloudflare's global edge network to provide low-latency connections worldwide, while the intelligent Python client ensures optimal worker selection, automatic recovery from failures, and seamless failover between multiple workers.
┌─────────────────────────────────────────────────────────────────────────────────────┐
│ CLIENT APPLICATIONS │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │ Browser │ │ curl │ │ wget │ │ git │ │ Docker │ ... │
│ └────┬─────┘ └────┬─────┘ └────┬─────┘ └────┬─────┘ └────┬─────┘ │
│ │ │ │ │ │ │
│ └─────────────┴─────────────┴─────────────┴─────────────┘ │
│ │ │
│ ┌────────▼────────┐ │
│ │ HTTP/SOCKS5 │ │
│ │ Proxy Server │ │
│ │ (127.0.0.1:1080)│ │
│ └────────┬────────┘ │
│ │ │
│ ┌─────────────────┼─────────────────┐ │
│ │ │ │ │
│ ┌──────▼──────┐ ┌──────▼──────┐ ┌──────▼──────┐ │
│ │ Worker 1 │ │ Worker 2 │ │ Worker N │ │
│ │ Scoring │ │ Scoring │ │ Scoring │ │
│ │ Health │ │ Health │ │ Health │ │
│ │ Checks │ │ Checks │ │ Checks │ │
│ └──────┬──────┘ └──────┬──────┘ └──────┬──────┘ │
│ │ │ │ │
│ └─────────────────┼─────────────────┘ │
│ │ │
│ ┌──────────▼──────────┐ │
│ │ Cloudflare Edge │ │
│ │ Network (Workers) │ │
│ └──────────┬──────────┘ │
│ │ │
└─────────────────────────────────────┼───────────────────────────────────────────────┘
│
┌────────────┼────────────┐
│ │ │
┌──────▼──────┐ ┌──▼───┐ ┌─────▼─────┐
│ Target │ │Target│ │ Target │
│ Server 1 │ │Srv 2 │ │ Server 3 │
│ (example) │ │ │ │ │
└─────────────┘ └──────┘ └───────────┘
The connection establishment process is a multi-step handshake designed for security and reliability:
Client (Python) Cloudflare Worker
│ │
│ 1. Establish WebSocket │
│───────────────────────────────────►│
│ │
│ 2. Send Handshake (JSON) │
│ { │
│ "hostname": "example.com", │
│ "port": 443, │
│ "auth": { │
│ "ts": "1712345678", │
│ "nonce": "a1b2c3d4...", │
│ "sig": "e5a4d3c2..." │
│ } │
│ } │
│───────────────────────────────────►│
│ │
│ 3. Verify Auth │
│ - Check timestamp│
│ - Validate HMAC │
│ - Verify nonce │
│ │
│ 4. Response (Status) │
│ {"status": "connected"} │
│◄───────────────────────────────────│
│ │
│ 5. Raw TCP Data Relay Starts │
│ (Binary WebSocket Frames) │
│◄══════════════════════════════════►│
│ │
Detailed Steps:
The data relay mechanism is optimized for both throughput and latency:
Client → Worker Direction:
Worker → Client Direction:
Benefits of Coalescing:
BatProxy handles HTTP CONNECT method (used for HTTPS, WebSockets, and other TLS tunnels):
Browser/Client BatProxy Client Worker Target Server
│ │ │ │
│ 1. CONNECT example.com:443 │ │
│───────────────────────►│ │ │
│ │ │ │
│ │ 2. Select Worker │ │
│ │ 3. Handshake │ │
│ │───────────────────►│ │
│ │ │ │
│ │ 4. Connected │ │
│ │◄───────────────────│ │
│ │ │ │
│ 5. 200 OK │ │ │
│◄───────────────────────│ │ │
│ │ │ │
│ 6. TLS Tunnel Established (Bidirectional Relay) │
│◄══════════════════════►│◄══════════════════►│◄════════════════════►│
Process Flow:
The SOCKS5 protocol implementation supports all standard features:
Browser/Client BatProxy Client Worker Target Server
│ │ │ │
│ 1. SOCKS5 Handshake │ │ │
│───────────────────────►│ │ │
│ 2. Auth Method (NoAuth)│ │ │
│◄───────────────────────│ │ │
│ │ │ │
│ 3. CONNECT Request │ │ │
│ (host, port) │ │ │
│───────────────────────►│ │ │
│ │ │ │
│ │ 4. Select Worker │ │
│ │ 5. Handshake │ │
│ │───────────────────►│ │
│ │ │ │
│ │ 6. Connected │ │
│ │◄───────────────────│ │
│ │ │ │
│ 7. SOCKS5 Response (Success) │ │
│◄───────────────────────│ │ │
│ │ │ │
│ 8. Bidirectional Data Relay │ │
│◄══════════════════════►│◄══════════════════►│◄════════════════════►│
Supported SOCKS5 Features:
The worker selection algorithm uses a sophisticated scoring system to choose the optimal worker:
def calculate_score(worker_state):
# Base success rate (EWMA)
score = worker_state.ewma_success
# RTT penalty (lower is better)
rtt_penalty = (worker_state.ewma_rtt or 200.0) / 10.0
score -= rtt_penalty
# Slow streak penalty
if worker_state.slow_streak >= 3:
score -= 20.0
# Availability penalty
if worker_state.state == "open" and cooldown_remaining > 0:
return -1.0 # Exclude from selection
# Load penalty
if worker_state.active >= max_connections:
score -= 50.0
return scoreScoring Factors:
| Factor | Weight | Description |
|---|---|---|
| Success Rate (EWMA) | High | Weighted average of recent successes, α=0.35 |
| RTT (EWMA) | Medium | Weighted average of connection latency, α=0.35 |
| Slow Streak | Medium | Consecutive slow connections (>600ms) |
| Active Connections | Low | Current load on the worker |
| Cooldown Status | Critical | Workers in cooldown are excluded |
Selection Process:
The circuit breaker pattern prevents cascading failures:
Worker States:
┌─────────┐
│ CLOSED │ ← Normal operation (successful requests)
└────┬────┘
│ Consecutive failures >= 3
▼
┌─────────┐
│HALF-OPEN│ ← Probationary state (limited retries)
└────┬────┘
│ Additional failure
▼
┌─────────┐
│ OPEN │ ← Cooldown period (excluded from selection)
└────┬────┘
│ Cooldown expires / Health check success
▼
┌─────────┐
│HALF-OPEN│ ← Retry with one request
└────┬────┘
│ Success
▼
┌─────────┐
│ CLOSED │ ← Full recovery
└─────────┘
Transition Rules:
Cooldown Calculation:
cooldown = min(
COOLDOWN_BASE * (2 ** (consec_failures - HALF_OPEN_AFTER_FAILS)),
COOLDOWN_MAX
)The background health check system continuously monitors worker health:
┌─────────────────────────────────────────────────────────────────┐ │ Health Check Loop │ │ (Every HEALTH_CHECK_INTERVAL) │ ├─────────────────────────────────────────────────────────────────┤ │ │ │ 1. For each worker in "open" state: │ │ ├── Send "ping" command with HMAC authentication │ │ ├── Wait for "pong" response (timeout: CONNECT_TIMEOUT) │ │ ├── If successful: │ │ │ ├── Update EWMA RTT │ │ │ ├── Transition state: OPEN → HALF-OPEN │ │ │ └── Decrement consecutive failure counter │ │ └── If failed: │ │ └── Keep in OPEN state (extend cooldown) │ │ │ └─────────────────────────────────────────────────────────────────┘
Health Check Features:
The destination cache improves performance for repeated connections to the same target:
dest_cache = {
"example.com:443": {
"url": "wss://worker1.workers.dev",
"ts": 1712345678.0
},
"api.github.com:443": {
"url": "wss://worker2.workers.dev",
"ts": 1712345680.0
}
}Cache Benefits:
BatProxy implements intelligent retry logic for improved reliability:
Retry Conditions:
Idempotent Methods (GET, HEAD, OPTIONS, TRACE):
Non-Idempotent Methods (POST, PUT, DELETE, PATCH):
Retry Flow:
1. Attempt request with best worker
2. If failed:
├── Mark worker as failed
├── Add worker to exclusion set
├── If method is idempotent and attempts < MAX_ATTEMPTS:
│ ├── Select next best worker
│ └── Go to step 1
└── Else:
└── Return error to client
The Cloudflare Worker component is written in JavaScript and runs on Cloudflare's V8-based edge runtime.
Core Functions:
fetch(request, env, ctx): The main entry point for all HTTP requests
verifyAuth(passwd, subject, auth): Authentication verification
claimNonce(nonce, now): Nonce management
Data Coalescing: The worker implements intelligent buffering
Key Implementation Details:
// WebSocket Pair Creation
const { 0: client, 1: server } = new WebSocketPair();
// TCP Connection via Cloudflare's connect API
tcpSocket = connect({ hostname, port });
// Bidirectional Piping
const reader = tcpSocket.readable.getReader();
while (true) {
const { value, done } = await reader.read();
if (done) break;
if (value) queueSend(value);
}The Python client is built on asyncio with a modular, event-driven architecture.
Core Components:
handle_client(reader, writer): Main entry point for client connections
open_tunnel(hostname, port, exclude): Worker connection manager
relay(reader, writer, ws, preloaded): Data relay coordinator
pipe_local_to_ws(reader, ws): Local → Worker pipeline
pipe_ws_to_local(ws, writer, preloaded): Worker → Local pipeline
Event Loop Architecture:
┌─────────────────────────────────────────────────────────────┐ │ Asyncio Event Loop │ ├─────────────────────────────────────────────────────────────┤ │ │ │ ┌────────────────┐ ┌────────────────┐ ┌──────────────┐ │ │ │ HTTP Handler │ │ SOCKS5 Handler │ │ HTTP Handler │ │ │ └───────┬────────┘ └───────┬────────┘ └──────┬───────┘ │ │ │ │ │ │ │ └───────────────────┼──────────────────┘ │ │ │ │ │ ┌───────────▼────────────┐ │ │ │ Tunnel Manager │ │ │ │ - Worker Selection │ │ │ │ - Connection Pool │ │ │ │ - Health Checks │ │ │ └───────────┬────────────┘ │ │ │ │ │ ┌───────────────────┼──────────────────┐ │ │ │ │ │ │ │ ┌───────▼───────┐ ┌───────▼───────┐ ┌───────▼──────┐ │ │ │ Worker 1 │ │ Worker 2 │ │ Worker N │ │ │ │ WebSocket │ │ WebSocket │ │ WebSocket │ │ │ └───────────────┘ └───────────────┘ └──────────────┘ │ │ │ └─────────────────────────────────────────────────────────────┘
The authentication system is designed to be secure against various attack vectors:
Authentication Token Generation (Client Side):
def make_token(password, subject):
# Generate timestamp (Unix epoch)
ts = str(int(time.time()))
# Create random nonce (8 bytes hex)
nonce = secrets.token_hex(8)
# Construct message: subject:timestamp:nonce
msg = f"{subject}:{ts}:{nonce}".encode()
# Compute HMAC-SHA256
sig = hmac.new(password.encode(), msg, hashlib.sha256).hexdigest()
return {"ts": ts, "nonce": nonce, "sig": sig}Verification Process (Worker Side):
┌─────────────────────────────────────────────────────────────────┐ │ Authentication Verification │ ├─────────────────────────────────────────────────────────────────┤ │ │ │ Input: password, subject, auth_token │ │ │ │ 1. Extract: ts, nonce, sig from auth_token │ │ │ │ 2. Timestamp Validation: │ │ └── current_time - ts <= AUTH_WINDOW (30s) │ │ │ │ 3. HMAC Recalculation: │ │ └── expected = HMAC-SHA256(password, subject:ts:nonce) │ │ │ │ 4. Signature Match: │ │ └── constant_time_compare(expected, sig) │ │ │ │ 5. Nonce Uniqueness: │ │ └── claimNonce(nonce, current_time) │ │ ├── Check if nonce exists in seenNonces map │ │ ├── If not, add with expiry (current_time + window) │ │ └── If exists, reject (replay attack) │ │ │ │ 6. All checks passed → Authentication successful │ │ │ └─────────────────────────────────────────────────────────────────┘
Security Properties:
BatProxy implements several optimizations for high performance:
1. Data Coalescing:
2. EWMA Metrics:
3. Connection Pooling:
4. Asynchronous I/O:
5. Buffer Management:
1. Worker Security:
2. Authentication Security:
3. Data Protection:
4. Operational Security:
5. Recommended Practices:
The terminal dashboard provides real-time monitoring with colored output:
🦇 Bat Proxy listening on 127.0.0.1:1080 (engine: uvloop, workers: 3, verbose: False) curl (HTTP) : curl -x http://127.0.0.1:1080 https://example.com curl (SOCKS5) : curl -x socks5h://127.0.0.1:1080 https://example.com Browser : set proxy to 127.0.0.1:1080 (HTTP or SOCKS5, all protocols) (tip: pip install rich -> colored live dashboard) ╭────────────────────────────────────────────────────────────────────╮ │ 🦇 Bat Proxy │ ├────────────────────────────────────────────────────────────────────┤ │ Active │ Total │ OK │ Failed │ │ 12 │ 1547 │ 1532 │ 15 │ ├────────────────────────────────────────────────────────────────────┤ │ Workers │ ├──────────┬──────────┬──────────┬──────────┬──────────┬──────────┤ │ Worker │ Status │ Conns │ RTT │ Score │ OK/Fail │ ├──────────┼──────────┼──────────┼──────────┼──────────┼──────────┤ │ worker1 │ closed │ 8 │ 124ms │ 85 │ 512/5 │ │ worker2 │ half-open│ 2 │ 189ms │ 72 │ 421/8 │ │ worker3 │ open 45s │ 2 │ 345ms │ -1 │ 199/2 │ └──────────┴──────────┴──────────┴──────────┴──────────┴──────────┘
Dashboard Components:
The HTML dashboard provides a clean, browser-based interface:
Features:
Endpoint Structure:
{
"active": 12,
"total": 1547,
"ok": 1532,
"fail": 15,
"workers": [
{
"url": "worker1",
"status": "closed",
"cooldown": 0,
"active": 8,
"rtt": 124.5,
"score": 85.3,
"ok": 512,
"fail": 5
}
]
}websocket-client rich # Optional, for better dashboard uvloop # Optional, for better performance
Step 1: Create Cloudflare Account
Step 2: Create Worker
Step 3: Deploy Worker Code
Option 1: Using Cloudflare Dashboard
Option 2: Using Wrangler CLI
# Install Wrangler
npm install -g wrangler
# Login
wrangler login
# Set secret
wrangler secret put PASSWD
# (Enter your password when prompted)
# Deploy
wrangler deploy1. Install Python 3.8+
# Ubuntu/Debian
sudo apt update
sudo apt install python3 python3-pip
# macOS (using Homebrew)
brew install python3
# Windows (using Chocolatey)
choco install python32. Clone the Repository
git clone https://github.com/batmanpriv/BatProxy.git
cd BatProxy3. Install Dependencies
# Install core dependencies
pip install -r requirements.txtThe client is configured via configx.py or environment variables.
Worker Configuration:
# configx.py
WORKERS = [
{"url": "wss://worker1.workers.dev", "password": "your_password"},
{"url": "wss://worker2.workers.dev", "password": "your_password"},
# Add more workers for redundancy
]Performance Settings:
# Connection and timeout settings
CONNECT_TIMEOUT = 6 # Seconds to wait for connection
COOLDOWN_BASE = 5 # Initial cooldown in seconds
COOLDOWN_MAX = 120 # Maximum cooldown in seconds
MAX_ATTEMPTS_PER_REQUEST = 4 # Maximum retry attempts
# Buffer and coalescing settings
WRITE_BUFFER_MAX = 65536 # 64KB buffer
WRITE_BUFFER_DELAY = 0.004 # 4ms delay
# Load balancing settings
MAX_CONN_PER_WORKER = 150 # Maximum concurrent connections
HALF_OPEN_AFTER_FAILS = 3 # Failures before circuit opens
# Cache settings
DEST_CACHE_TTL = 600 # 10 minutes cache TTL
DEST_CACHE_CLEANUP_INTERVAL = 60 # 1 minute cleanup interval
# EWMA settings (success rate)
ALPHA_SUCCESS = 0.35 # Smoothing factor for success rate
ALPHA_RTT = 0.35 # Smoothing factor for RTT
# Performance thresholds
SLOW_RTT_MS = 600 # Considered "slow" in milliseconds
SLOW_PENALTY = 20.0 # Score penalty for slow workersEnvironment Variables:
// worker.js - can be set via Cloudflare dashboard
const DEFAULT_PASSWORD = '123456'; // Fallback if PASSWD not set
const AUTH_WINDOW = 30; // Seconds
const COALESCE_MS = 4; // Milliseconds
const COALESCE_MAX = 65536; // Bytes
const MAX_HANDSHAKE_BYTES = 2048; // Bytes
const PING_TARGET_HOST = '1.1.1.1'; // Health check target
const PING_TARGET_PORT = 443; // Health check port
const MAX_NONCES = 5000; // Maximum stored nonces| Variable | Description | Default |
|---|---|---|
| PASSWD | Authentication password | 123456 |
| AUTH_WINDOW | Authentication time window (seconds) | 30 |
| COALESCE_MS | Data coalescing delay (milliseconds) | 4 |
| COALESCE_MAX | Data coalescing size limit (bytes) | 65536 |
| MAX_HANDSHAKE_BYTES | Maximum handshake size (bytes) | 2048 |
| PING_TARGET_HOST | Host for health checks | 1.1.1.1 |
| PING_TARGET_PORT | Port for health checks | 443 |
| MAX_NONCES | Maximum stored nonces | 5000 |
python batproxy.py [options]| Option | Description | Default |
|---|---|---|
| -v, --verbose | Enable verbose logging | False |
| --host HOST | Local proxy host | 127.0.0.1 |
| --port PORT | Local proxy port | 1080 |
| --dashboard-host HOST | Dashboard host | 127.0.0.1 |
| --dashboard-port PORT | Dashboard port | 8088 |
| --no-web-dashboard | Disable web dashboard | False |
Examples:
# Default configuration
python batproxy.py
# Custom proxy port with verbose logging
python batproxy.py --port 8080 -v
# Run without web dashboard
python batproxy.py --no-web-dashboard
# Custom dashboard port
python batproxy.py --dashboard-port 9090Firefox:
Chrome/Chromium:
# Command line
chrome --proxy-server="http://127.0.0.1:1080"
# Or via Settings → System → Open your computer's proxy settingsSystem Proxy (Ubuntu):
# Set HTTP/HTTPS proxy
export http_proxy="http://127.0.0.1:1080"
export https_proxy="http://127.0.0.1:1080"
# Set SOCKS5 proxy
export all_proxy="socks5://127.0.0.1:1080"HTTP/HTTPS Proxy:
# Basic HTTP GET
curl -x http://127.0.0.1:1080 https://example.com
# HTTP GET with headers
curl -x http://127.0.0.1:1080 -H "User-Agent: BatProxy" https://api.example.com/data
# POST request with data
curl -x http://127.0.0.1:1080 -X POST -d '{"key":"value"}' https://httpbin.org/post
# Download file through proxy
curl -x http://127.0.0.1:1080 -O https://example.com/file.zipSOCKS5 Proxy:
# Basic SOCKS5
curl -x socks5h://127.0.0.1:1080 https://example.com
# SOCKS5 with authentication (if enabled)
curl -x socks5h://user:pass@127.0.0.1:1080 https://example.com
# SOCKS5 for all protocols
curl --socks5-hostname 127.0.0.1:1080 https://example.comFor maximum reliability and performance, configure multiple workers:
# config.py
WORKERS = [
# Primary worker (US region)
{"url": "wss://us-worker.workers.dev", "password": "secure_password"},
# Backup worker (EU region)
{"url": "wss://eu-worker.workers.dev", "password": "secure_password"},
# Additional worker (Asia region)
{"url": "wss://asia-worker.workers.dev", "password": "secure_password"},
# Load balancing across multiple regions
{"url": "wss://worker1.example.com", "password": "secure_password"},
{"url": "wss://worker2.example.com", "password": "secure_password"},
{"url": "wss://worker3.example.com", "password": "secure_password"},
]For Maximum Reliability:
MAX_ATTEMPTS_PER_REQUEST = 5
CONNECT_TIMEOUT = 8
HALF_OPEN_AFTER_FAILS = 2
HEALTH_CHECK_INTERVAL = 15For Maximum Performance:
WRITE_BUFFER_MAX = 131072 # 128KB
WRITE_BUFFER_DELAY = 0.002 # 2ms
MAX_CONN_PER_WORKER = 300
COALESCE_MS = 2
COALESCE_MAX = 131072For Low Latency:
WRITE_BUFFER_DELAY = 0.001 # 1ms
WRITE_BUFFER_MAX = 8192 # 8KB
COALESCE_MS = 1
COALESCE_MAX = 81921. Connection Timeout
Error: ConnectionError: all workers failed
Solutions:
2. Authentication Failure
Error: invalid signature
Solutions:
3. WebSocket Connection Failed
Error: WebSocket connection failed
Solutions:
4. High Latency
Warning: Slow RTT detected
Solutions:
5. Memory Issues
MemoryError: Unable to allocate buffer
Solutions:
Enable Verbose Logging:
python batproxy.py -vCheck Worker Status:
# Access dashboard
curl http://127.0.0.1:8088/api/statsTest Worker Connectivity:
# Simple connectivity test
python -c "
import websockets
import asyncio
async def test():
try:
ws = await websockets.connect('wss://your-worker.workers.dev')
print('Connection successful')
await ws.close()
except Exception as e:
print(f'Connection failed: {e}')
asyncio.run(test())
"Monitor Logs:
# On Linux/macOS
tail -f /var/log/batproxy.log
# On Windows (PowerShell)
Get-Content -Path C:\batproxy\log.txt -WaitQ: What is the maximum throughput? A: The system can handle 1000+ concurrent connections with proper configuration. Throughput is typically limited by your network connection and Cloudflare's bandwidth limits.
Q: Can I use it for torrents or P2P? A: While technically possible, we recommend against it. Cloudflare Workers have usage limits, and P2P traffic may violate their terms of service.
Q: How much does it cost? A: Cloudflare Workers has a free tier with limited usage. Paid plans start at $5/month and offer higher limits.
Q: Can I run multiple clients? A: Yes, you can run multiple client instances on different ports, or share the same client across multiple applications.
Q: What happens if all workers fail? A: The client will return a 502 Bad Gateway response to the client application. All workers will go into cooldown and recovery.
Q: Does it support IPv6? A: Yes, both the client and Cloudflare Workers support IPv6 addressing.
Q: How do I update the worker code? A: Edit the code in Cloudflare dashboard and click "Save and Deploy". Wait 1-2 minutes for propagation.
| Back | FazBrowse Home | New Git URL |