"""Front of the web simulator: listens on 127.0.0.1:8765 (this PC only — the page can switch real trading and holds exchange API keys) and forwards every request to the simulator engine on 127.0.0.1:8766. Why a separate process: the engine needs the VPN (the exchanges are not reachable without it), while answers to visitors from outside must leave directly through the home connection. Run this file with pythonw.exe (a different program than the engine's python.exe) and add pythonw.exe to the VPN's app exclusions; the engine stays in the VPN. pyw -3 web_proxy.py (run_web_sim.bat starts both) """ from __future__ import annotations import sys import html import ipaddress import json import os import shutil import socket import subprocess import threading import time from collections import defaultdict, deque from http.cookies import SimpleCookie from pathlib import Path from urllib.parse import parse_qs from request_security import trusted_request import urllib.error import urllib.request from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from user_auth import AuthError, UserStore LISTEN = ("127.0.0.1", 8765) # local only: real trading and API keys are behind this page ENGINE = "http://127.0.0.1:8766" ROOT = Path(__file__).resolve().parent DATA_ROOT = ROOT / "web_sim_data" STORE = UserStore(DATA_ROOT) SESSION_COOKIE = "crypto_scam_session" COOKIE_SECURE = "; Secure" if os.environ.get("CRYPTO_SCAM_PUBLIC_HOST") else "" HOP_HEADERS = {"connection", "keep-alive", "transfer-encoding", "te", "trailer", "upgrade", "proxy-authorization", "proxy-authenticate", "host", "content-length"} class TenantManager: """One complete engine process and durable data folder per account.""" def __init__(self, store: UserStore): self.store = store self.lock = threading.RLock() self.workers: dict[str, tuple[subprocess.Popen | None, int]] = {} @staticmethod def _healthy(port: int, user_id: str) -> bool: try: with urllib.request.urlopen(f"http://127.0.0.1:{port}/health", timeout=0.5) as resp: return json.loads(resp.read()).get("tenant") == user_id except Exception: return False @staticmethod def _port() -> int: with socket.socket() as sock: sock.bind(("127.0.0.1", 0)) return int(sock.getsockname()[1]) def ensure(self, user_id: str) -> str: with self.lock: old = self.workers.get(user_id) if old and (old[0] is None or old[0].poll() is None) and self._healthy(old[1], user_id): return f"http://127.0.0.1:{old[1]}" data = self.store.data_dir(user_id) marker = data / "worker.json" try: saved_port = int(json.loads(marker.read_text(encoding="utf-8")).get("port", 0)) except (OSError, ValueError, TypeError): saved_port = 0 if saved_port and self._healthy(saved_port, user_id): self.workers[user_id] = (None, saved_port) return f"http://127.0.0.1:{saved_port}" port = self._port() env = os.environ.copy() env["CRYPTO_SCAM_DATA_DIR"] = str(data) py = Path(sys.executable) if py.name.lower() == "pythonw.exe" and py.with_name("python.exe").exists(): py = py.with_name("python.exe") log_path = data / "backend.log" data.mkdir(parents=True, exist_ok=True) with log_path.open("ab") as log: proc = subprocess.Popen([str(py), "-B", str(ROOT / "web_sim.py"), "--backend", "--port", str(port)], cwd=ROOT, env=env, stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT, creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0)) self.workers[user_id] = (proc, port) marker.write_text(json.dumps({"pid": proc.pid, "port": port}), encoding="utf-8") deadline = time.monotonic() + 15 while proc.poll() is None and time.monotonic() < deadline: if self._healthy(port, user_id): return f"http://127.0.0.1:{port}" time.sleep(0.1) raise OSError("Личный движок не запустился за 15 секунд; посмотрите backend.log") def start_all(self) -> None: for user_id in self.store.user_ids(): try: self.ensure(user_id) except OSError: continue def stop_all(self) -> None: with self.lock: workers = list(self.workers.values()) self.workers.clear() for proc, _ in workers: if proc is not None and proc.poll() is None: proc.terminate() TENANTS = TenantManager(STORE) ATTEMPTS: dict[str, deque[float]] = defaultdict(deque) ATTEMPT_LOCK = threading.Lock() def _login_page(message: str = "") -> bytes: safe = html.escape(message) page = f""" Вход · Crypto Scam

Crypto Scam

Войдите в свой аккаунт

{safe}
""" return page.encode("utf-8") def _cookie(handler) -> str | None: jar = SimpleCookie() try: jar.load(handler.headers.get("Cookie", "")) except Exception: return None morsel = jar.get(SESSION_COOKIE) return morsel.value if morsel else None class Gateway(BaseHTTPRequestHandler): """Authenticate every browser session, then route it only to that account's private engine.""" def log_message(self, *args) -> None: pass def _send(self, status: int, body: bytes, kind: str = "text/html; charset=utf-8", headers=()) -> None: self.send_response(status) self.send_header("Content-Type", kind) self.send_header("Cache-Control", "no-store") self.send_header("X-Content-Type-Options", "nosniff") self.send_header("Referrer-Policy", "same-origin") self.send_header("Content-Length", str(len(body))) for key, value in headers: self.send_header(key, value) self.end_headers() self.wfile.write(body) def _json(self, status: int, data: dict, headers=()) -> None: self._send(status, json.dumps(data, ensure_ascii=False).encode("utf-8"), "application/json; charset=utf-8", headers) def _user(self) -> str | None: return STORE.user_for_session(_cookie(self)) def _body(self) -> dict: length = int(self.headers.get("Content-Length") or 0) if length < 0 or length > 65536: raise ValueError("Слишком большой запрос") raw = self.rfile.read(length) if "application/x-www-form-urlencoded" in self.headers.get("Content-Type", ""): form = parse_qs(raw.decode("utf-8"), keep_blank_values=True) return {k: v[-1] for k, v in form.items()} obj = json.loads(raw or b"{}") if not isinstance(obj, dict): raise ValueError("Ожидается объект запроса") return obj def _auth_attempt_allowed(self) -> bool: key, now = self.client_address[0], time.time() if self.client_address[0] == "127.0.0.1": forwarded_ip = self.headers.get("X-Real-IP", "") try: key = str(ipaddress.ip_address(forwarded_ip)) except ValueError: pass with ATTEMPT_LOCK: q = ATTEMPTS[key] while q and now - q[0] > 600: q.popleft() if len(q) >= 8: return False q.append(now) return True def _start_session(self, user_id: str) -> None: try: TENANTS.ensure(user_id) except OSError: self._send(503, _login_page("Не удалось запустить личный движок. Проверьте свободные порты и журнал.")) return token = STORE.create_session(user_id) self.send_response(303) self.send_header("Location", "/") self.send_header("Set-Cookie", f"{SESSION_COOKIE}={token}; Path=/; HttpOnly; SameSite=Strict{COOKIE_SECURE}; Max-Age={UserStore.SESSION_SECONDS}") self.send_header("Cache-Control", "no-store") self.send_header("Content-Length", "0") self.end_headers() def do_GET(self) -> None: if not trusted_request(self): self._json(403, {"error": "Недоверенный запрос"}) return path = self.path.partition("?")[0] if path == "/health": self._json(200, {"ok": True, "accounts": len(STORE.user_ids())}) return if path == "/system/status": self._system_status() return if path == "/auth/logout": STORE.delete_session(_cookie(self)) self.send_response(303) self.send_header("Location", "/") self.send_header("Set-Cookie", f"{SESSION_COOKIE}=; Path=/; HttpOnly; SameSite=Strict{COOKIE_SECURE}; Max-Age=0") self.send_header("Cache-Control", "no-store") self.send_header("Content-Length", "0") self.end_headers() return user_id = self._user() if user_id is None: self._send(200, _login_page()) return self._forward("GET", user_id) def do_POST(self) -> None: if not trusted_request(self): self._json(403, {"ok": False, "error": "Недоверенный запрос"}) return path = self.path.partition("?")[0] if path in ("/auth/login", "/auth/register"): if not self._auth_attempt_allowed(): self._send(429, _login_page("Слишком много попыток. Подождите 10 минут.")) return try: body = self._body() username, password = str(body.get("username", "")), str(body.get("password", "")) if path == "/auth/register": user_id = STORE.register(username, password) if STORE.mark_legacy_imported(): _import_legacy_data(STORE.data_dir(user_id)) else: user_id = STORE.authenticate(username, password) if user_id is None: raise AuthError("Неверный логин или пароль") except (AuthError, ValueError, UnicodeError) as exc: self._send(400, _login_page(str(exc))) return self._start_session(user_id) return if self._user() is None: self._json(401, {"ok": False, "error": "Сначала войдите в аккаунт"}) return if self.headers.get("X-Sim") != "1": self._json(403, {"ok": False, "error": "Недоверенный запрос"}) return self._forward("POST", self._user()) def _forward(self, method: str, user_id: str) -> None: try: engine = TENANTS.ensure(user_id) length = int(self.headers.get("Content-Length") or 0) if length < 0 or length > 65536: self._json(413, {"error": "Слишком большой запрос"}) return body = self.rfile.read(length) if length else None headers = {k: v for k, v in self.headers.items() if k.lower() not in HOP_HEADERS and k.lower() not in ("cookie",)} headers["Host"] = self.headers.get("Host", "127.0.0.1:8765") req = urllib.request.Request(engine + self.path, data=body, method=method, headers=headers) with urllib.request.urlopen(req, timeout=60) as resp: status, data, resp_headers = resp.status, resp.read(), resp.getheaders() except urllib.error.HTTPError as exc: status, data, resp_headers = exc.code, exc.read(), exc.headers.items() except (urllib.error.URLError, OSError, ValueError) as exc: status, data = 502, json.dumps({"error": f"Личный движок не отвечает: {exc}"}, ensure_ascii=False).encode() resp_headers = [("Content-Type", "application/json; charset=utf-8")] self.send_response(status) for key, value in resp_headers: if key.lower() not in HOP_HEADERS and key.lower() not in ("set-cookie",): self.send_header(key, value) self.send_header("Content-Length", str(len(data))) self.send_header("Cache-Control", "no-store") self.end_headers() self.wfile.write(data) def _system_status(self) -> None: open_trades = [] for user_id in STORE.user_ids(): try: engine = TENANTS.ensure(user_id) req = urllib.request.Request(engine + "/api/basis?ex=cross_real") with urllib.request.urlopen(req, timeout=10) as resp: data = json.loads(resp.read()) open_trades.extend({"user": STORE.username(user_id), "coin": p.get("base"), "closing": bool(p.get("closing"))} for p in data.get("positions", []) if p.get("real")) except Exception: continue self._json(200, {"real_positions": open_trades}) def _import_legacy_data(target: Path) -> None: """Copy the old single-account files into the first account without removing the originals.""" try: items = list(DATA_ROOT.iterdir()) except OSError: items = [] for source in items: if source.name in {"users", "accounts.sqlite3", "engine.lock"} or source.name.endswith((".log", ".tmp")): continue destination = target / source.name try: if source.is_file() and not destination.exists(): shutil.copy2(source, destination) elif source.is_dir() and source.name == "scalp_recordings": shutil.copytree(source, destination, dirs_exist_ok=True) except OSError: continue # One old connection/removal file lived at the project root. Do not copy source code or config examples. source = ROOT / "lead_connections_removed.json" destination = target / source.name try: if source.is_file() and not destination.exists(): shutil.copy2(source, destination) except OSError: pass class Proxy(BaseHTTPRequestHandler): def log_message(self, *args) -> None: pass def _forward(self, method: str) -> None: if not trusted_request(self, command=method == "POST"): self.send_error(403, "only from this computer") return length = int(self.headers.get("Content-Length") or 0) body = self.rfile.read(length) if length else None headers = {k: v for k, v in self.headers.items() if k.lower() not in HOP_HEADERS} # Preserve the validated authority so the engine can compare the browser Origin. headers["Host"] = self.headers["Host"] req = urllib.request.Request(ENGINE + self.path, data=body, method=method, headers=headers) try: with urllib.request.urlopen(req, timeout=30) as resp: status, data, resp_headers = resp.status, resp.read(), resp.getheaders() except urllib.error.HTTPError as exc: status, data, resp_headers = exc.code, exc.read(), exc.headers.items() except (urllib.error.URLError, OSError): status, data = 502, "Движок симулятора не отвечает (web_sim.py --backend не запущен?)".encode("utf-8") resp_headers = [("Content-Type", "text/plain; charset=utf-8")] self.send_response(status) for k, v in resp_headers: if k.lower() not in HOP_HEADERS: self.send_header(k, v) self.send_header("Content-Length", str(len(data))) self.end_headers() self.wfile.write(data) def do_GET(self) -> None: self._forward("GET") def do_POST(self) -> None: self._forward("POST") def main() -> None: server = ThreadingHTTPServer(LISTEN, Gateway) if sys.stdout: print(f"Сервер с авторизацией: http://{LISTEN[0]}:{LISTEN[1]}", flush=True) threading.Thread(target=TENANTS.start_all, daemon=True).start() try: server.serve_forever() finally: server.server_close() TENANTS.stop_all() if __name__ == "__main__": main()