-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathflareprox.py
More file actions
2253 lines (1905 loc) · 87.6 KB
/
flareprox.py
File metadata and controls
2253 lines (1905 loc) · 87.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
FlareProx - Simple URL Redirection via Cloudflare Workers
Redirect all traffic through Cloudflare Workers for any provided URL
"""
import argparse
import asyncio
import getpass
import json
import os
import random
import secrets
import requests
import string
import socket
import struct
import sys
import time
import contextlib
from typing import Dict, List, Optional, Tuple, Union
from urllib.parse import urlparse
from websockets.exceptions import ConnectionClosed
from websockets.legacy.client import WebSocketClientProtocol, connect as ws_connect
import ipaddress
# Global DNS resolution cache: hostname -> (ip, timestamp)
_dns_cache: Dict[str, Tuple[str, float]] = {}
_DNS_CACHE_TTL = 300 # 5 minutes
class FlareProxError(Exception):
"""Custom exception for FlareProx-specific errors."""
pass
class WorkerFallbackRequired(Exception):
"""Raised when the worker requests a relay fallback."""
def __init__(self, reason: str):
super().__init__(reason)
self.reason = reason
class TunnelSetupError(Exception):
"""Raised when an upstream tunnel cannot be established."""
pass
def resolve_hostname_to_ipv4(hostname: str, timeout: float = 5.0, use_cache: bool = True) -> Optional[str]:
"""
Resolve a hostname to its IPv4 address using Cloudflare DNS-over-HTTPS.
Forces IPv4-only resolution and caches results.
Args:
hostname: The hostname to resolve
timeout: Request timeout in seconds
use_cache: Whether to use cached results
Returns:
IPv4 address as string, or None if resolution fails
"""
# Check cache first
if use_cache:
cached = _dns_cache.get(hostname)
if cached:
ip, timestamp = cached
if time.time() - timestamp < _DNS_CACHE_TTL:
return ip
# Resolve via Cloudflare DoH
try:
doh_url = f"https://cloudflare-dns.com/dns-query?name={hostname}&type=A"
headers = {"Accept": "application/dns-json"}
response = requests.get(doh_url, headers=headers, timeout=timeout)
response.raise_for_status()
data = response.json()
# Check for successful DNS response
if data.get("Status") == 0 and data.get("Answer"):
# Find first IPv4 address in answers
for answer in data["Answer"]:
ip = answer.get("data", "")
# Validate IPv4 format
if ip and _is_valid_ipv4(ip):
# Cache the result
if use_cache:
_dns_cache[hostname] = (ip, time.time())
return ip
return None
except Exception:
# On error, return None (caller will handle)
return None
def _is_valid_ipv4(ip: str) -> bool:
"""Check if string is a valid IPv4 address."""
try:
parts = ip.split('.')
if len(parts) != 4:
return False
for part in parts:
num = int(part)
if num < 0 or num > 255:
return False
return True
except (ValueError, AttributeError):
return False
def check_if_cloudflare_ip(target: str, use_doh: bool = True, doh_timeout: float = 5.0) -> Tuple[bool, str]:
"""
Check if an IP address or hostname resolves to Cloudflare IP ranges.
Args:
target: IP address or hostname
use_doh: Whether to use DNS-over-HTTPS for resolution (default: True)
doh_timeout: Timeout for DoH requests in seconds (default: 5.0)
Returns:
Tuple of (is_cloudflare_ip, resolved_ip)
"""
# Try to parse as IP first
try:
ip_obj = ipaddress.ip_address(target)
is_cf = _is_cloudflare_ip_address(ip_obj)
return (is_cf, target)
except ValueError:
pass
# Not an IP, treat as hostname - resolve it
if use_doh:
resolved_ip = resolve_hostname_to_ipv4(target, timeout=doh_timeout)
if resolved_ip:
try:
ip_obj = ipaddress.ip_address(resolved_ip)
is_cf = _is_cloudflare_ip_address(ip_obj)
return (is_cf, resolved_ip)
except ValueError:
return (False, resolved_ip)
else:
# Resolution failed
return (False, target)
else:
# Fall back to standard DNS resolution
try:
resolved_ip = socket.gethostbyname(target)
ip_obj = ipaddress.ip_address(resolved_ip)
is_cf = _is_cloudflare_ip_address(ip_obj)
return (is_cf, resolved_ip)
except (socket.gaierror, socket.herror, ValueError):
return (False, target)
def _is_cloudflare_ip_address(ip: Union[ipaddress.IPv4Address, ipaddress.IPv6Address]) -> bool:
"""Check if an IP address object is in Cloudflare ranges."""
# Cloudflare IPv4 CIDR ranges
cf_ipv4 = (
"173.245.48.0/20",
"103.21.244.0/22",
"103.22.200.0/22",
"103.31.4.0/22",
"141.101.64.0/18",
"108.162.192.0/18",
"190.93.240.0/20",
"188.114.96.0/20",
"197.234.240.0/22",
"198.41.128.0/17",
"162.158.0.0/15",
"104.16.0.0/13",
"104.24.0.0/14",
"172.64.0.0/13",
"131.0.72.0/22",
)
# Cloudflare IPv6 CIDR ranges
cf_ipv6 = (
"2400:cb00::/32",
"2606:4700::/32",
"2803:f800::/32",
"2405:b500::/32",
"2405:8100::/32",
"2a06:98c0::/29",
"2c0f:f248::/32",
)
if isinstance(ip, ipaddress.IPv4Address):
# Use cached networks for performance
if not hasattr(_is_cloudflare_ip_address, '_cf_ipv4_networks'):
_is_cloudflare_ip_address._cf_ipv4_networks = [
ipaddress.ip_network(cidr) for cidr in cf_ipv4
]
return any(ip in network for network in _is_cloudflare_ip_address._cf_ipv4_networks)
else:
# IPv6
if not hasattr(_is_cloudflare_ip_address, '_cf_ipv6_networks'):
_is_cloudflare_ip_address._cf_ipv6_networks = [
ipaddress.ip_network(cidr) for cidr in cf_ipv6
]
return any(ip in network for network in _is_cloudflare_ip_address._cf_ipv6_networks)
class CloudflareManager:
"""Manages Cloudflare Worker deployments for FlareProx."""
def __init__(
self,
api_token: str,
account_id: str,
zone_id: Optional[str] = None,
worker_settings: Optional[Dict] = None
):
self.api_token = api_token
self.account_id = account_id
self.zone_id = zone_id
self.base_url = "https://api.cloudflare.com/client/v4"
self.headers = {
"Authorization": f"Bearer {api_token}",
"Content-Type": "application/json"
}
self._account_subdomain = None
self.worker_settings = worker_settings or {}
def _generate_subdomain_name(self) -> str:
"""Generate a subdomain name for new accounts."""
# Use first 10 chars of account ID + 3 random chars
account_prefix = self.account_id[:10].lower()
random_suffix = ''.join(random.choices(string.ascii_lowercase + string.digits, k=3))
return f"{account_prefix}-{random_suffix}"
def ensure_subdomain_provisioned(self) -> str:
"""Provision a workers.dev subdomain for the account if it doesn't exist."""
url = f"{self.base_url}/accounts/{self.account_id}/workers/subdomain"
# First, check if subdomain already exists
try:
response = requests.get(url, headers=self.headers, timeout=30)
if response.status_code == 200:
data = response.json()
subdomain = data.get("result", {}).get("subdomain")
if subdomain:
return subdomain
except requests.RequestException:
pass
# Subdomain doesn't exist, create it
subdomain_name = self._generate_subdomain_name()
try:
response = requests.put(
url,
headers=self.headers,
json={"subdomain": subdomain_name},
timeout=30
)
if response.status_code == 200:
data = response.json()
subdomain = data.get("result", {}).get("subdomain")
if subdomain:
print(f"\n ✓ Subdomain provisioned: {subdomain}.workers.dev\n")
return subdomain
elif response.status_code == 409:
# Error 10036: subdomain already exists
# This can happen if subdomain was created between our GET and PUT
# Try GET again to retrieve it
response = requests.get(url, headers=self.headers, timeout=30)
if response.status_code == 200:
data = response.json()
subdomain = data.get("result", {}).get("subdomain")
if subdomain:
return subdomain
raise FlareProxError(
"Subdomain already exists but couldn't retrieve it. "
"Please visit https://dash.cloudflare.com -> Workers & Pages"
)
else:
error_data = response.json() if response.content else {}
errors = error_data.get("errors", [])
error_msg = errors[0].get("message", "Unknown error") if errors else "Unknown error"
raise FlareProxError(
f"Failed to provision workers.dev subdomain (HTTP {response.status_code}): {error_msg}. "
"Please ensure your API token has 'Workers Scripts:Write' permission."
)
except requests.RequestException as e:
raise FlareProxError(
f"Network error while provisioning subdomain: {e}"
)
@property
def worker_subdomain(self) -> str:
"""Get the worker subdomain for workers.dev URLs."""
if self._account_subdomain:
return self._account_subdomain
# Try to get configured subdomain with retries
url = f"{self.base_url}/accounts/{self.account_id}/workers/subdomain"
max_retries = 3
for attempt in range(max_retries):
try:
response = requests.get(url, headers=self.headers, timeout=30)
if response.status_code == 200:
data = response.json()
subdomain = data.get("result", {}).get("subdomain")
if subdomain:
self._account_subdomain = subdomain
return subdomain
else:
# API succeeded but returned empty subdomain
if attempt < max_retries - 1:
time.sleep(1) # Wait before retry
continue
raise FlareProxError(
"Cloudflare API returned no workers.dev subdomain. "
"Your account should have a default subdomain assigned. "
"Please check https://dash.cloudflare.com -> Workers & Pages"
)
elif response.status_code == 404:
# Subdomain not provisioned yet - try to provision it automatically
if attempt == 0:
print("\n ⚙ Setting up workers.dev subdomain for your account...")
try:
subdomain = self.ensure_subdomain_provisioned()
if subdomain:
self._account_subdomain = subdomain
return subdomain
except FlareProxError as e:
# If provisioning fails, retry with GET in next attempt
if attempt < max_retries - 1:
time.sleep(2)
continue
raise
else:
# Already tried provisioning, just wait and retry
if attempt < max_retries - 1:
time.sleep(2)
continue
raise FlareProxError(
"Workers subdomain could not be provisioned automatically. "
"Please visit https://dash.cloudflare.com -> Workers & Pages to initialize your account."
)
else:
raise FlareProxError(
f"Failed to retrieve workers.dev subdomain (HTTP {response.status_code}). "
"Please check your API token has 'Workers Scripts:Read' permission."
)
except requests.RequestException as e:
if attempt < max_retries - 1:
time.sleep(1)
continue
raise FlareProxError(
f"Network error while retrieving workers.dev subdomain: {e}"
)
# Should never reach here due to raises above, but just in case
raise FlareProxError("Failed to retrieve workers.dev subdomain after retries")
def _generate_worker_name(self) -> str:
"""Generate a unique worker name."""
timestamp = str(int(time.time()))
random_suffix = ''.join(random.choices(string.ascii_lowercase, k=6))
return f"flareprox-{timestamp}-{random_suffix}"
def _get_worker_script(self) -> str:
"""Return the Cloudflare Worker script.
Modes:
- http (default): original HTTP proxy from upstream flareprox-main
- socks: minimal SOCKS-over-WebSocket bridge compatible with our client
"""
mode = (self.worker_settings.get("mode") or "http").lower()
if mode == "http":
# Module-style version of the original upstream HTTP proxy
return """
export default {
async fetch(request) {
try {
const url = new URL(request.url);
const targetUrl = getTargetUrl(url, request.headers);
if (!targetUrl) {
return createErrorResponse('No target URL specified', {
usage: {
query_param: '?url=https://example.com',
header: 'X-Target-URL: https://example.com',
path: '/https://example.com'
}
}, 400);
}
let targetURL;
try { targetURL = new URL(targetUrl); }
catch (e) { return createErrorResponse('Invalid target URL', { provided: targetUrl }, 400); }
const targetParams = new URLSearchParams();
for (const [key, value] of url.searchParams) {
if (!['url', '_cb', '_t'].includes(key)) {
targetParams.append(key, value);
}
}
if (targetParams.toString()) {
targetURL.search = targetParams.toString();
}
const proxyRequest = createProxyRequest(request, targetURL);
const response = await fetch(proxyRequest);
return createProxyResponse(response, request.method);
} catch (error) {
return createErrorResponse('Proxy request failed', { message: error.message, timestamp: new Date().toISOString() }, 500);
}
}
}
function getTargetUrl(url, headers) {
let targetUrl = url.searchParams.get('url');
if (!targetUrl) targetUrl = headers.get('X-Target-URL');
if (!targetUrl && url.pathname !== '/') {
const pathUrl = url.pathname.slice(1);
if (pathUrl.startsWith('http')) targetUrl = pathUrl;
}
return targetUrl;
}
function createProxyRequest(request, targetURL) {
const proxyHeaders = new Headers();
const allowedHeaders = ['accept','accept-language','accept-encoding','authorization','cache-control','content-type','origin','referer','user-agent'];
for (const [key, value] of request.headers) {
if (allowedHeaders.includes(key.toLowerCase())) proxyHeaders.set(key, value);
}
proxyHeaders.set('Host', targetURL.hostname);
const custom = request.headers.get('X-My-X-Forwarded-For');
proxyHeaders.set('X-Forwarded-For', custom || generateRandomIP());
return new Request(targetURL.toString(), { method: request.method, headers: proxyHeaders, body: ['GET','HEAD'].includes(request.method) ? null : request.body });
}
function createProxyResponse(response, requestMethod) {
const responseHeaders = new Headers();
for (const [key, value] of response.headers) {
if (!['content-encoding','content-length','transfer-encoding'].includes(key.toLowerCase())) {
responseHeaders.set(key, value);
}
}
responseHeaders.set('Access-Control-Allow-Origin', '*');
responseHeaders.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS, PATCH, HEAD');
responseHeaders.set('Access-Control-Allow-Headers', '*');
if (requestMethod === 'OPTIONS') return new Response(null, { status: 204, headers: responseHeaders });
return new Response(response.body, { status: response.status, statusText: response.statusText, headers: responseHeaders });
}
function createErrorResponse(error, details, status) {
return new Response(JSON.stringify({ error, ...details }), { status, headers: { 'Content-Type': 'application/json' } });
}
function generateRandomIP() {
return [1,2,3,4].map(() => Math.floor(Math.random()*255)+1).join('.');
}
"""
# SOCKS-over-WebSocket minimal bridge (keeps 'ready' control for client compatibility)
auth_token = json.dumps(self.worker_settings.get("auth_token", ""))
socks_password = json.dumps(self.worker_settings.get("socks_password", ""))
return ("""
import { connect } from 'cloudflare:sockets';
const AUTH_TOKEN = AUTH_TOKEN_PLACEHOLDER;
const SOCKS_PASSWORD = SOCKS_PASSWORD_PLACEHOLDER;
const textEncoder = new TextEncoder();
export default {
async fetch(request) {
if (AUTH_TOKEN && request.headers.get('Authorization') !== AUTH_TOKEN) {
return new Response('Unauthorized', { status: 401 });
}
if (request.headers.get('Upgrade') !== 'websocket') {
return new Response('Expected Upgrade: websocket', { status: 426 });
}
const pair = new WebSocketPair();
const [client, server] = Object.values(pair);
server.accept();
server.binaryType = 'arraybuffer';
server.addEventListener('message', async ({ data }) => {
try {
if (typeof data !== 'string') { server.close(1003, 'Invalid request'); return; }
const payload = JSON.parse(data);
const hostname = payload.hostname;
const port = Number(payload.port);
const password = payload.password ?? payload.psw ?? '';
if (!hostname || !Number.isInteger(port) || port < 1 || port > 65535) { server.close(1008, 'Invalid target'); return; }
if (SOCKS_PASSWORD && password !== SOCKS_PASSWORD) { server.close(1008, 'Invalid credentials'); return; }
let socket;
try { socket = connect({ hostname, port }); }
catch (e) { server.close(1011, 'Upstream connect failed'); return; }
// Minimal control for client handshake
try { server.send(JSON.stringify({ type: 'ready' })); } catch (_) {}
const inbound = new ReadableStream({
start(controller) {
server.addEventListener('message', event => {
const p = event.data;
if (typeof p === 'string') controller.enqueue(textEncoder.encode(p));
else if (p instanceof ArrayBuffer) controller.enqueue(new Uint8Array(p));
});
server.addEventListener('error', ev => controller.error(ev));
server.addEventListener('close', () => controller.close());
},
cancel() { try { socket && socket.close && socket.close(); } catch (_) {} }
});
inbound.pipeTo(socket.writable).catch(() => server.close(1011, 'Client error'));
socket.readable.pipeTo(new WritableStream({
write(chunk) { server.send(chunk instanceof ArrayBuffer ? chunk : new Uint8Array(chunk)); },
close() { server.close(); },
abort() { server.close(1011, 'Upstream aborted'); }
})).catch(() => server.close(1011, 'Upstream error'));
} catch (e) { server.close(1003, 'Invalid request'); }
}, { once: true });
return new Response(null, { status: 101, webSocket: client });
}
}
"""
).replace("AUTH_TOKEN_PLACEHOLDER", auth_token).replace("SOCKS_PASSWORD_PLACEHOLDER", socks_password)
def create_deployment(self, name: Optional[str] = None) -> Dict:
"""Deploy a new Cloudflare Worker."""
if not name:
name = self._generate_worker_name()
script_content = self._get_worker_script()
url = f"{self.base_url}/accounts/{self.account_id}/workers/scripts/{name}"
compatibility_flags = self.worker_settings.get("compatibility_flags", ["nodejs_compat"])
if isinstance(compatibility_flags, str):
compatibility_flags = [compatibility_flags]
elif not isinstance(compatibility_flags, list):
compatibility_flags = ["nodejs_compat"]
metadata = {
"main_module": "worker.js",
"compatibility_date": self.worker_settings.get("compatibility_date", "2023-09-04"),
"compatibility_flags": compatibility_flags
}
files = {
'metadata': (None, json.dumps(metadata), 'application/json'),
'worker.js': ('worker.js', script_content, 'application/javascript+module')
}
headers = {"Authorization": f"Bearer {self.api_token}"}
try:
response = requests.put(url, headers=headers, files=files, timeout=60)
response.raise_for_status()
except requests.HTTPError as e:
detail = ""
if e.response is not None:
try:
payload = e.response.json()
errors = payload.get("errors") if isinstance(payload, dict) else None
if errors:
detail = json.dumps(errors)
elif payload:
detail = json.dumps(payload)
except (ValueError, AttributeError):
detail = e.response.text
message = detail or str(e)
raise FlareProxError(f"Failed to create worker: {message}")
except requests.RequestException as e:
raise FlareProxError(f"Failed to create worker: {e}")
worker_data = response.json()
# Enable worker on subdomain - this is CRITICAL for subdomain to work
# On freshly provisioned subdomains, this may need a retry
subdomain_url = f"{self.base_url}/accounts/{self.account_id}/workers/scripts/{name}/subdomain"
max_retries = 3
for attempt in range(max_retries):
try:
response = requests.post(subdomain_url, headers=self.headers, json={"enabled": True}, timeout=30)
if response.status_code in [200, 201]:
break # Success!
elif attempt < max_retries - 1:
# Wait before retry
time.sleep(5)
else:
# Last attempt failed
print(f" ⚠ Could not enable worker on subdomain (HTTP {response.status_code})")
error_data = response.json() if response.content else {}
if error_data.get("errors"):
print(f" Error: {error_data['errors'][0].get('message', 'Unknown')}")
except requests.RequestException as e:
if attempt < max_retries - 1:
time.sleep(5)
else:
print(f" ⚠ Could not enable worker on subdomain: {e}")
worker_url = f"https://{name}.{self.worker_subdomain}.workers.dev"
return {
"name": name,
"url": worker_url,
"created_at": time.strftime('%Y-%m-%d %H:%M:%S'),
"id": worker_data.get("result", {}).get("id", name),
"auth_token": self.worker_settings.get("auth_token", ""),
"socks_password": self.worker_settings.get("socks_password", "")
}
def list_deployments(self) -> List[Dict]:
"""List all FlareProx deployments."""
url = f"{self.base_url}/accounts/{self.account_id}/workers/scripts"
try:
response = requests.get(url, headers=self.headers, timeout=30)
response.raise_for_status()
except requests.RequestException as e:
raise FlareProxError(f"Failed to list workers: {e}")
data = response.json()
workers = []
for script in data.get("result", []):
name = script.get("id", "")
if name.startswith("flareprox-"):
workers.append({
"name": name,
"url": f"https://{name}.{self.worker_subdomain}.workers.dev",
"created_at": script.get("created_on", "unknown")
})
return workers
def wait_for_worker_ready(self, worker_url: str, worker_name: str, max_wait_seconds: int = 600) -> bool:
"""
Wait for a worker to be fully provisioned and accessible.
Args:
worker_url: The full worker URL (e.g., https://worker.subdomain.workers.dev)
worker_name: The worker name for logging
max_wait_seconds: Maximum time to wait in seconds (default: 10 minutes)
Returns:
True if worker becomes ready, False if timeout
"""
import sys
start_time = time.time()
attempt = 0
check_interval = 2 # Check every 2 seconds
spinner = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']
spinner_idx = 0
while time.time() - start_time < max_wait_seconds:
try:
# Simple GET request to root to check if SSL/DNS is ready
response = requests.get(worker_url, timeout=10, allow_redirects=False)
# Any response (even 404 or 400) means the worker is accessible
return True
except requests.exceptions.SSLError:
# SSL not ready yet, keep waiting
pass
except requests.exceptions.ConnectionError:
# DNS/connection not ready yet, keep waiting
pass
except requests.RequestException:
# Other errors, consider worker ready (SSL/DNS working)
return True
# Show spinner animation
elapsed = int(time.time() - start_time)
msg = f'\r {spinner[spinner_idx % len(spinner)]} Waiting for worker to be ready... ({elapsed}s)'
sys.stdout.write(msg)
sys.stdout.flush()
spinner_idx += 1
time.sleep(0.5)
attempt += 1
# Check if we've exceeded max wait time
if time.time() - start_time >= max_wait_seconds:
sys.stdout.write('\r' + ' ' * 100 + '\r') # Clear line
sys.stdout.flush()
return False
sys.stdout.write('\r' + ' ' * 80 + '\r') # Clear line
sys.stdout.flush()
return False
def test_deployment(self, deployment_url: str, target_url: str, method: str = "GET") -> Dict:
"""Test a deployment endpoint."""
test_url = f"{deployment_url}?url={target_url}"
try:
response = requests.request(method, test_url, timeout=30)
return {
"success": True,
"status_code": response.status_code,
"response_length": len(response.content),
"headers": dict(response.headers)
}
except requests.RequestException as e:
return {
"success": False,
"error": str(e)
}
def delete_workers(self, worker_names: List[str]) -> Dict[str, bool]:
"""
Delete specific workers by name.
Args:
worker_names: List of worker names to delete
Returns:
Dictionary mapping worker names to success status
"""
results = {}
for name in worker_names:
url = f"{self.base_url}/accounts/{self.account_id}/workers/scripts/{name}"
try:
response = requests.delete(url, headers=self.headers, timeout=30)
if response.status_code in [200, 404]:
results[name] = True
else:
results[name] = False
except requests.RequestException:
results[name] = False
return results
def cleanup_all(self) -> None:
"""Delete all FlareProx workers."""
workers = self.list_deployments()
if not workers:
print(f" • No workers to delete")
return
print(f" Deleting {len(workers)} worker{'s' if len(workers) != 1 else ''}...\n")
deleted_count = 0
failed_count = 0
for i, worker in enumerate(workers, 1):
url = f"{self.base_url}/accounts/{self.account_id}/workers/scripts/{worker['name']}"
try:
response = requests.delete(url, headers=self.headers, timeout=30)
if response.status_code in [200, 404]:
print(f" ✓ [{i}/{len(workers)}] Deleted: {worker['name']}")
deleted_count += 1
else:
print(f" ✗ [{i}/{len(workers)}] Failed: {worker['name']}")
failed_count += 1
except requests.RequestException as e:
print(f" ✗ [{i}/{len(workers)}] Error: {worker['name']}")
failed_count += 1
print(f"\n Summary: {deleted_count} deleted, {failed_count} failed")
class LocalSocksServer:
def __init__(self, endpoint: Dict, worker_defaults: Dict, client_defaults: Dict, bind_host: str):
self.endpoint = dict(endpoint)
self.bind_host = bind_host
self.auth_token = self.endpoint.get("auth_token") or worker_defaults.get("auth_token", "")
self.socks_password = self.endpoint.get("socks_password") or worker_defaults.get("socks_password", "")
self.websocket_url = self._build_websocket_url(self.endpoint.get("url", ""))
self.name = self.endpoint.get("name", "unknown")
self._server: Optional[asyncio.AbstractServer] = None
self.port: Optional[int] = None
self.cf_override_ip = (client_defaults.get("cf_override_ip") or "").strip()
self.cf_hostnames = [h.lower() for h in client_defaults.get("cf_hostnames", []) if isinstance(h, str)]
relay_defaults = client_defaults.get("relay") if isinstance(client_defaults.get("relay"), dict) else {}
self.relay_config = dict(relay_defaults)
self.relay_url = (self.relay_config.get("url") or "").strip()
self.relay_auth_token = (self.relay_config.get("auth_token") or "").strip()
relay_password = (self.relay_config.get("socks_password") or "").strip()
self.relay_password = relay_password or self.socks_password
self.relay_enabled = bool(self.relay_config.get("enabled")) and bool(self.relay_url)
self.handshake_timeout = float(self.relay_config.get("handshake_timeout", client_defaults.get("handshake_timeout", 5.0)))
# Increase default buffer to 256KB to capture full TLS handshakes
replay_limit = self.relay_config.get("retry_buffer_bytes", 262144)
try:
replay_limit = int(replay_limit)
except (TypeError, ValueError):
replay_limit = 262144
self.replay_buffer_bytes = max(0, replay_limit)
# DoH settings
self.use_doh = bool(client_defaults.get("use_doh", True))
self.doh_timeout = float(client_defaults.get("doh_timeout", 5.0))
class _HandshakeState:
def __init__(self, limit: int) -> None:
self.limit = max(0, int(limit))
self._segments: List[bytes] = []
self._captured = 0
self._replay_consumed = False
self.confirmed = False
def record(self, chunk: bytes) -> None:
if self.confirmed or self._replay_consumed or self.limit == 0 or not chunk:
return
available = self.limit - self._captured
if available <= 0:
return
piece = bytes(chunk[:available])
if piece:
self._segments.append(piece)
self._captured += len(piece)
def mark_established(self) -> None:
if not self.confirmed:
self.confirmed = True
self._segments.clear()
@property
def has_replay(self) -> bool:
return not self.confirmed and not self._replay_consumed and bool(self._segments)
def consume(self) -> List[bytes]:
if not self.has_replay:
return []
self._replay_consumed = True
segments = list(self._segments)
self._segments.clear()
return segments
@staticmethod
def _parse_control_frame(message: str) -> Optional[Dict]:
if not message or len(message) > 65536:
return None
try:
data = json.loads(message)
except (TypeError, ValueError):
return None
if isinstance(data, dict) and isinstance(data.get("type"), str):
return data
return None
@staticmethod
def _build_websocket_url(url: str) -> str:
parsed = urlparse(url)
scheme = 'wss' if parsed.scheme == 'https' else 'ws'
path = parsed.path or ''
if parsed.query:
path = f"{path}?{parsed.query}"
if not parsed.netloc:
return url
return f"{scheme}://{parsed.netloc}{path}"
async def start(self, port_hint: Optional[int] = None) -> None:
if not self.websocket_url:
raise FlareProxError(f"Endpoint {self.name} does not have a valid URL.")
listen_port = port_hint if port_hint not in (None, 0) else 0
try:
self._server = await asyncio.start_server(self._handle_client, self.bind_host, listen_port)
except OSError:
if listen_port != 0:
self._server = await asyncio.start_server(self._handle_client, self.bind_host, 0)
else:
raise
sock = self._server.sockets[0].getsockname()
self.port = sock[1]
async def close(self) -> None:
if self._server:
self._server.close()
await self._server.wait_closed()
self._server = None
async def _handle_client(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
websocket: Optional[WebSocketClientProtocol] = None
peer = writer.get_extra_info('peername', 'unknown')
try:
result = await self._negotiate(reader, writer)
if not result:
return
hostname, port, request_data = result
# Check if target matches manual CF hostname list for override
connect_hostname = hostname
if self.cf_override_ip and self._matches_cf_host(hostname.lower()):
connect_hostname = self.cf_override_ip
try:
websocket, upstream_source = await self._connect_upstream(
connect_hostname, hostname, port
)
except TunnelSetupError:
await self._send_failure(writer)
return
await self._send_success(writer, request_data)
websocket = await self._bridge_streams(
reader,
writer,
websocket,
upstream_source,
hostname,
port
)
except Exception:
pass
finally:
with contextlib.suppress(Exception):
if websocket is not None:
await websocket.close()
with contextlib.suppress(Exception):
writer.close()
await writer.wait_closed()
async def _negotiate(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> Optional[Tuple[str, int, bytes]]:
try:
header = await reader.readexactly(2)
except asyncio.IncompleteReadError:
return None
version, method_count = header
if version != 5:
return None
try:
await reader.readexactly(method_count)
except asyncio.IncompleteReadError:
return None
writer.write(b"\x05\x00")
await writer.drain()
try:
request = await reader.readexactly(4)
except asyncio.IncompleteReadError:
return None
version, command, _, address_type = request
if version != 5 or command != 1:
await self._send_failure(writer, 0x07)
return None
# Build the full request data to echo back in success response
request_data = bytearray(request)
try:
if address_type == 1:
raw_address = await reader.readexactly(4)
hostname = socket.inet_ntoa(raw_address)
request_data.extend(raw_address)
elif address_type == 3:
length = await reader.readexactly(1)
raw_address = await reader.readexactly(length[0])
hostname = raw_address.decode("utf-8")
request_data.extend(length)
request_data.extend(raw_address)
elif address_type == 4:
raw_address = await reader.readexactly(16)
hostname = socket.inet_ntop(socket.AF_INET6, raw_address)
request_data.extend(raw_address)
else:
await self._send_failure(writer, 0x08)
return None
raw_port = await reader.readexactly(2)
port = struct.unpack(">H", raw_port)[0]
request_data.extend(raw_port)
except asyncio.IncompleteReadError:
return None
if port <= 0 or port > 65535:
await self._send_failure(writer, 0x09)
return None
return hostname, port, bytes(request_data)
async def _bridge_streams(
self,
reader: asyncio.StreamReader,
writer: asyncio.StreamWriter,
websocket: WebSocketClientProtocol,
upstream_source: str,
original_hostname: str,
port: int