"""Start xray from the XRAY_VLESS secret (a vless:// link), then the app through it.""" import json import os import socket import subprocess import sys import time from urllib.parse import parse_qs, unquote, urlsplit PORT = 10809 args = ["python", "run.py", "--mode", "live", "--data-dir", "/data", "--host", "0.0.0.0", "--port", "7860", "--workspace-concurrency", "2", "--task-workers", "4", "--enable-generation", "--captcha-timeout", "90"] link = os.environ.get("XRAY_VLESS", "").strip() if link: u = urlsplit(link) q = {k: v[0] for k, v in parse_qs(u.query).items()} net, sec = q.get("type", "tcp"), q.get("security", "none") stream = {"network": net, "security": sec} if sec == "reality": stream["realitySettings"] = {"serverName": q.get("sni", ""), "fingerprint": q.get("fp", "chrome"), "publicKey": q.get("pbk", ""), "shortId": q.get("sid", ""), "spiderX": unquote(q.get("spx", ""))} elif sec == "tls": stream["tlsSettings"] = {"serverName": q.get("sni", u.hostname), "fingerprint": q.get("fp", "chrome")} if net == "ws": stream["wsSettings"] = {"path": unquote(q.get("path", "/")), "headers": {"Host": q.get("host", "")}} elif net == "grpc": stream["grpcSettings"] = {"serviceName": unquote(q.get("serviceName", ""))} user = {"id": unquote(u.username), "encryption": q.get("encryption", "none")} if q.get("flow"): user["flow"] = q["flow"] config = { "log": {"loglevel": "warning"}, "inbounds": [{"listen": "127.0.0.1", "port": PORT, "protocol": "http"}], "outbounds": [{"protocol": "vless", "tag": "proxy", "streamSettings": stream, "settings": {"vnext": [{"address": u.hostname, "port": u.port or 443, "users": [user]}]}}], } with open("/tmp/xray.json", "w") as f: json.dump(config, f) subprocess.Popen(["xray", "run", "-c", "/tmp/xray.json"]) for _ in range(50): try: socket.create_connection(("127.0.0.1", PORT), 0.2).close() break except OSError: time.sleep(0.2) args += ["--proxy", f"http://127.0.0.1:{PORT}"] print("egress via xray", flush=True) else: print("XRAY_VLESS not set: direct egress", flush=True) sys.stdout.flush() os.execvp(args[0], args)