j49_c commited on
Commit
4db7b7b
·
1 Parent(s): e237d7e

Production System Hardening: DNS fix, Performance monitoring, and Security updates

Browse files
Files changed (9) hide show
  1. .gitignore +4 -1
  2. Dockerfile +12 -5
  3. README.md +1 -2
  4. admin.html +26 -6
  5. app.py +180 -30
  6. dns_fix.py +99 -0
  7. index.html +94 -15
  8. pinger.py +23 -12
  9. requirements.txt +2 -1
.gitignore CHANGED
@@ -1,4 +1,7 @@
 
1
  __pycache__/
2
- USERS/
3
  *.pyc
 
 
 
4
  .env
 
1
+ .venv/
2
  __pycache__/
 
3
  *.pyc
4
+ DATA/
5
+ USERS/
6
+ *.log
7
  .env
Dockerfile CHANGED
@@ -1,26 +1,33 @@
1
- FROM python:3.9-slim
2
 
3
  RUN apt-get update && apt-get install -y \
4
  gcc \
5
  python3-dev \
 
 
 
6
  && rm -rf /var/lib/apt/lists/*
7
 
8
- # Create a user for Hugging Face (UID 1000 is required)
 
 
9
  RUN useradd -m -u 1000 user
10
  USER user
11
  ENV PATH="/home/user/.local/bin:$PATH"
12
 
13
  WORKDIR /app
14
 
15
- # Copy requirements first for better caching
16
  COPY --chown=user requirements.txt .
17
  RUN pip install --no-cache-dir --upgrade -r requirements.txt
18
 
19
- # Copy all files with correct ownership
20
  COPY --chown=user . .
21
 
22
- # Hugging Face uses port 7860 by default
23
  ENV SERVER_PORT=7860
 
 
24
  EXPOSE 7860
25
 
 
 
 
26
  CMD ["python", "app.py"]
 
1
+ FROM python:3.11-slim
2
 
3
  RUN apt-get update && apt-get install -y \
4
  gcc \
5
  python3-dev \
6
+ dnsutils \
7
+ ca-certificates \
8
+ curl \
9
  && rm -rf /var/lib/apt/lists/*
10
 
11
+ RUN printf "nameserver 8.8.8.8\nnameserver 8.8.4.4\nnameserver 1.1.1.1\n" > /etc/resolv.conf && \
12
+ chmod 666 /etc/resolv.conf
13
+
14
  RUN useradd -m -u 1000 user
15
  USER user
16
  ENV PATH="/home/user/.local/bin:$PATH"
17
 
18
  WORKDIR /app
19
 
 
20
  COPY --chown=user requirements.txt .
21
  RUN pip install --no-cache-dir --upgrade -r requirements.txt
22
 
 
23
  COPY --chown=user . .
24
 
 
25
  ENV SERVER_PORT=7860
26
+ ENV PYTHONUNBUFFERED=1
27
+ ENV PYTHONDONTWRITEBYTECODE=1
28
  EXPOSE 7860
29
 
30
+ HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
31
+ CMD curl -f http://localhost:7860/health || exit 1
32
+
33
  CMD ["python", "app.py"]
README.md CHANGED
@@ -11,5 +11,4 @@ pinned: false
11
  الذئب الابيض - @j49_c
12
 
13
  ### 🔗 روابط الوصول:
14
- * **الرابط المختصر:** [rb.gy/mqkfan](https://rb.gy/mqkfan)
15
- * **الرابط المباشر:** [hf.co/spaces/mohammed978/hostbot](https://huggingface.co/spaces/mohammed978/hostbot)
 
11
  الذئب الابيض - @j49_c
12
 
13
  ### 🔗 روابط الوصول:
14
+ * **الرابط المختصر:** [rb.gy/mqkfan](https://rb.gy/mqkfan)
 
admin.html CHANGED
@@ -338,14 +338,15 @@
338
  <div class="stat-footer" id="u_active_stat">0 Active Accounts</div>
339
  </div>
340
  <div class="stat-card">
341
- <div class="stat-label">System Health</div>
342
- <div class="stat-value" style="color:var(--success)">OPTIMAL</div>
343
- <div class="stat-footer">Handshake Latency: <span id="ping">...</span></div>
344
  </div>
345
  <div class="stat-card">
346
- <div class="stat-label">Quarantine</div>
347
- <div class="stat-value" id="st_ban" style="color:var(--error)">0</div>
348
- <div class="stat-footer">Restricted Access Nodes</div>
 
349
  </div>
350
  </div>
351
 
@@ -413,6 +414,25 @@
413
  document.getElementById('u_total').textContent = s.users_total || 0;
414
  document.getElementById('u_active_stat').textContent = `${s.users_active || 0} Active Accounts`;
415
  document.getElementById('ping').textContent = (Date.now() - startT) + 'ms';
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
416
  }
417
 
418
  async function refreshServers() {
 
338
  <div class="stat-footer" id="u_active_stat">0 Active Accounts</div>
339
  </div>
340
  <div class="stat-card">
341
+ <div class="stat-label">CPU Usage</div>
342
+ <div class="stat-value" id="sys_cpu" style="color:var(--success)">0%</div>
343
+ <div class="stat-footer">RAM: <span id="sys_ram">0</span> MB / <span id="sys_ram_total">0</span> MB</div>
344
  </div>
345
  <div class="stat-card">
346
+ <div class="stat-label">System Health</div>
347
+ <div class="stat-value" id="sys_health" style="color:var(--success)">OPTIMAL</div>
348
+ <div class="stat-footer">Disk: <span id="sys_disk">0</span>% | Banned: <span id="st_ban"
349
+ style="color:var(--error)">0</span> | Ping: <span id="ping">...</span></div>
350
  </div>
351
  </div>
352
 
 
414
  document.getElementById('u_total').textContent = s.users_total || 0;
415
  document.getElementById('u_active_stat').textContent = `${s.users_active || 0} Active Accounts`;
416
  document.getElementById('ping').textContent = (Date.now() - startT) + 'ms';
417
+ try {
418
+ const sr = await fetch('/api/system/status');
419
+ const sd = await sr.json();
420
+ if (sd.success) {
421
+ document.getElementById('sys_cpu').textContent = sd.cpu_percent + '%';
422
+ document.getElementById('sys_cpu').style.color = sd.cpu_percent > 80 ? 'var(--error)' : sd.cpu_percent > 50 ? 'var(--warning)' : 'var(--success)';
423
+ document.getElementById('sys_ram').textContent = sd.memory_used_mb;
424
+ document.getElementById('sys_ram_total').textContent = sd.memory_total_mb;
425
+ document.getElementById('sys_disk').textContent = sd.disk_percent;
426
+ const health = document.getElementById('sys_health');
427
+ if (sd.cpu_percent > 85 || sd.memory_percent > 90) {
428
+ health.textContent = 'CRITICAL'; health.style.color = 'var(--error)';
429
+ } else if (sd.cpu_percent > 60 || sd.memory_percent > 70) {
430
+ health.textContent = 'MODERATE'; health.style.color = 'var(--warning)';
431
+ } else {
432
+ health.textContent = 'OPTIMAL'; health.style.color = 'var(--success)';
433
+ }
434
+ }
435
+ } catch (e) { }
436
  }
437
 
438
  async function refreshServers() {
app.py CHANGED
@@ -8,13 +8,24 @@ import subprocess
8
  import threading
9
  import time
10
  import sys
 
 
11
  import requests
12
 
 
13
  import psutil
14
  from flask import Flask, send_from_directory, request, jsonify, redirect, session
15
  from werkzeug.security import generate_password_hash, check_password_hash
16
  from werkzeug.middleware.proxy_fix import ProxyFix
17
  from functools import wraps
 
 
 
 
 
 
 
 
18
 
19
  BASE_DIR = os.path.dirname(os.path.abspath(__file__))
20
 
@@ -32,14 +43,36 @@ app.config.update(
32
  SESSION_COOKIE_HTTPONLY=True,
33
  SESSION_COOKIE_SAMESITE='None',
34
  SESSION_COOKIE_SECURE=True,
35
- PERMANENT_SESSION_LIFETIME=604800 # 1 week
 
36
  )
37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
  @app.after_request
39
  def add_security_headers(response):
40
  response.headers['X-Content-Type-Options'] = 'nosniff'
41
  response.headers['X-XSS-Protection'] = '1; mode=block'
42
  response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'
 
 
43
  return response
44
 
45
  ADMIN_USERNAME = os.environ.get("ADMIN_USER", "moh777")
@@ -48,6 +81,9 @@ ADMIN_USERNAME = os.environ.get("ADMIN_USER", "moh777")
48
  # For maximum privacy, we will allow the admin password to be an environment variable.
49
  ADMIN_PASSWORD = os.environ.get("ADMIN_PASS", "Mm@123456")
50
 
 
 
 
51
  running_procs = {}
52
  server_states = {}
53
  lock = threading.Lock()
@@ -329,9 +365,23 @@ def ensure_requirements_installed(owner: str, folder: str):
329
  return False
330
 
331
 
 
 
 
 
 
 
 
332
  def start_with_autoinstall(owner: str, folder: str, startup_file: str):
333
- wrapper_code = r'''
334
- import runpy, sys, subprocess, traceback, re, os
 
 
 
 
 
 
 
335
  script = sys.argv[1]
336
  cwd = os.getcwd()
337
 
@@ -344,7 +394,7 @@ def append_installed(pkg):
344
  existing = set([x.strip() for x in f.read().splitlines() if x.strip()])
345
  if pkg and pkg not in existing:
346
  with open(p, "a", encoding="utf-8") as f:
347
- f.write(pkg + "\n")
348
  except:
349
  pass
350
 
@@ -352,7 +402,7 @@ def parse_missing_name(e):
352
  n = getattr(e, "name", None)
353
  if n: return n
354
  s = str(e)
355
- m = re.search(r"No module named '([^']+)'", s)
356
  if m: return m.group(1)
357
  return None
358
 
@@ -365,14 +415,14 @@ while True:
365
  if not pkg:
366
  traceback.print_exc()
367
  break
368
- print(f"[AUTO-INSTALL] Missing module: {pkg} -> installing...")
369
  try:
370
  subprocess.check_call([sys.executable, "-m", "pip", "install", pkg])
371
  append_installed(pkg)
372
- print(f"[AUTO-INSTALL] Installed: {pkg} ✅ -> restarting...")
373
  continue
374
  except Exception as ex:
375
- print(f"[AUTO-INSTALL] Failed: {ex}")
376
  traceback.print_exc()
377
  break
378
  except Exception:
@@ -388,6 +438,7 @@ while True:
388
  cwd=server_dir,
389
  stdout=log_file,
390
  stderr=log_file,
 
391
  )
392
  return proc, log_file
393
 
@@ -1013,42 +1064,141 @@ def admin_quickstats():
1013
 
1014
 
1015
  def run_keep_alive():
1016
- """Background thread to keep the server awake and monitor bots."""
1017
  port = int(os.environ.get("SERVER_PORT", 30170))
1018
- url = f"http://127.0.0.1:{port}/"
1019
-
1020
- print(f"[*] Starting Keep-Alive and Auto-Recovery system...")
1021
-
1022
  while True:
1023
  try:
1024
- # 1. Self-ping to prevent sleep
1025
  requests.get(url, timeout=10)
1026
-
1027
- # 2. Check and recover crashed bots (Auto-Recovery)
1028
- # This is a basic safety mechanism to restart nodes if they die unexpectedly
1029
  with lock:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1030
  for key, state in list(server_states.items()):
1031
  if state == "Running" and key not in running_procs:
1032
- # Found a bot that should be running but the process is missing
1033
- print(f"[!] Auto-Recovery: Restarting crashed node '{key}'")
1034
  try:
1035
- owner, folder = parse_server_key(key, allow_admin=True)
1036
  meta = read_meta(owner, folder)
1037
  startup = meta.get("startup_file")
1038
- if startup:
1039
  t = threading.Thread(target=background_start, args=(key, owner, folder, startup), daemon=True)
1040
  t.start()
1041
- except Exception as re:
1042
- print(f"[!] Recovery failed for '{key}': {re}")
1043
-
 
 
1044
  except Exception as e:
1045
- print(f"[!] Keep-Alive Error: {e}")
1046
-
1047
- time.sleep(300) # Check every 5 minutes
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1048
 
1049
  if __name__ == "__main__":
1050
- # Start the safety/keep-alive thread
1051
  threading.Thread(target=run_keep_alive, daemon=True).start()
1052
-
1053
  port = int(os.environ.get("SERVER_PORT", 30170))
1054
- app.run(host="0.0.0.0", port=port)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  import threading
9
  import time
10
  import sys
11
+ import signal
12
+ import logging
13
  import requests
14
 
15
+ import dns_fix
16
  import psutil
17
  from flask import Flask, send_from_directory, request, jsonify, redirect, session
18
  from werkzeug.security import generate_password_hash, check_password_hash
19
  from werkzeug.middleware.proxy_fix import ProxyFix
20
  from functools import wraps
21
+ from collections import defaultdict
22
+
23
+ logging.basicConfig(
24
+ level=logging.INFO,
25
+ format='[%(asctime)s] %(levelname)s: %(message)s',
26
+ datefmt='%Y-%m-%d %H:%M:%S'
27
+ )
28
+ logger = logging.getLogger('hostbot')
29
 
30
  BASE_DIR = os.path.dirname(os.path.abspath(__file__))
31
 
 
43
  SESSION_COOKIE_HTTPONLY=True,
44
  SESSION_COOKIE_SAMESITE='None',
45
  SESSION_COOKIE_SECURE=True,
46
+ PERMANENT_SESSION_LIFETIME=604800,
47
+ MAX_CONTENT_LENGTH=50 * 1024 * 1024
48
  )
49
 
50
+ _rate_store = defaultdict(list)
51
+ _rate_lock = threading.Lock()
52
+ RATE_LIMIT = 120
53
+ RATE_WINDOW = 60
54
+
55
+
56
+ def rate_limited(fn):
57
+ @wraps(fn)
58
+ def wrapper(*args, **kwargs):
59
+ ip = request.remote_addr or '0.0.0.0'
60
+ now = time.time()
61
+ with _rate_lock:
62
+ _rate_store[ip] = [t for t in _rate_store[ip] if now - t < RATE_WINDOW]
63
+ if len(_rate_store[ip]) >= RATE_LIMIT:
64
+ return jsonify({"success": False, "message": "Rate limit exceeded"}), 429
65
+ _rate_store[ip].append(now)
66
+ return fn(*args, **kwargs)
67
+ return wrapper
68
+
69
  @app.after_request
70
  def add_security_headers(response):
71
  response.headers['X-Content-Type-Options'] = 'nosniff'
72
  response.headers['X-XSS-Protection'] = '1; mode=block'
73
  response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'
74
+ response.headers['X-Frame-Options'] = 'SAMEORIGIN'
75
+ response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'
76
  return response
77
 
78
  ADMIN_USERNAME = os.environ.get("ADMIN_USER", "moh777")
 
81
  # For maximum privacy, we will allow the admin password to be an environment variable.
82
  ADMIN_PASSWORD = os.environ.get("ADMIN_PASS", "Mm@123456")
83
 
84
+ MAX_PROCESS_MEMORY_MB = int(os.environ.get("MAX_PROC_MEM_MB", 512))
85
+ MAX_LOG_SIZE = 2 * 1024 * 1024
86
+
87
  running_procs = {}
88
  server_states = {}
89
  lock = threading.Lock()
 
365
  return False
366
 
367
 
368
+ def get_subprocess_env():
369
+ env = os.environ.copy()
370
+ env['PYTHONUNBUFFERED'] = '1'
371
+ env['PYTHONDONTWRITEBYTECODE'] = '1'
372
+ return env
373
+
374
+
375
  def start_with_autoinstall(owner: str, folder: str, startup_file: str):
376
+ dns_fix_path = os.path.join(BASE_DIR, 'dns_fix.py')
377
+ wrapper_code = f'''
378
+ import sys, os
379
+ sys.path.insert(0, "{BASE_DIR}")
380
+ try:
381
+ import dns_fix
382
+ except:
383
+ pass
384
+ import runpy, subprocess, traceback, re
385
  script = sys.argv[1]
386
  cwd = os.getcwd()
387
 
 
394
  existing = set([x.strip() for x in f.read().splitlines() if x.strip()])
395
  if pkg and pkg not in existing:
396
  with open(p, "a", encoding="utf-8") as f:
397
+ f.write(pkg + "\\n")
398
  except:
399
  pass
400
 
 
402
  n = getattr(e, "name", None)
403
  if n: return n
404
  s = str(e)
405
+ m = re.search(r"No module named \'([^\']+)\'", s)
406
  if m: return m.group(1)
407
  return None
408
 
 
415
  if not pkg:
416
  traceback.print_exc()
417
  break
418
+ print(f"[AUTO-INSTALL] Missing module: {{pkg}} -> installing...")
419
  try:
420
  subprocess.check_call([sys.executable, "-m", "pip", "install", pkg])
421
  append_installed(pkg)
422
+ print(f"[AUTO-INSTALL] Installed: {{pkg}} -> restarting...")
423
  continue
424
  except Exception as ex:
425
+ print(f"[AUTO-INSTALL] Failed: {{ex}}")
426
  traceback.print_exc()
427
  break
428
  except Exception:
 
438
  cwd=server_dir,
439
  stdout=log_file,
440
  stderr=log_file,
441
+ env=get_subprocess_env(),
442
  )
443
  return proc, log_file
444
 
 
1064
 
1065
 
1066
  def run_keep_alive():
 
1067
  port = int(os.environ.get("SERVER_PORT", 30170))
1068
+ url = f"http://127.0.0.1:{port}/health"
1069
+ logger.info("Keep-Alive and Auto-Recovery system started")
 
 
1070
  while True:
1071
  try:
 
1072
  requests.get(url, timeout=10)
 
 
 
1073
  with lock:
1074
+ for key in list(running_procs.keys()):
1075
+ proc, logf = running_procs[key]
1076
+ if not psutil.pid_exists(proc.pid) or proc.poll() is not None:
1077
+ logger.info(f"Process dead for '{key}', cleaning up")
1078
+ try:
1079
+ logf.close()
1080
+ except Exception:
1081
+ pass
1082
+ running_procs.pop(key, None)
1083
+ server_states[key] = "Offline"
1084
+ else:
1085
+ try:
1086
+ p = psutil.Process(proc.pid)
1087
+ mem_mb = p.memory_info().rss / 1024 / 1024
1088
+ if mem_mb > MAX_PROCESS_MEMORY_MB:
1089
+ logger.warning(f"Process '{key}' using {mem_mb:.0f}MB, killing")
1090
+ for child in p.children(recursive=True):
1091
+ child.kill()
1092
+ p.kill()
1093
+ running_procs.pop(key, None)
1094
+ server_states[key] = "Offline"
1095
+ log_append(key, f"[SYSTEM] Killed: memory limit exceeded ({mem_mb:.0f}MB)\n")
1096
+ except Exception:
1097
+ pass
1098
  for key, state in list(server_states.items()):
1099
  if state == "Running" and key not in running_procs:
1100
+ logger.info(f"Auto-Recovery: restarting '{key}'")
 
1101
  try:
1102
+ owner, folder = key.split("::", 1) if "::" in key else (ADMIN_USERNAME, key)
1103
  meta = read_meta(owner, folder)
1104
  startup = meta.get("startup_file")
1105
+ if startup and not meta.get("banned", False):
1106
  t = threading.Thread(target=background_start, args=(key, owner, folder, startup), daemon=True)
1107
  t.start()
1108
+ else:
1109
+ server_states[key] = "Offline"
1110
+ except Exception as e:
1111
+ logger.error(f"Recovery failed for '{key}': {e}")
1112
+ server_states[key] = "Offline"
1113
  except Exception as e:
1114
+ logger.error(f"Keep-Alive Error: {e}")
1115
+ time.sleep(300)
1116
+
1117
+
1118
+ def truncate_large_logs():
1119
+ if not os.path.isdir(USERS_ROOT):
1120
+ return
1121
+ for owner in os.listdir(USERS_ROOT):
1122
+ root = get_user_servers_root(owner)
1123
+ if not os.path.isdir(root):
1124
+ continue
1125
+ for folder in os.listdir(root):
1126
+ log_path = os.path.join(get_server_dir(owner, folder), "server.log")
1127
+ try:
1128
+ if os.path.exists(log_path) and os.path.getsize(log_path) > MAX_LOG_SIZE:
1129
+ with open(log_path, 'r', encoding='utf-8', errors='ignore') as f:
1130
+ f.seek(os.path.getsize(log_path) - MAX_LOG_SIZE // 2)
1131
+ content = f.read()
1132
+ with open(log_path, 'w', encoding='utf-8') as f:
1133
+ f.write("[SYSTEM] Log truncated\n" + content)
1134
+ except Exception:
1135
+ pass
1136
+
1137
+
1138
+ def run_log_cleaner():
1139
+ while True:
1140
+ time.sleep(600)
1141
+ truncate_large_logs()
1142
+
1143
+
1144
+ @app.route("/health")
1145
+ def health_check():
1146
+ return jsonify({"status": "ok", "uptime": time.time()})
1147
+
1148
+
1149
+ @app.route("/api/system/status")
1150
+ @admin_required
1151
+ def system_status():
1152
+ try:
1153
+ cpu = psutil.cpu_percent(interval=0.5)
1154
+ mem = psutil.virtual_memory()
1155
+ disk = psutil.disk_usage('/')
1156
+ procs = len(running_procs)
1157
+ return jsonify({
1158
+ "success": True,
1159
+ "cpu_percent": cpu,
1160
+ "memory_used_mb": round(mem.used / 1024 / 1024),
1161
+ "memory_total_mb": round(mem.total / 1024 / 1024),
1162
+ "memory_percent": mem.percent,
1163
+ "disk_used_gb": round(disk.used / 1024 / 1024 / 1024, 1),
1164
+ "disk_total_gb": round(disk.total / 1024 / 1024 / 1024, 1),
1165
+ "disk_percent": round(disk.percent, 1),
1166
+ "running_processes": procs
1167
+ })
1168
+ except Exception as e:
1169
+ return jsonify({"success": False, "message": str(e)}), 500
1170
+
1171
+
1172
+ def graceful_shutdown(signum, frame):
1173
+ logger.info("Shutting down gracefully...")
1174
+ with lock:
1175
+ for key in list(running_procs.keys()):
1176
+ stop_proc(key)
1177
+ logger.info("All processes stopped.")
1178
+ sys.exit(0)
1179
+
1180
+
1181
+ signal.signal(signal.SIGTERM, graceful_shutdown)
1182
+ signal.signal(signal.SIGINT, graceful_shutdown)
1183
 
1184
  if __name__ == "__main__":
 
1185
  threading.Thread(target=run_keep_alive, daemon=True).start()
1186
+ threading.Thread(target=run_log_cleaner, daemon=True).start()
1187
  port = int(os.environ.get("SERVER_PORT", 30170))
1188
+ logger.info(f"Starting server on port {port}")
1189
+ try:
1190
+ from gunicorn.app.wsgiapp import run as gunicorn_run
1191
+ sys.argv = [
1192
+ 'gunicorn',
1193
+ '--bind', f'0.0.0.0:{port}',
1194
+ '--worker-class', 'gthread',
1195
+ '--workers', '1',
1196
+ '--threads', '8',
1197
+ '--timeout', '120',
1198
+ '--preload',
1199
+ 'app:app'
1200
+ ]
1201
+ gunicorn_run()
1202
+ except ImportError:
1203
+ logger.info("Gunicorn not found, using Flask dev server")
1204
+ app.run(host="0.0.0.0", port=port)
dns_fix.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import socket
2
+ import struct
3
+ import random
4
+ import os
5
+
6
+ _orig_getaddrinfo = socket.getaddrinfo
7
+ _dns_cache = {}
8
+ _DNS_SERVERS = ['8.8.8.8', '8.8.4.4', '1.1.1.1']
9
+
10
+
11
+ def _raw_dns_resolve(hostname, dns_server='8.8.8.8'):
12
+ try:
13
+ tid = random.randint(0, 65535)
14
+ header = struct.pack('!HHHHHH', tid, 0x0100, 1, 0, 0, 0)
15
+ question = b''
16
+ for label in hostname.encode('ascii').split(b'.'):
17
+ question += bytes([len(label)]) + label
18
+ question += b'\x00' + struct.pack('!HH', 1, 1)
19
+ sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
20
+ sock.settimeout(5)
21
+ sock.sendto(header + question, (dns_server, 53))
22
+ data, _ = sock.recvfrom(4096)
23
+ sock.close()
24
+ an_count = struct.unpack('!H', data[6:8])[0]
25
+ if an_count == 0:
26
+ return None
27
+ pos = 12
28
+ while data[pos] != 0:
29
+ pos += data[pos] + 1
30
+ pos += 5
31
+ for _ in range(an_count):
32
+ if data[pos] & 0xC0 == 0xC0:
33
+ pos += 2
34
+ else:
35
+ while data[pos] != 0:
36
+ pos += data[pos] + 1
37
+ pos += 1
38
+ rtype, _, _, rdlen = struct.unpack('!HHIH', data[pos:pos + 10])
39
+ pos += 10
40
+ if rtype == 1 and rdlen == 4:
41
+ return '.'.join(str(b) for b in data[pos:pos + 4])
42
+ pos += rdlen
43
+ return None
44
+ except Exception:
45
+ return None
46
+
47
+
48
+ def _patched_getaddrinfo(host, port, family=0, type=0, proto=0, flags=0):
49
+ try:
50
+ return _orig_getaddrinfo(host, port, family, type, proto, flags)
51
+ except socket.gaierror as e:
52
+ if not isinstance(host, str) or host.replace('.', '').isdigit():
53
+ raise e
54
+ cache_key = f"{host}:{port}"
55
+ if cache_key in _dns_cache:
56
+ ip = _dns_cache[cache_key]
57
+ else:
58
+ ip = None
59
+ for dns in _DNS_SERVERS:
60
+ ip = _raw_dns_resolve(host, dns)
61
+ if ip:
62
+ _dns_cache[cache_key] = ip
63
+ break
64
+ if ip:
65
+ results = []
66
+ if type == 0 or type == socket.SOCK_STREAM:
67
+ results.append((socket.AF_INET, socket.SOCK_STREAM, 6, '', (ip, port or 443)))
68
+ if type == 0 or type == socket.SOCK_DGRAM:
69
+ results.append((socket.AF_INET, socket.SOCK_DGRAM, 17, '', (ip, port or 443)))
70
+ if results:
71
+ return results
72
+ raise e
73
+
74
+
75
+ def _fix_resolv_conf():
76
+ dns_content = "nameserver 8.8.8.8\nnameserver 8.8.4.4\nnameserver 1.1.1.1\n"
77
+ try:
78
+ path = '/etc/resolv.conf'
79
+ need_fix = False
80
+ if os.path.exists(path):
81
+ with open(path, 'r') as f:
82
+ content = f.read().strip()
83
+ if not content or 'nameserver' not in content:
84
+ need_fix = True
85
+ else:
86
+ need_fix = True
87
+ if need_fix:
88
+ with open(path, 'w') as f:
89
+ f.write(dns_content)
90
+ except (PermissionError, OSError):
91
+ pass
92
+
93
+
94
+ def apply():
95
+ _fix_resolv_conf()
96
+ socket.getaddrinfo = _patched_getaddrinfo
97
+
98
+
99
+ apply()
index.html CHANGED
@@ -631,10 +631,70 @@
631
  resize: none;
632
  line-height: 1.6;
633
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
634
  </style>
635
  </head>
636
 
637
  <body>
 
638
  <div class="topbar">
639
  <div class="topbar-content">
640
  <div class="brand" onclick="goHome()">
@@ -698,6 +758,11 @@
698
  <div class="stat-val"><span class="stat-label">MEMORY</span><span class="stat-num" id="memTxt">0.0
699
  MB</span></div>
700
  </div>
 
 
 
 
 
701
  <div class="stat-row">
702
  <div class="ico-box">🌐</div>
703
  <div class="stat-val"><span class="stat-label">IP ADDRESS</span><span class="stat-num"
@@ -848,6 +913,7 @@
848
  document.getElementById('logOut').textContent = d.logs || "ESTABLISHING VIRTUAL LINK...";
849
  document.getElementById('statusTxt').textContent = (d.status || 'OFFLINE').toUpperCase();
850
  document.getElementById('memTxt').textContent = d.mem || '0.0 MB';
 
851
  document.getElementById('ipTxt').textContent = d.ip || '0.0.0.0';
852
  const running = ['running', 'installing', 'starting'].includes(d.status.toLowerCase());
853
  document.getElementById('btnStart').disabled = running;
@@ -900,12 +966,25 @@
900
  document.getElementById('editor-view').style.display = 'flex';
901
  }
902
  function closeEditor() { document.getElementById('editor-view').style.display = 'none'; }
 
 
 
 
 
 
 
 
 
903
  async function saveFile() {
904
- await fetch(`/files/save/${encodeURIComponent(currentSrv.key || currentSrv.folder)}`, {
905
- method: 'POST', headers: { 'Content-Type': 'application/json' },
906
- body: JSON.stringify({ file: currentFile, content: document.getElementById('ed-area').value })
907
- });
908
- alert("BLOCK WRITTEN ✅");
 
 
 
 
909
  }
910
 
911
  function openM(t, v, cb) {
@@ -916,26 +995,26 @@
916
  }
917
  function closeM() { document.getElementById('modalOverlay').style.display = 'none'; }
918
 
919
- async function renameDir(n) { openM("Rename Directory", n, async v => { await fetch(`/files/rename/${encodeURIComponent(currentSrv.key || currentSrv.folder)}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ path: currentPath, old: n, new: v }) }); loadFiles(); closeM(); }); }
920
- async function deleteDir(n) { if (confirm(`PURGE DIRECTORY '${n}'?`)) { await fetch(`/files/delete/${encodeURIComponent(currentSrv.key || currentSrv.folder)}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ path: currentPath, name: n, kind: 'dir' }) }); loadFiles(); } }
921
- async function renameFilePrompt(n) { openM("Rename File", n, async v => { await fetch(`/files/rename/${encodeURIComponent(currentSrv.key || currentSrv.folder)}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ path: currentPath, old: n, new: v }) }); loadFiles(); closeM(); }); }
922
- async function deleteFilePrompt(n) { if (confirm(`PURGE FILE '${n}'?`)) { await fetch(`/files/delete/${encodeURIComponent(currentSrv.key || currentSrv.folder)}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ path: currentPath, name: n, kind: 'file' }) }); loadFiles(); } }
923
 
924
- async function doUploadFiles(inp) { let fd = new FormData(); for (let f of inp.files) fd.append("files", f); await fetch(`/files/upload/${encodeURIComponent(currentSrv.key || currentSrv.folder)}?path=${encodeURIComponent(currentPath)}`, { method: "POST", body: fd }); loadFiles(); }
925
- async function doUploadFolder(inp) { let fd = new FormData(); for (let f of inp.files) { fd.append("files", f); fd.append("relpaths", f.webkitRelativePath || f.name); } await fetch(`/files/upload/${encodeURIComponent(currentSrv.key || currentSrv.folder)}?path=${encodeURIComponent(currentPath)}`, { method: "POST", body: fd }); loadFiles(); }
926
 
927
- async function changeStartup() { openM("Set Entrypoint", currentSrv.startup_file, async v => { await fetch(`/server/set-startup/${encodeURIComponent(currentSrv.key || currentSrv.folder)}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ file: v }) }); currentSrv.startup_file = v; document.getElementById('mainFileTxt').textContent = v; closeM(); }); }
928
- async function deleteServer() { if (confirm("ABSOLUTE DATA DESTRUCTION?")) { await fetch(`/server/delete/${encodeURIComponent(currentSrv.key || currentSrv.folder)}`, { method: 'POST' }); goHome(); } }
929
 
930
  document.getElementById('newBtn').onclick = () => openM("INIT NEW ENGINE", "", async v => {
931
  const r = await fetch('/add', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: v }) });
932
  const d = await r.json();
933
- if (d.success) { closeM(); loadServers(); } else alert(d.message);
934
  });
935
 
936
  document.addEventListener('DOMContentLoaded', () => { loadServers(); loadPythonHost(); });
 
937
 
938
- // --- SECURITY PROTOCOL: ANTI-INSPECTION ---
939
  document.addEventListener('contextmenu', e => e.preventDefault());
940
  document.onkeydown = function (e) {
941
  if (e.keyCode == 123) return false;
 
631
  resize: none;
632
  line-height: 1.6;
633
  }
634
+
635
+ .toast-container {
636
+ position: fixed;
637
+ top: 80px;
638
+ right: 24px;
639
+ z-index: 9999;
640
+ display: flex;
641
+ flex-direction: column;
642
+ gap: 10px;
643
+ }
644
+
645
+ .toast {
646
+ background: rgba(20, 20, 25, 0.95);
647
+ backdrop-filter: blur(20px);
648
+ border: 1px solid var(--border);
649
+ border-radius: var(--radius-sm);
650
+ padding: 14px 20px;
651
+ font-size: 13px;
652
+ font-weight: 600;
653
+ color: var(--text);
654
+ animation: toastIn 0.3s ease, toastOut 0.3s ease 2.7s;
655
+ max-width: 360px;
656
+ box-shadow: 0 10px 30px rgba(0, 0, 0, 0.5);
657
+ }
658
+
659
+ .toast.success {
660
+ border-left: 3px solid var(--success);
661
+ }
662
+
663
+ .toast.error {
664
+ border-left: 3px solid var(--error);
665
+ }
666
+
667
+ .toast.info {
668
+ border-left: 3px solid var(--primary);
669
+ }
670
+
671
+ @keyframes toastIn {
672
+ from {
673
+ opacity: 0;
674
+ transform: translateX(30px);
675
+ }
676
+
677
+ to {
678
+ opacity: 1;
679
+ transform: translateX(0);
680
+ }
681
+ }
682
+
683
+ @keyframes toastOut {
684
+ from {
685
+ opacity: 1;
686
+ }
687
+
688
+ to {
689
+ opacity: 0;
690
+ transform: translateY(-10px);
691
+ }
692
+ }
693
  </style>
694
  </head>
695
 
696
  <body>
697
+ <div class="toast-container" id="toastBox"></div>
698
  <div class="topbar">
699
  <div class="topbar-content">
700
  <div class="brand" onclick="goHome()">
 
758
  <div class="stat-val"><span class="stat-label">MEMORY</span><span class="stat-num" id="memTxt">0.0
759
  MB</span></div>
760
  </div>
761
+ <div class="stat-row">
762
+ <div class="ico-box">⚙️</div>
763
+ <div class="stat-val"><span class="stat-label">CPU</span><span class="stat-num" id="cpuTxt">0%</span>
764
+ </div>
765
+ </div>
766
  <div class="stat-row">
767
  <div class="ico-box">🌐</div>
768
  <div class="stat-val"><span class="stat-label">IP ADDRESS</span><span class="stat-num"
 
913
  document.getElementById('logOut').textContent = d.logs || "ESTABLISHING VIRTUAL LINK...";
914
  document.getElementById('statusTxt').textContent = (d.status || 'OFFLINE').toUpperCase();
915
  document.getElementById('memTxt').textContent = d.mem || '0.0 MB';
916
+ document.getElementById('cpuTxt').textContent = d.cpu || '0%';
917
  document.getElementById('ipTxt').textContent = d.ip || '0.0.0.0';
918
  const running = ['running', 'installing', 'starting'].includes(d.status.toLowerCase());
919
  document.getElementById('btnStart').disabled = running;
 
966
  document.getElementById('editor-view').style.display = 'flex';
967
  }
968
  function closeEditor() { document.getElementById('editor-view').style.display = 'none'; }
969
+ function toast(msg, type = 'info') {
970
+ const box = document.getElementById('toastBox');
971
+ const t = document.createElement('div');
972
+ t.className = `toast ${type}`;
973
+ t.textContent = msg;
974
+ box.appendChild(t);
975
+ setTimeout(() => t.remove(), 3000);
976
+ }
977
+
978
  async function saveFile() {
979
+ try {
980
+ const r = await fetch(`/files/save/${encodeURIComponent(currentSrv.key || currentSrv.folder)}`, {
981
+ method: 'POST', headers: { 'Content-Type': 'application/json' },
982
+ body: JSON.stringify({ file: currentFile, content: document.getElementById('ed-area').value })
983
+ });
984
+ const d = await r.json();
985
+ if (d.success) toast('FILE SAVED', 'success');
986
+ else toast(d.message || 'Save failed', 'error');
987
+ } catch (e) { toast('Network error', 'error'); }
988
  }
989
 
990
  function openM(t, v, cb) {
 
995
  }
996
  function closeM() { document.getElementById('modalOverlay').style.display = 'none'; }
997
 
998
+ async function renameDir(n) { openM("Rename Directory", n, async v => { await fetch(`/files/rename/${encodeURIComponent(currentSrv.key || currentSrv.folder)}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ path: currentPath, old: n, new: v }) }); loadFiles(); closeM(); toast('Renamed', 'success'); }); }
999
+ async function deleteDir(n) { if (confirm(`PURGE DIRECTORY '${n}'?`)) { await fetch(`/files/delete/${encodeURIComponent(currentSrv.key || currentSrv.folder)}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ path: currentPath, name: n, kind: 'dir' }) }); loadFiles(); toast('Directory deleted', 'success'); } }
1000
+ async function renameFilePrompt(n) { openM("Rename File", n, async v => { await fetch(`/files/rename/${encodeURIComponent(currentSrv.key || currentSrv.folder)}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ path: currentPath, old: n, new: v }) }); loadFiles(); closeM(); toast('Renamed', 'success'); }); }
1001
+ async function deleteFilePrompt(n) { if (confirm(`PURGE FILE '${n}'?`)) { await fetch(`/files/delete/${encodeURIComponent(currentSrv.key || currentSrv.folder)}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ path: currentPath, name: n, kind: 'file' }) }); loadFiles(); toast('File deleted', 'success'); } }
1002
 
1003
+ async function doUploadFiles(inp) { let fd = new FormData(); for (let f of inp.files) fd.append("files", f); await fetch(`/files/upload/${encodeURIComponent(currentSrv.key || currentSrv.folder)}?path=${encodeURIComponent(currentPath)}`, { method: "POST", body: fd }); loadFiles(); toast(`${inp.files.length} file(s) uploaded`, 'success'); inp.value = ''; }
1004
+ async function doUploadFolder(inp) { let fd = new FormData(); for (let f of inp.files) { fd.append("files", f); fd.append("relpaths", f.webkitRelativePath || f.name); } await fetch(`/files/upload/${encodeURIComponent(currentSrv.key || currentSrv.folder)}?path=${encodeURIComponent(currentPath)}`, { method: "POST", body: fd }); loadFiles(); toast('Folder uploaded', 'success'); inp.value = ''; }
1005
 
1006
+ async function changeStartup() { openM("Set Entrypoint", currentSrv.startup_file, async v => { await fetch(`/server/set-startup/${encodeURIComponent(currentSrv.key || currentSrv.folder)}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ file: v }) }); currentSrv.startup_file = v; document.getElementById('mainFileTxt').textContent = v; closeM(); toast('Entrypoint updated', 'success'); }); }
1007
+ async function deleteServer() { if (confirm("ABSOLUTE DATA DESTRUCTION?")) { await fetch(`/server/delete/${encodeURIComponent(currentSrv.key || currentSrv.folder)}`, { method: 'POST' }); goHome(); toast('Server deleted', 'success'); } }
1008
 
1009
  document.getElementById('newBtn').onclick = () => openM("INIT NEW ENGINE", "", async v => {
1010
  const r = await fetch('/add', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: v }) });
1011
  const d = await r.json();
1012
+ if (d.success) { closeM(); loadServers(); toast('Engine created', 'success'); } else toast(d.message, 'error');
1013
  });
1014
 
1015
  document.addEventListener('DOMContentLoaded', () => { loadServers(); loadPythonHost(); });
1016
+ setInterval(() => { if (document.getElementById('homeView').style.display !== 'none') loadServers(); }, 10000);
1017
 
 
1018
  document.addEventListener('contextmenu', e => e.preventDefault());
1019
  document.onkeydown = function (e) {
1020
  if (e.keyCode == 123) return false;
pinger.py CHANGED
@@ -1,22 +1,33 @@
1
  import requests
2
  import time
3
  import datetime
 
 
 
 
 
 
 
 
 
4
 
5
- # ضع الرابط الذي تريد زيارته هنا
6
- TARGET_URL = "http://127.0.0.1:30170"
7
 
8
  def start_pinging():
9
- print(f"[*] Starting keep-alive bot for: {TARGET_URL}")
 
10
  while True:
11
- try:
12
- response = requests.get(TARGET_URL)
13
- now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
14
- print(f"[{now}] Visited! Status Code: {response.status_code}")
15
- except Exception as e:
16
- print(f"[!] Error visiting site: {e}")
17
-
18
- # الانتظار لمدة 5 دقائق (300 ثانية)
19
- time.sleep(300)
 
 
 
20
 
21
  if __name__ == "__main__":
22
  start_pinging()
 
1
  import requests
2
  import time
3
  import datetime
4
+ import os
5
+
6
+ SPACE_URL = os.environ.get("SPACE_URL", "")
7
+ LOCAL_PORT = os.environ.get("SERVER_PORT", "7860")
8
+ LOCAL_URL = f"http://127.0.0.1:{LOCAL_PORT}/health"
9
+
10
+ TARGETS = [LOCAL_URL]
11
+ if SPACE_URL:
12
+ TARGETS.append(SPACE_URL.rstrip("/") + "/health")
13
 
 
 
14
 
15
  def start_pinging():
16
+ print(f"[*] Keep-alive targets: {TARGETS}")
17
+ fail_count = 0
18
  while True:
19
+ for url in TARGETS:
20
+ try:
21
+ r = requests.get(url, timeout=15)
22
+ now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
23
+ print(f"[{now}] {url} -> {r.status_code}")
24
+ fail_count = 0
25
+ except Exception as e:
26
+ fail_count += 1
27
+ print(f"[!] Error: {url} -> {e}")
28
+ sleep_time = 180 if fail_count == 0 else 60
29
+ time.sleep(sleep_time)
30
+
31
 
32
  if __name__ == "__main__":
33
  start_pinging()
requirements.txt CHANGED
@@ -1,4 +1,5 @@
1
  Flask>=2.2.0
2
  Werkzeug>=2.2.0
3
  psutil>=5.9.0
4
- requests>=2.28.0
 
 
1
  Flask>=2.2.0
2
  Werkzeug>=2.2.0
3
  psutil>=5.9.0
4
+ requests>=2.28.0
5
+ gunicorn>=21.2.0