-
Notifications
You must be signed in to change notification settings - Fork 11
Collapse file tree
Files
Search this repository
/
Copy pathflareprox.py
More file actions
More file actions
Latest commit
795 lines (649 loc) · 27.4 KB
/
flareprox.py
File metadata and controls
795 lines (649 loc) · 27.4 KB
You must be signed in to make or propose changes
More edit options
Edit and raw actions
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
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
#!/usr/bin/env python3
"""
FlareProx - Simple URL Redirection via Cloudflare Workers
Redirect all traffic through Cloudflare Workers for any provided URL
"""
import argparse
import getpass
import json
import os
import random
import requests
import string
import time
from typing import Dict, List, Optional
class FlareProxError(Exception):
"""Custom exception for FlareProx-specific errors."""
pass
class CloudflareManager:
"""Manages Cloudflare Worker deployments for FlareProx."""
def __init__(self, api_token: str, account_id: str, zone_id: Optional[str] = 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
@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
url = f"{self.base_url}/accounts/{self.account_id}/workers/subdomain"
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
except requests.RequestException:
pass
# Fallback: use account ID as subdomain
self._account_subdomain = self.account_id.lower()
return self._account_subdomain
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 optimized Cloudflare Worker script."""
return '''/**
* FlareProx - Cloudflare Worker URL Redirection Script
*/
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(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)
}
// Build target URL with filtered query parameters
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()
}
// Create proxied request
const proxyRequest = createProxyRequest(request, targetURL)
const response = await fetch(proxyRequest)
// Process and return response
return createProxyResponse(response, request.method)
} catch (error) {
return createErrorResponse('Proxy request failed', {
message: error.message,
timestamp: new Date().toISOString()
}, 500)
}
}
function getTargetUrl(url, headers) {
// Priority: query param > header > path
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'
]
// Copy allowed headers
for (const [key, value] of request.headers) {
if (allowedHeaders.includes(key.toLowerCase())) {
proxyHeaders.set(key, value)
}
}
proxyHeaders.set('Host', targetURL.hostname)
// Set X-Forwarded-For header
const customXForwardedFor = request.headers.get('X-My-X-Forwarded-For')
if (customXForwardedFor) {
proxyHeaders.set('X-Forwarded-For', customXForwardedFor)
} else {
proxyHeaders.set('X-Forwarded-For', 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()
// Copy response headers (excluding problematic ones)
for (const [key, value] of response.headers) {
if (!['content-encoding', 'content-length', 'transfer-encoding'].includes(key.toLowerCase())) {
responseHeaders.set(key, value)
}
}
// Add CORS headers
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('.')
}'''
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}"
files = {
'metadata': (None, json.dumps({
"body_part": "script",
"main_module": "worker.js"
})),
'script': ('worker.js', script_content, 'application/javascript')
}
headers = {"Authorization": f"Bearer {self.api_token}"}
try:
response = requests.put(url, headers=headers, files=files, timeout=60)
response.raise_for_status()
except requests.RequestException as e:
raise FlareProxError(f"Failed to create worker: {e}")
worker_data = response.json()
# Enable subdomain
subdomain_url = f"{self.base_url}/accounts/{self.account_id}/workers/scripts/{name}/subdomain"
try:
requests.post(subdomain_url, headers=self.headers, json={"enabled": True}, timeout=30)
except requests.RequestException:
pass # Subdomain enabling is not critical
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)
}
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 test_deployment(self, deployment_url: str, target_url: str, method: str = "GET") -> Dict:
def show_detailed_help() -> None:
"""Display detailed help information."""
print("FlareProx - Detailed Help")
print("=" * 30)
print("\nFlareProx provides simple URL redirection through Cloudflare Workers.")
print("All traffic sent to your FlareProx endpoints will be redirected to")
print("the target URL you specify, supporting all HTTP methods.")
print("\nFeatures:")
print("- Support for all HTTP methods (GET, POST, PUT, DELETE, etc.)")
print("- Automatic CORS headers")
print("- IP masking through Cloudflare's global network")
print("- Simple URL-based redirection")
print("- Free tier: 100,000 requests/day")
def main():
"""Main entry point."""
parser = create_argument_parser()
args = parser.parse_args()
# Show help if no command provided
if not args.command:
show_help_message()
return
if args.command == "config":
show_config_help()
return
if args.command == "help":
show_detailed_help()
return
# Initialize FlareProx
try:
flareprox = FlareProx(config_file=args.config)
except Exception as e:
print(f"Configuration error: {e}")
return
if not flareprox.is_configured:
print("FlareProx not configured. Use 'python3 flareprox.py config' for setup.")
return
try:
if args.command == "create":
flareprox.create_proxies(args.count)
elif args.command == "list":
flareprox.list_proxies()
elif args.command == "test":
if args.url:
flareprox.test_proxies(args.url, args.method)
else:
flareprox.test_proxies() # Use default httpbin.org/ip
elif args.command == "cleanup":
confirm = input("Delete ALL FlareProx endpoints? (y/N): ")
if confirm.lower() == 'y':
flareprox.cleanup_all()
else:
print("Cleanup cancelled.")
except FlareProxError as e:
print(f"Error: {e}")
except KeyboardInterrupt:
print("\nOperation cancelled by user")
except Exception as e:
print(f"Unexpected error: {e}")
if __name__ == "__main__":
main()