Files
Crypto_Scam/web_proxy.py

71 lines
3.0 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
from request_security import trusted_request
import urllib.error
import urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
LISTEN = ("127.0.0.1", 8765) # local only: real trading and API keys are behind this page
ENGINE = "http://127.0.0.1:8766"
HOP_HEADERS = {"connection", "keep-alive", "transfer-encoding", "te", "trailer", "upgrade", "proxy-authorization",
"proxy-authenticate", "host", "content-length"}
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, Proxy)
if sys.stdout:
print(f"Прокси страницы: {LISTEN[0]}:{LISTEN[1]} → {ENGINE}", flush=True)
server.serve_forever()
if __name__ == "__main__":
main()