-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
168 lines (148 loc) · 5.91 KB
/
Copy pathserver.py
File metadata and controls
168 lines (148 loc) · 5.91 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
import http.server
import json
import subprocess
import sys
import os
import tempfile
import socketserver
import time
from collections import defaultdict
try:
import resource as _resource
except ImportError:
_resource = None
MAX_CODE_SIZE = 30_000
BLOCKED_MODULES = [
'os', 'subprocess', 'shutil', 'ctypes', 'sys', 'socket',
'threading', 'multiprocessing', 'urllib', 'http.client',
'smtplib', 'ftplib', 'telnetlib', 'pathlib', 'glob',
'io', 'sqlite3', 'pickle', 'signal', 'asyncio',
'importlib', 'builtins', 'requests', 'httpx', 'aiohttp',
'urllib3', 'inspect', 'code', 'pdb', 'webbrowser',
'runpy', 'compileall', 'py_compile', 'zipimport',
'antigravity', 'turtle', 'tkinter',
]
BLOCKED_PATTERNS = [
'__import__', '__builtins__',
'exec(', 'eval(', 'compile(',
'open("/', "open('/", 'open("c:', "open('c:",
'open( "', "open( '", 'open(b"', "open(b'",
'breakpoint(', 'help(',
'vars(', 'globals(', 'locals(',
] + [f'import {m}' for m in BLOCKED_MODULES] \
+ [f'from {m}' for m in BLOCKED_MODULES]
RATE_LIMIT = 5
RATE_WINDOW = 60
BLACKLIST_TIME = 300
_rate_map = defaultdict(list)
_blacklist = {}
def is_rate_limited(ip):
now = time.time()
if ip in _blacklist:
if now - _blacklist[ip] < BLACKLIST_TIME:
return True
del _blacklist[ip]
_rate_map[ip] = [t for t in _rate_map[ip] if now - t < RATE_WINDOW]
if len(_rate_map[ip]) >= RATE_LIMIT:
_blacklist[ip] = now
return True
_rate_map[ip].append(now)
return False
def is_code_safe(code):
if len(code) > MAX_CODE_SIZE:
return False, f'Code exceeds maximum size of {MAX_CODE_SIZE} bytes'
lowered = code.lower()
for pat in BLOCKED_PATTERNS:
if pat in code or pat in lowered:
return False, f'Code contains blocked pattern: {pat}'
return True, ''
class Handler(http.server.SimpleHTTPRequestHandler):
ALLOWED_ORIGINS = ('https://majedql29-spec.github.io', 'https://jometcode.2bd.net', 'https://jometcode.onrender.com')
ALLOWED_ORIGIN = 'https://majedql29-spec.github.io'
def end_headers(self):
origin = self.headers.get('Origin', '')
if origin in self.ALLOWED_ORIGINS:
self.send_header('Access-Control-Allow-Origin', origin)
else:
self.send_header('Access-Control-Allow-Origin', self.ALLOWED_ORIGIN)
self.send_header('X-Content-Type-Options', 'nosniff')
self.send_header('X-Frame-Options', 'DENY')
self.send_header('Referrer-Policy', 'strict-origin-when-cross-origin')
super().end_headers()
def send_json(self, data, code=200):
self.send_response(code)
self.send_header('Content-Type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps(data).encode())
def send_error_json(self, msg, code=400):
self.send_json({'error': msg}, code)
MAX_BODY_SIZE = 50_000
def read_body(self):
length = int(self.headers.get('Content-Length', 0))
if length > self.MAX_BODY_SIZE:
raise ValueError('Request body too large')
return json.loads(self.rfile.read(length))
def do_OPTIONS(self):
self.send_response(200)
self.send_header('Access-Control-Allow-Methods', 'GET,POST,OPTIONS')
self.send_header('Access-Control-Allow-Headers', 'Content-Type,Authorization')
self.end_headers()
def do_POST(self):
if self.path == '/api/run':
ip = self.client_address[0]
if is_rate_limited(ip):
return self.send_json({'output': '', 'error': 'Rate limit exceeded (5 runs per minute)'})
try:
data = self.read_body()
except Exception:
return self.send_json({'output': '', 'error': 'Invalid request'})
code = data.get('code', '')
safe, reason = is_code_safe(code)
if not safe:
return self.send_json({'output': '', 'error': f'Security error: {reason}'})
fname = None
try:
with tempfile.NamedTemporaryFile(mode='w', suffix='.py', delete=False, encoding='utf-8') as f:
f.write(code); fname = f.name
kwargs = {}
if _resource:
kwargs['preexec_fn'] = lambda: (
_resource.setrlimit(_resource.RLIMIT_CPU, (5, 5)),
)
res = subprocess.run(
[sys.executable, '-I', '-u', fname],
capture_output=True, text=True, timeout=5, **kwargs
)
self.send_json({'output': res.stdout, 'error': res.stderr})
except subprocess.TimeoutExpired:
self.send_json({'output': '', 'error': 'Timeout (5 seconds)'})
except Exception:
self.send_json({'output': '', 'error': 'Execution error'})
finally:
if fname and os.path.exists(fname):
try: os.unlink(fname)
except: pass
else:
self.send_error_json('Not found')
def do_GET(self):
host = self.headers.get('Host', '')
if 'onrender.com' in host:
self.send_response(301)
self.send_header('Location', 'https://majedql29-spec.github.io/JometCode/')
self.end_headers()
return
if self.path == '/':
self.path = '/index.html'
if self.path.endswith('.py') or self.path.endswith('.env') or '.git' in self.path:
self.send_error(403)
return
return super().do_GET()
def log_message(self, format, *args): pass
PORT = int(os.environ.get('PORT', '8000'))
class ThreadedServer(socketserver.ThreadingMixIn, http.server.HTTPServer):
allow_reuse_address = True
daemon_threads = True
if __name__ == '__main__':
print(f'[SERVER] http://0.0.0.0:{PORT}')
sys.stdout.flush()
ThreadedServer(('0.0.0.0', PORT), Handler).serve_forever()