feat(wip): xray proxy backend
This commit is contained in:
36 files changed
+2265
-996
No files matched your search
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Read a proxy URL from stdin and emit a sing-box outbound JSON object."""
|
||||
"""Read a proxy URL from stdin and emit a backend outbound JSON object."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
@@ -10,15 +10,16 @@ from proxy_parsing import build_outbound
|
||||
|
||||
def main() -> None:
|
||||
ap = argparse.ArgumentParser(
|
||||
description="Convert a proxy URL from stdin into a sing-box outbound JSON object."
|
||||
description="Convert a proxy URL from stdin into a backend outbound JSON object."
|
||||
)
|
||||
ap.add_argument("--tag", required=True)
|
||||
ap.add_argument("--backend", choices=["sing-box", "xray"], default="sing-box")
|
||||
ap.add_argument("--routing-mark", type=int, default=None, dest="routing_mark")
|
||||
args = ap.parse_args()
|
||||
|
||||
url = sys.stdin.read().strip()
|
||||
try:
|
||||
outbound = build_outbound(url, args.tag, args.routing_mark)
|
||||
outbound = build_outbound(url, args.tag, args.routing_mark, args.backend)
|
||||
except ValueError as exc:
|
||||
print(f"error: {exc}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Read a subscription URL from stdin and emit a JSON array of outbounds."""
|
||||
"""Read a subscription URL from stdin and emit a JSON array of backend outbounds."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
@@ -10,7 +10,7 @@ from proxy_parsing import decode_subscription, fetch_raw, parse_subscription
|
||||
|
||||
def main() -> None:
|
||||
ap = argparse.ArgumentParser(
|
||||
description="Fetch a proxy subscription URL from stdin and emit a sing-box outbound JSON array."
|
||||
description="Fetch a proxy subscription URL from stdin and emit a backend outbound JSON array."
|
||||
)
|
||||
ap.add_argument(
|
||||
"--tag-prefix",
|
||||
@@ -18,6 +18,7 @@ def main() -> None:
|
||||
dest="tag_prefix",
|
||||
help="Prefix for outbound tags, e.g. 'my-sub'.",
|
||||
)
|
||||
ap.add_argument("--backend", choices=["sing-box", "xray"], default="sing-box")
|
||||
ap.add_argument("--routing-mark", type=int, default=None, dest="routing_mark")
|
||||
args = ap.parse_args()
|
||||
|
||||
@@ -33,7 +34,7 @@ def main() -> None:
|
||||
sys.exit(1)
|
||||
|
||||
lines = decode_subscription(raw)
|
||||
outbounds = parse_subscription(lines, args.tag_prefix, args.routing_mark)
|
||||
outbounds = parse_subscription(lines, args.tag_prefix, args.routing_mark, args.backend)
|
||||
|
||||
if not outbounds:
|
||||
print("error: subscription contained no parseable proxy URIs", file=sys.stderr)
|
||||
|
||||
+176
-4
@@ -13,14 +13,186 @@ def detect_scheme(url: str) -> str:
|
||||
return url.split("://", 1)[0].lower()
|
||||
|
||||
|
||||
def build_outbound(url: str, tag: str, routing_mark: int | None = None) -> dict:
|
||||
def _parse_url(url: str, tag: str, backend: str) -> dict:
|
||||
scheme = detect_scheme(url)
|
||||
if scheme not in PARSERS:
|
||||
raise ValueError(f"unsupported scheme '{scheme}'")
|
||||
|
||||
outbound = PARSERS[scheme](url, tag)
|
||||
parser = PARSERS[scheme]
|
||||
try:
|
||||
return parser(url, tag, backend)
|
||||
except TypeError:
|
||||
return parser(url, tag)
|
||||
|
||||
|
||||
def _xray_sockopt(routing_mark: int | None) -> dict:
|
||||
if routing_mark is None:
|
||||
return {}
|
||||
return {"streamSettings": {"sockopt": {"mark": routing_mark}}}
|
||||
|
||||
|
||||
def _xray_tls(tls: dict | None) -> tuple[str, dict]:
|
||||
if not tls or not tls.get("enabled"):
|
||||
return "none", {}
|
||||
|
||||
if tls.get("reality", {}).get("enabled"):
|
||||
reality = tls["reality"]
|
||||
settings = {
|
||||
"serverName": tls.get("server_name", ""),
|
||||
"publicKey": reality["public_key"],
|
||||
"shortId": reality.get("short_id", ""),
|
||||
}
|
||||
utls = tls.get("utls", {})
|
||||
if utls.get("enabled") and utls.get("fingerprint"):
|
||||
settings["fingerprint"] = utls["fingerprint"]
|
||||
return "reality", {"realitySettings": settings}
|
||||
|
||||
settings = {"serverName": tls.get("server_name", "")}
|
||||
if tls.get("alpn"):
|
||||
settings["alpn"] = tls["alpn"]
|
||||
if tls.get("insecure"):
|
||||
settings["allowInsecure"] = True
|
||||
if tls.get("ech_config_list"):
|
||||
settings["echConfigList"] = tls["ech_config_list"]
|
||||
utls = tls.get("utls", {})
|
||||
if utls.get("enabled") and utls.get("fingerprint"):
|
||||
settings["fingerprint"] = utls["fingerprint"]
|
||||
return "tls", {"tlsSettings": settings}
|
||||
|
||||
|
||||
def _xray_transport(transport: dict | None) -> tuple[str, dict]:
|
||||
if not transport:
|
||||
return "tcp", {}
|
||||
|
||||
t = transport["type"]
|
||||
if t == "ws":
|
||||
return "ws", {"wsSettings": {"path": transport.get("path", "/"), "headers": transport.get("headers", {})}}
|
||||
if t == "grpc":
|
||||
return "grpc", {"grpcSettings": {"serviceName": transport.get("service_name", "")}}
|
||||
if t == "http":
|
||||
return "http", {"httpSettings": {"host": transport.get("host", []), "path": transport.get("path", "/")}}
|
||||
if t == "httpupgrade":
|
||||
return "httpupgrade", {
|
||||
"httpupgradeSettings": {
|
||||
"host": transport.get("host", ""),
|
||||
"path": transport.get("path", "/"),
|
||||
}
|
||||
}
|
||||
if t == "quic":
|
||||
return "quic", {}
|
||||
if t == "xhttp":
|
||||
return "xhttp", {
|
||||
"xhttpSettings": {
|
||||
"host": transport.get("host", ""),
|
||||
"path": transport.get("path", "/"),
|
||||
}
|
||||
}
|
||||
return t, {}
|
||||
|
||||
|
||||
def render_xray_outbound(ob: dict, routing_mark: int | None = None) -> dict:
|
||||
typ = ob["type"]
|
||||
tag = ob["tag"]
|
||||
|
||||
def stream_settings() -> dict:
|
||||
security, sec = _xray_tls(ob.get("tls"))
|
||||
network, net = _xray_transport(ob.get("transport"))
|
||||
stream = {"network": network, "security": security}
|
||||
stream.update(sec)
|
||||
stream.update(net)
|
||||
if routing_mark is not None:
|
||||
stream.setdefault("sockopt", {})["mark"] = routing_mark
|
||||
return stream
|
||||
|
||||
if typ == "vless":
|
||||
settings = {
|
||||
"address": ob["server"],
|
||||
"port": ob["server_port"],
|
||||
"id": ob["uuid"],
|
||||
"encryption": "none",
|
||||
}
|
||||
if ob.get("flow"):
|
||||
settings["flow"] = ob["flow"]
|
||||
return {"protocol": "vless", "tag": tag, "settings": settings, "streamSettings": stream_settings()}
|
||||
|
||||
if typ == "vmess":
|
||||
settings = {
|
||||
"address": ob["server"],
|
||||
"port": ob["server_port"],
|
||||
"id": ob["uuid"],
|
||||
"security": ob.get("security", "auto"),
|
||||
"alterId": ob.get("alter_id", 0),
|
||||
}
|
||||
return {"protocol": "vmess", "tag": tag, "settings": settings, "streamSettings": stream_settings()}
|
||||
|
||||
if typ == "trojan":
|
||||
settings = {
|
||||
"address": ob["server"],
|
||||
"port": ob["server_port"],
|
||||
"password": ob["password"],
|
||||
}
|
||||
return {"protocol": "trojan", "tag": tag, "settings": settings, "streamSettings": stream_settings()}
|
||||
|
||||
if typ == "shadowsocks":
|
||||
settings = {
|
||||
"address": ob["server"],
|
||||
"port": ob["server_port"],
|
||||
"method": ob["method"],
|
||||
"password": ob["password"],
|
||||
}
|
||||
return {"protocol": "shadowsocks", "tag": tag, "settings": settings, **_xray_sockopt(routing_mark)}
|
||||
|
||||
if typ == "hysteria2":
|
||||
stream = stream_settings()
|
||||
stream["network"] = "hysteria"
|
||||
stream["security"] = "tls"
|
||||
settings = {
|
||||
"version": 2,
|
||||
"address": ob["server"],
|
||||
"port": ob["server_port"],
|
||||
}
|
||||
if ob.get("password"):
|
||||
settings["password"] = ob["password"]
|
||||
return {"protocol": "hysteria", "tag": tag, "settings": settings, "streamSettings": stream}
|
||||
|
||||
if typ == "socks":
|
||||
settings = {"address": ob["server"], "port": ob["server_port"]}
|
||||
if ob.get("username"):
|
||||
settings["user"] = ob["username"]
|
||||
settings["pass"] = ob.get("password", "")
|
||||
return {"protocol": "socks", "tag": tag, "settings": settings, **_xray_sockopt(routing_mark)}
|
||||
|
||||
if typ == "http":
|
||||
settings = {"address": ob["server"], "port": ob["server_port"]}
|
||||
if ob.get("username"):
|
||||
settings["user"] = ob["username"]
|
||||
settings["pass"] = ob.get("password", "")
|
||||
outbound = {"protocol": "http", "tag": tag, "settings": settings}
|
||||
if ob.get("tls"):
|
||||
security, sec = _xray_tls(ob.get("tls"))
|
||||
outbound["streamSettings"] = {"security": security, **sec}
|
||||
if routing_mark is not None:
|
||||
outbound["streamSettings"].setdefault("sockopt", {})["mark"] = routing_mark
|
||||
elif routing_mark is not None:
|
||||
outbound.update(_xray_sockopt(routing_mark))
|
||||
return outbound
|
||||
|
||||
raise ValueError(f"unsupported XRay outbound type '{typ}'")
|
||||
|
||||
|
||||
def build_outbound(
|
||||
url: str, tag: str, routing_mark: int | None = None, backend: str = "sing-box"
|
||||
) -> dict:
|
||||
if backend not in {"sing-box", "xray"}:
|
||||
raise ValueError(f"unsupported backend '{backend}'")
|
||||
|
||||
outbound = _parse_url(url, tag, backend)
|
||||
if routing_mark is not None:
|
||||
if backend == "xray":
|
||||
return render_xray_outbound(outbound, routing_mark)
|
||||
outbound["routing_mark"] = routing_mark
|
||||
elif backend == "xray":
|
||||
return render_xray_outbound(outbound)
|
||||
return outbound
|
||||
|
||||
|
||||
@@ -63,7 +235,7 @@ def make_tag(prefix: str, remark: str, index: int) -> str:
|
||||
|
||||
|
||||
def parse_subscription(
|
||||
lines: list[str], tag_prefix: str, routing_mark: int | None
|
||||
lines: list[str], tag_prefix: str, routing_mark: int | None, backend: str = "sing-box"
|
||||
) -> list[dict]:
|
||||
outbounds = []
|
||||
seen_tags: set[str] = set()
|
||||
@@ -84,7 +256,7 @@ def parse_subscription(
|
||||
tag = f"{base_tag}-{suffix}"
|
||||
|
||||
try:
|
||||
outbound = build_outbound(line, tag, routing_mark)
|
||||
outbound = build_outbound(line, tag, routing_mark, backend)
|
||||
except Exception as exc:
|
||||
print(f"warning: skipping entry {index} ({scheme}): {exc}", file=sys.stderr)
|
||||
continue
|
||||
|
||||
@@ -16,6 +16,11 @@ SUPPORTED_VLESS_TRANSPORTS = {
|
||||
"quic",
|
||||
}
|
||||
|
||||
SUPPORTED_XRAY_TRANSPORTS = SUPPORTED_VLESS_TRANSPORTS | {
|
||||
"xhttp",
|
||||
"splithttp",
|
||||
}
|
||||
|
||||
|
||||
def _qs(query: str) -> dict:
|
||||
return dict(urllib.parse.parse_qsl(query, keep_blank_values=True))
|
||||
@@ -79,6 +84,12 @@ def _mk_transport(
|
||||
return {
|
||||
"type": "quic",
|
||||
}
|
||||
if normalized in ("xhttp", "splithttp"):
|
||||
return {
|
||||
"type": "xhttp",
|
||||
"host": host_header,
|
||||
"path": urllib.parse.unquote(path),
|
||||
}
|
||||
return None
|
||||
|
||||
|
||||
@@ -100,22 +111,25 @@ def _mk_auth(userinfo: str) -> "tuple[str | None, str | None]":
|
||||
return None, None
|
||||
|
||||
|
||||
def parse_vless(url: str, tag: str) -> dict:
|
||||
def parse_vless(url: str, tag: str, backend: str = "sing-box") -> dict:
|
||||
userinfo, host, port, params = _parse_url_parts(url, "vless")
|
||||
security = params.get("security", "none")
|
||||
transport = params.get("type", "tcp")
|
||||
normalized_transport = transport.lower()
|
||||
|
||||
if "ech" in params:
|
||||
if "ech" in params and backend != "xray":
|
||||
raise ValueError(
|
||||
"unsupported VLESS parameter 'ech': proxy-suite does not translate "
|
||||
"share-link ECH blobs into sing-box TLS config"
|
||||
)
|
||||
|
||||
if normalized_transport not in SUPPORTED_VLESS_TRANSPORTS:
|
||||
supported_transports = (
|
||||
SUPPORTED_XRAY_TRANSPORTS if backend == "xray" else SUPPORTED_VLESS_TRANSPORTS
|
||||
)
|
||||
if normalized_transport not in supported_transports:
|
||||
raise ValueError(
|
||||
f"unsupported VLESS transport '{transport}': proxy-suite only maps "
|
||||
"sing-box-documented transports; use raw JSON or another client/core"
|
||||
f"{backend}-documented transports; use raw JSON or another client/core"
|
||||
)
|
||||
|
||||
ob: dict = {
|
||||
@@ -138,6 +152,8 @@ def parse_vless(url: str, tag: str) -> dict:
|
||||
ob["tls"] = _mk_tls(
|
||||
params.get("sni", host), fp=params.get("fp"), alpn=params.get("alpn")
|
||||
)
|
||||
if backend == "xray" and "ech" in params:
|
||||
ob["tls"]["ech_config_list"] = urllib.parse.unquote(params["ech"])
|
||||
|
||||
tr = _mk_transport(
|
||||
normalized_transport,
|
||||
|
||||
@@ -11,6 +11,10 @@ def run_parser(url: str):
|
||||
return build_outbound(url, "test-outbound")
|
||||
|
||||
|
||||
def run_xray_parser(url: str):
|
||||
return build_outbound(url, "test-outbound", backend="xray")
|
||||
|
||||
|
||||
class BuildOutboundTests(unittest.TestCase):
|
||||
def test_vless_reality(self):
|
||||
ob = run_parser(
|
||||
@@ -50,6 +54,41 @@ class BuildOutboundTests(unittest.TestCase):
|
||||
"vless://uuid@example.com:443?type=xhttp&security=tls&sni=cdn.example.com"
|
||||
)
|
||||
|
||||
def test_xray_vless_xhttp(self):
|
||||
ob = run_xray_parser(
|
||||
"vless://uuid@example.com:443?type=xhttp&security=tls&sni=cdn.example.com&host=cdn.example.com&path=%2Fx"
|
||||
)
|
||||
self.assertEqual(ob["protocol"], "vless")
|
||||
self.assertEqual(ob["settings"]["address"], "example.com")
|
||||
self.assertEqual(ob["settings"]["id"], "uuid")
|
||||
self.assertEqual(ob["streamSettings"]["network"], "xhttp")
|
||||
self.assertEqual(ob["streamSettings"]["xhttpSettings"]["path"], "/x")
|
||||
|
||||
def test_xray_vless_ech(self):
|
||||
ob = run_xray_parser(
|
||||
"vless://uuid@example.com:443?type=tcp&security=tls&sni=cdn.example.com&ech=udp%3A%2F%2F1.1.1.1"
|
||||
)
|
||||
self.assertEqual(ob["streamSettings"]["tlsSettings"]["echConfigList"], "udp://1.1.1.1")
|
||||
|
||||
def test_xray_socks_uses_current_flat_settings_shape(self):
|
||||
ob = run_xray_parser("socks5://user:pass@example.com:1080")
|
||||
self.assertEqual(ob["protocol"], "socks")
|
||||
self.assertEqual(ob["settings"]["address"], "example.com")
|
||||
self.assertEqual(ob["settings"]["user"], "user")
|
||||
self.assertNotIn("servers", ob["settings"])
|
||||
|
||||
def test_xray_shadowsocks_uses_current_flat_settings_shape(self):
|
||||
credentials = (
|
||||
base64.urlsafe_b64encode(b"chacha20-ietf-poly1305:passw0rd")
|
||||
.decode()
|
||||
.rstrip("=")
|
||||
)
|
||||
ob = run_xray_parser(f"ss://{credentials}@ss.example.com:8388")
|
||||
self.assertEqual(ob["protocol"], "shadowsocks")
|
||||
self.assertEqual(ob["settings"]["address"], "ss.example.com")
|
||||
self.assertEqual(ob["settings"]["method"], "chacha20-ietf-poly1305")
|
||||
self.assertNotIn("servers", ob["settings"])
|
||||
|
||||
def test_vless_ech_fails_loudly(self):
|
||||
with self.assertRaisesRegex(ValueError, "unsupported VLESS parameter 'ech'"):
|
||||
run_parser(
|
||||
|
||||
Reference in new issue
Block a user