megatrump commited on
Commit
1dbbd42
·
verified ·
1 Parent(s): 5d66f59

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +29 -22
app.py CHANGED
@@ -1,15 +1,15 @@
1
  import re
2
  from flask import Flask, request, Response
3
  import requests
 
4
 
5
  app = Flask(__name__)
6
 
7
- # --- 白名单过滤规则 (保持不变) ---
8
- # 这些规则现在将应用到从路径中解析出的完整URL上
9
  ALLOWED_PATTERNS = [
10
  re.compile(r'^https://github\.com/[^/]+/[^/]+/(?:releases|archive)/.*$', re.IGNORECASE),
11
  re.compile(r'^https://github\.com/[^/]+/[^/]+/(?:blob|raw)/.*$', re.IGNORECASE),
12
- re.compile(r'^https://github\.com/[^/]+/[^/]+/(?:info|git-).*/.*$', re.IGNORECASE),
13
  re.compile(r'^https://raw\.(?:githubusercontent|github)\.com/[^/]+/[^/]+/.*/.*$', re.IGNORECASE),
14
  re.compile(r'^https://gist\.(?:githubusercontent|github)\.com/[^/]+/[^/]+/.*/.*$', re.IGNORECASE),
15
  re.compile(r'^https://github\.com/[^/]+/[^/]+/tags.*$', re.IGNORECASE),
@@ -20,38 +20,43 @@ ALLOWED_PATTERNS = [
20
  ]
21
 
22
  def is_url_allowed(url):
23
- """检查给定的URL是否匹配白名单中的任何一个模式。"""
24
  for pattern in ALLOWED_PATTERNS:
25
  if pattern.match(url):
26
  return True
27
  return False
28
 
29
- # --- 核心代理逻辑 ---
30
 
31
- # 我们现在使用一个更通用的路由来捕获所有请求
32
- @app.route('/', defaults={'path': ''})
33
- @app.route('/<path:path>')
34
  def proxy(path):
35
  """
36
- 一个通用的反向代理,它将目标URL作为路径的一部分。
37
- 例如: /https://github.com/user/repo
38
  """
39
 
40
- # --- 1. 从请求路径中构建目标URL ---
41
- # 使用 request.full_path 来获取完整的路径和查询参数, e.g., /https://github.com/user/repo?service=...
42
  target_path = request.full_path
43
 
44
- # 移除开头的斜杠
45
  if target_path.startswith('/'):
46
  target_path = target_path[1:]
47
 
48
- # 如果路径本身不是一个完整的URL,则为其添加 https://
 
 
 
 
 
 
49
  if not target_path.startswith(('http://', 'https://')):
50
  target_url = 'https://' + target_path
51
  else:
52
  target_url = target_path
53
 
54
- # --- 2. 执行安全过滤检查 ---
55
  if not is_url_allowed(target_url):
56
  error_message = (
57
  "<h1>403 Forbidden</h1>"
@@ -60,13 +65,13 @@ def proxy(path):
60
  )
61
  return error_message, 403
62
 
63
- # --- 3. 转发请求 ---
64
- # 从目标URL中解析出Host头
65
  try:
66
- from urllib.parse import urlparse
67
  target_host = urlparse(target_url).hostname
68
- except Exception:
69
- return "Invalid target URL in path", 400
 
 
70
 
71
  headers = {key: value for (key, value) in request.headers if key.lower() != 'host'}
72
  headers['Host'] = target_host
@@ -79,7 +84,8 @@ def proxy(path):
79
  data=request.get_data(),
80
  cookies=request.cookies,
81
  allow_redirects=False,
82
- stream=True
 
83
  )
84
 
85
  excluded_headers = ['content-encoding', 'content-length', 'transfer-encoding', 'connection']
@@ -92,4 +98,5 @@ def proxy(path):
92
 
93
 
94
  if __name__ == '__main__':
95
- app.run(host='0.0.0.0', port=7860)
 
 
1
  import re
2
  from flask import Flask, request, Response
3
  import requests
4
+ from urllib.parse import urlparse
5
 
6
  app = Flask(__name__)
7
 
8
+ # --- Whitelist filtering rules (Unchanged) ---
 
9
  ALLOWED_PATTERNS = [
10
  re.compile(r'^https://github\.com/[^/]+/[^/]+/(?:releases|archive)/.*$', re.IGNORECASE),
11
  re.compile(r'^https://github\.com/[^/]+/[^/]+/(?:blob|raw)/.*$', re.IGNORECASE),
12
+ re.compile(r'^https://github\.com/[^/]+/[^/]+/(?:info|git-).*/.*$', re.IGNORECASE), # This is key for git clone
13
  re.compile(r'^https://raw\.(?:githubusercontent|github)\.com/[^/]+/[^/]+/.*/.*$', re.IGNORECASE),
14
  re.compile(r'^https://gist\.(?:githubusercontent|github)\.com/[^/]+/[^/]+/.*/.*$', re.IGNORECASE),
15
  re.compile(r'^https://github\.com/[^/]+/[^/]+/tags.*$', re.IGNORECASE),
 
20
  ]
21
 
22
  def is_url_allowed(url):
23
+ """Checks if the given URL matches any pattern in the whitelist."""
24
  for pattern in ALLOWED_PATTERNS:
25
  if pattern.match(url):
26
  return True
27
  return False
28
 
29
+ # --- Core Proxy Logic ---
30
 
31
+ # A single, consolidated route to capture all requests and methods
32
+ @app.route('/', defaults={'path': ''}, methods=['GET', 'POST', 'PUT', 'DELETE'])
33
+ @app.route('/<path:path>', methods=['GET', 'POST', 'PUT', 'DELETE'])
34
  def proxy(path):
35
  """
36
+ A universal reverse proxy that takes the target URL as part of the path.
 
37
  """
38
 
39
+ # --- 1. Construct target URL from the request path ---
40
+ # request.full_path includes the query string, which is essential for git
41
  target_path = request.full_path
42
 
43
+ # Remove the leading slash
44
  if target_path.startswith('/'):
45
  target_path = target_path[1:]
46
 
47
+ # If the path is empty (root request), return a simple landing page
48
+ if not target_path:
49
+ return ("<p>This is a GitHub reverse proxy. Usage:</p>"
50
+ "<p><code>&lt;proxy_url&gt;/&lt;target_github_url&gt;</code></p>"
51
+ "<p>Example: <code>/github.com/python/cpython.git</code></p>"), 200
52
+
53
+ # Prepend https:// if no scheme is present
54
  if not target_path.startswith(('http://', 'https://')):
55
  target_url = 'https://' + target_path
56
  else:
57
  target_url = target_path
58
 
59
+ # --- 2. Perform security filter check ---
60
  if not is_url_allowed(target_url):
61
  error_message = (
62
  "<h1>403 Forbidden</h1>"
 
65
  )
66
  return error_message, 403
67
 
68
+ # --- 3. Forward the request ---
 
69
  try:
 
70
  target_host = urlparse(target_url).hostname
71
+ if not target_host:
72
+ raise ValueError("Could not parse hostname from target URL")
73
+ except Exception as e:
74
+ return f"Invalid target URL in path: {e}", 400
75
 
76
  headers = {key: value for (key, value) in request.headers if key.lower() != 'host'}
77
  headers['Host'] = target_host
 
84
  data=request.get_data(),
85
  cookies=request.cookies,
86
  allow_redirects=False,
87
+ stream=True,
88
+ timeout=30 # Added a timeout for robustness
89
  )
90
 
91
  excluded_headers = ['content-encoding', 'content-length', 'transfer-encoding', 'connection']
 
98
 
99
 
100
  if __name__ == '__main__':
101
+ # For production, use a proper WSGI server like Gunicorn
102
+ app.run(host='0.0.0.0', port=7860)