Files
Crypto_Scam/LinuxServer/web_proxy.py
T
listik 45b0b3044b
Offline regression tests / windows (3.11) (push) Canceled after 0s
Offline regression tests / windows (3.12) (push) Canceled after 0s
Offline regression tests / windows (3.13) (push) Canceled after 0s
1
2026-10-24 00:07:25 +03:00

400 lines
18 KiB
Python

"""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")
and os.environ.get("CRYPTO_SCAM_PUBLIC_SCHEME", "https").lower() == "https" 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"""<!doctype html><html lang="ru"><meta charset="utf-8"><meta name="viewport" content="width=device-width">
<title>Вход · Crypto Scam</title><style>
body{{margin:0;background:#10141d;color:#e8eef9;font:16px system-ui;display:grid;place-items:center;min-height:100vh}}
main{{width:min(420px,calc(100% - 36px));background:#1a202c;border:1px solid #303a4a;border-radius:14px;padding:26px;box-sizing:border-box}}
h1{{font-size:22px;margin:0 0 6px}}p{{color:#9aa9bf;font-size:14px}}label{{display:block;margin:16px 0 6px;color:#b9c7db}}
input{{box-sizing:border-box;width:100%;padding:11px;border-radius:7px;border:1px solid #39475a;background:#10141d;color:white;font-size:16px}}
button{{margin-top:20px;width:100%;padding:11px;border:0;border-radius:7px;background:#3b82f6;color:white;font-size:16px;cursor:pointer}}
.error{{color:#ff8b8b;min-height:20px}}.note{{color:#9aa9bf;font-size:13px;margin-top:16px}}
</style><main><h1>Crypto Scam</h1><p id="modeText">Войдите в свой аккаунт</p><div class="error">{safe}</div>
<form method="post" action="/auth/login"><label>Логин</label><input name="username" required minlength="3" maxlength="32" autocomplete="username">
<label>Пароль</label><input name="password" type="password" required minlength="12" maxlength="256" autocomplete="current-password">
<button>Войти</button></form><p class="note">Нового пользователя может создать администратор через SSH.</p></main></html>"""
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 == "/auth/register":
self._send(403, _login_page("Регистрация через сайт отключена. Обратитесь к администратору."))
return
if path == "/auth/login":
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", ""))
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()