feat/wip/fix: add inbounds support, fix ssh-proxy
This commit is contained in:
39 files changed
+5093
-48
No files matched your search
@@ -0,0 +1,42 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Read an inbound spec file and emit XRay inbounds plus client share links."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
|
||||
from proxy_inbound import build_inbounds
|
||||
|
||||
|
||||
def main() -> None:
|
||||
ap = argparse.ArgumentParser(
|
||||
description="Render services.proxy-suite.proxyInbounds into XRay inbounds."
|
||||
)
|
||||
ap.add_argument("--spec", required=True, help="path to the generated inbound spec JSON")
|
||||
ap.add_argument(
|
||||
"--server-address",
|
||||
default="",
|
||||
dest="server_address",
|
||||
help="public address used in generated share links",
|
||||
)
|
||||
args = ap.parse_args()
|
||||
|
||||
with open(args.spec, encoding="utf-8") as handle:
|
||||
spec = json.load(handle)
|
||||
|
||||
server_address = args.server_address or spec.get("serverAddress") or ""
|
||||
if spec.get("shareLinks", True) and not server_address:
|
||||
print("error: no server address available for share links", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
try:
|
||||
result = build_inbounds(spec, server_address)
|
||||
except (ValueError, OSError) as exc:
|
||||
print(f"error: {exc}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
print(json.dumps(result))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,325 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Render server-side proxy inbounds and their client share links.
|
||||
|
||||
The input spec is backend-neutral: it mirrors the
|
||||
services.proxy-suite.proxyInbounds option tree, with secrets given as file
|
||||
paths that are read here rather than at Nix evaluation time. Only XRay is
|
||||
rendered today; a render_sing_box_inbound would sit beside render_xray_inbound
|
||||
without changing the spec or the link generator.
|
||||
"""
|
||||
|
||||
import base64
|
||||
import json
|
||||
import urllib.parse
|
||||
|
||||
UUID_TYPES = ("vless", "vmess")
|
||||
PASSWORD_TYPES = ("trojan", "shadowsocks", "socks", "http")
|
||||
UDP_TYPES = ("shadowsocks", "socks")
|
||||
|
||||
TRANSPORT_SETTINGS_KEY = {
|
||||
"ws": "wsSettings",
|
||||
"grpc": "grpcSettings",
|
||||
"httpupgrade": "httpupgradeSettings",
|
||||
"xhttp": "xhttpSettings",
|
||||
}
|
||||
|
||||
|
||||
def _read_secret(path: str) -> str:
|
||||
with open(path, encoding="utf-8") as handle:
|
||||
return handle.read().strip()
|
||||
|
||||
|
||||
def _resolve(literal: str | None, path: str | None, what: str, tag: str) -> str:
|
||||
"""Take the inline value, or the contents of the file holding it."""
|
||||
if literal is not None:
|
||||
return literal
|
||||
if path is not None:
|
||||
value = _read_secret(path)
|
||||
if not value:
|
||||
raise ValueError(f"listener '{tag}': {what} file '{path}' is empty")
|
||||
return value
|
||||
raise ValueError(f"listener '{tag}': no {what} configured")
|
||||
|
||||
|
||||
def _user_secret(user: dict, listener_type: str, tag: str) -> str:
|
||||
if listener_type in UUID_TYPES:
|
||||
return _resolve(user.get("uuid"), user.get("uuidFile"), "uuid", tag)
|
||||
return _resolve(user.get("password"), user.get("passwordFile"), "password", tag)
|
||||
|
||||
|
||||
def _b64(value: str) -> str:
|
||||
"""base64 without padding, as share links carry it."""
|
||||
return base64.urlsafe_b64encode(value.encode("utf-8")).decode("ascii").rstrip("=")
|
||||
|
||||
|
||||
def _share_port(listener: dict) -> int:
|
||||
"""Port clients dial, which differs from the bound port when something in
|
||||
front of the listener (an nginx vhost, a port mapping) owns the public one."""
|
||||
return listener.get("sharePort") or listener["port"]
|
||||
|
||||
|
||||
def _clients(listener: dict, tag: str) -> list[dict]:
|
||||
clients = []
|
||||
for index, user in enumerate(listener["users"]):
|
||||
secret = _user_secret(user, listener["type"], tag)
|
||||
email = user.get("name") or f"{tag}-{index}"
|
||||
if listener["type"] in UUID_TYPES:
|
||||
client = {"id": secret, "email": email}
|
||||
if listener["type"] == "vless" and listener.get("flow"):
|
||||
client["flow"] = listener["flow"]
|
||||
else:
|
||||
client = {"password": secret, "email": email}
|
||||
clients.append(client)
|
||||
return clients
|
||||
|
||||
|
||||
def _accounts(listener: dict, tag: str) -> list[dict]:
|
||||
accounts = []
|
||||
for index, user in enumerate(listener["users"]):
|
||||
secret = _user_secret(user, listener["type"], tag)
|
||||
accounts.append({"user": user.get("name") or f"{tag}-{index}", "pass": secret})
|
||||
return accounts
|
||||
|
||||
|
||||
def _xray_stream(listener: dict, tag: str) -> dict:
|
||||
transport = listener["transport"]
|
||||
network = transport["type"]
|
||||
stream: dict = {"network": network}
|
||||
|
||||
settings_key = TRANSPORT_SETTINGS_KEY.get(network)
|
||||
if settings_key == "grpcSettings":
|
||||
stream[settings_key] = {"serviceName": transport["serviceName"]}
|
||||
elif settings_key is not None:
|
||||
settings = {"path": transport["path"]}
|
||||
if transport.get("host"):
|
||||
settings["host"] = transport["host"]
|
||||
if network == "xhttp" and transport.get("mode"):
|
||||
settings["mode"] = transport["mode"]
|
||||
stream[settings_key] = settings
|
||||
|
||||
reality = listener["reality"]
|
||||
tls = listener["tls"]
|
||||
if reality["enable"]:
|
||||
stream["security"] = "reality"
|
||||
stream["realitySettings"] = {
|
||||
"show": False,
|
||||
"dest": reality["dest"],
|
||||
"serverNames": reality["serverNames"],
|
||||
"privateKey": _resolve(
|
||||
reality.get("privateKey"),
|
||||
reality.get("privateKeyFile"),
|
||||
"reality private key",
|
||||
tag,
|
||||
),
|
||||
"shortIds": reality["shortIds"],
|
||||
}
|
||||
elif tls["enable"] or listener["type"] == "trojan":
|
||||
stream["security"] = "tls"
|
||||
certificate = {
|
||||
"certificateFile": tls["certificateFile"],
|
||||
"keyFile": tls["keyFile"],
|
||||
}
|
||||
stream["tlsSettings"] = {"certificates": [certificate]}
|
||||
if tls.get("serverName"):
|
||||
stream["tlsSettings"]["serverName"] = tls["serverName"]
|
||||
else:
|
||||
stream["security"] = "none"
|
||||
|
||||
return stream
|
||||
|
||||
|
||||
def render_xray_inbound(listener: dict) -> dict:
|
||||
"""Build one XRay inbound object from a typed listener spec."""
|
||||
tag = listener["tag"]
|
||||
listener_type = listener["type"]
|
||||
|
||||
if listener_type in UUID_TYPES:
|
||||
settings: dict = {"clients": _clients(listener, tag)}
|
||||
if listener_type == "vless":
|
||||
settings["decryption"] = "none"
|
||||
elif listener_type == "trojan":
|
||||
settings = {"clients": _clients(listener, tag)}
|
||||
elif listener_type == "shadowsocks":
|
||||
settings = {"method": listener["method"], "network": "tcp,udp"}
|
||||
users = listener["users"]
|
||||
if len(users) == 1:
|
||||
settings["password"] = _user_secret(users[0], listener_type, tag)
|
||||
else:
|
||||
# Multi-user shadowsocks needs the 2022 ciphers.
|
||||
settings["clients"] = _clients(listener, tag)
|
||||
elif listener_type in ("socks", "http"):
|
||||
settings = {"auth": "password", "accounts": _accounts(listener, tag)}
|
||||
if listener_type == "socks":
|
||||
settings["udp"] = True
|
||||
else:
|
||||
raise ValueError(f"listener '{tag}': unsupported type '{listener_type}'")
|
||||
|
||||
return {
|
||||
"tag": tag,
|
||||
"listen": listener["listen"],
|
||||
"port": listener["port"],
|
||||
"protocol": listener_type,
|
||||
"settings": settings,
|
||||
"streamSettings": _xray_stream(listener, tag),
|
||||
# routeOnly keeps the sniffed domain for routing decisions without
|
||||
# rewriting the destination the client actually asked for.
|
||||
"sniffing": {
|
||||
"enabled": True,
|
||||
"destOverride": ["http", "tls", "quic"],
|
||||
"routeOnly": True,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _link_transport_params(listener: dict) -> dict:
|
||||
transport = listener["transport"]
|
||||
network = transport["type"]
|
||||
# "raw" is XRay's current name for plain TCP; share links still say "tcp",
|
||||
# which is what every client (and our own outbound parser) understands.
|
||||
params: dict = {"type": "tcp" if network == "raw" else network}
|
||||
if network == "grpc":
|
||||
params["serviceName"] = transport["serviceName"]
|
||||
elif network in ("ws", "httpupgrade", "xhttp"):
|
||||
params["path"] = transport["path"]
|
||||
if transport.get("host"):
|
||||
params["host"] = transport["host"]
|
||||
if network == "xhttp" and transport.get("mode"):
|
||||
params["mode"] = transport["mode"]
|
||||
return params
|
||||
|
||||
|
||||
def _link_security_params(listener: dict, server_address: str) -> dict:
|
||||
reality = listener["reality"]
|
||||
tls = listener["tls"]
|
||||
if reality["enable"]:
|
||||
if not reality.get("publicKey"):
|
||||
raise ValueError(
|
||||
f"listener '{listener['tag']}': reality.publicKey is required "
|
||||
"to generate a share link"
|
||||
)
|
||||
server_names = reality["serverNames"]
|
||||
short_ids = reality["shortIds"]
|
||||
params = {
|
||||
"security": "reality",
|
||||
"pbk": reality["publicKey"],
|
||||
"sni": server_names[0] if server_names else server_address,
|
||||
"fp": "chrome",
|
||||
}
|
||||
if short_ids and short_ids[0]:
|
||||
params["sid"] = short_ids[0]
|
||||
return params
|
||||
if tls["enable"] or listener["type"] == "trojan":
|
||||
return {
|
||||
"security": "tls",
|
||||
"sni": tls.get("serverName") or server_address,
|
||||
"fp": "chrome",
|
||||
}
|
||||
return {"security": "none"}
|
||||
|
||||
|
||||
def _vmess_link(listener: dict, secret: str, server_address: str, label: str) -> str:
|
||||
transport = listener["transport"]
|
||||
reality = listener["reality"]
|
||||
tls = listener["tls"]
|
||||
blob = {
|
||||
"v": "2",
|
||||
"ps": label,
|
||||
"add": server_address,
|
||||
"port": str(_share_port(listener)),
|
||||
"id": secret,
|
||||
"aid": "0",
|
||||
"scy": "auto",
|
||||
"net": transport["type"],
|
||||
"type": "none",
|
||||
"host": transport.get("host") or "",
|
||||
"path": transport["path"],
|
||||
"tls": "tls" if (tls["enable"] or reality["enable"]) else "",
|
||||
"sni": tls.get("serverName") or server_address,
|
||||
}
|
||||
return "vmess://" + _b64(json.dumps(blob, separators=(",", ":")))
|
||||
|
||||
|
||||
def build_share_link(listener: dict, server_address: str, user_index: int = 0) -> str:
|
||||
"""Build the client-facing share URL for a listener."""
|
||||
tag = listener["tag"]
|
||||
listener_type = listener["type"]
|
||||
users = listener["users"]
|
||||
if not users:
|
||||
raise ValueError(f"listener '{tag}': no users to build a share link for")
|
||||
if user_index < 0 or user_index >= len(users):
|
||||
raise ValueError(f"listener '{tag}': user index {user_index} is out of range")
|
||||
|
||||
user = users[user_index]
|
||||
secret = _user_secret(user, listener_type, tag)
|
||||
user_name = user.get("name") or f"{tag}-{user_index}"
|
||||
label = f"{tag} ({user_name})"
|
||||
fragment = urllib.parse.quote(label, safe="")
|
||||
host = f"[{server_address}]" if ":" in server_address else server_address
|
||||
endpoint = f"{host}:{_share_port(listener)}"
|
||||
|
||||
if listener_type == "vmess":
|
||||
return _vmess_link(listener, secret, server_address, label)
|
||||
|
||||
if listener_type == "shadowsocks":
|
||||
userinfo = _b64(f"{listener['method']}:{secret}")
|
||||
return f"ss://{userinfo}@{endpoint}#{fragment}"
|
||||
|
||||
if listener_type in ("socks", "http"):
|
||||
if listener_type == "socks":
|
||||
userinfo = _b64(f"{user_name}:{secret}")
|
||||
return f"socks://{userinfo}@{endpoint}#{fragment}"
|
||||
credentials = urllib.parse.quote(user_name, safe="") + ":" + urllib.parse.quote(secret, safe="")
|
||||
return f"http://{credentials}@{endpoint}#{fragment}"
|
||||
|
||||
params = _link_transport_params(listener)
|
||||
params.update(_link_security_params(listener, server_address))
|
||||
if listener_type == "vless" and listener.get("flow"):
|
||||
params["flow"] = listener["flow"]
|
||||
query = urllib.parse.urlencode(params, quote_via=urllib.parse.quote)
|
||||
return f"{listener_type}://{secret}@{endpoint}?{query}#{fragment}"
|
||||
|
||||
|
||||
def build_listener(listener: dict, server_address: str, share_links: bool) -> dict:
|
||||
"""Render one listener into its inbound object and, when possible, a link.
|
||||
|
||||
Raw-JSON listeners are passed through untouched apart from the tag, and get
|
||||
no share link: proxy-suite does not know what they serve.
|
||||
"""
|
||||
tag = listener["tag"]
|
||||
|
||||
if listener.get("jsonFile") is not None:
|
||||
with open(listener["jsonFile"], encoding="utf-8") as handle:
|
||||
inbound = json.load(handle)
|
||||
return {"tag": tag, "inbound": {**inbound, "tag": tag}, "links": []}
|
||||
|
||||
if listener.get("xrayJson") is not None:
|
||||
return {"tag": tag, "inbound": {**listener["xrayJson"], "tag": tag}, "links": []}
|
||||
|
||||
inbound = render_xray_inbound(listener)
|
||||
links = (
|
||||
[build_share_link(listener, server_address, index) for index in range(len(listener["users"]))]
|
||||
if share_links
|
||||
else []
|
||||
)
|
||||
return {"tag": tag, "type": listener["type"], "port": _share_port(listener), "inbound": inbound, "links": links}
|
||||
|
||||
|
||||
def build_inbounds(spec: dict, server_address: str) -> dict:
|
||||
"""Render a whole spec into {"inbounds": [...], "links": [...]}."""
|
||||
inbounds = []
|
||||
links = []
|
||||
for listener in spec["listeners"]:
|
||||
rendered = build_listener(listener, server_address, spec.get("shareLinks", True))
|
||||
inbounds.append(rendered["inbound"])
|
||||
for index, link in enumerate(rendered["links"]):
|
||||
user = listener["users"][index]
|
||||
links.append(
|
||||
{
|
||||
"tag": rendered["tag"],
|
||||
"user": user.get("name") or f"{rendered['tag']}-{index}",
|
||||
"type": rendered.get("type", ""),
|
||||
"port": rendered.get("port", 0),
|
||||
"link": link,
|
||||
}
|
||||
)
|
||||
return {"inbounds": inbounds, "links": links}
|
||||
@@ -0,0 +1,454 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import tempfile
|
||||
import unittest
|
||||
import urllib.parse
|
||||
|
||||
from proxy_inbound import build_inbounds, build_share_link, render_xray_inbound
|
||||
from proxy_parsing import build_outbound
|
||||
|
||||
|
||||
def listener(**overrides):
|
||||
"""A listener spec with the same defaults the Nix option tree renders."""
|
||||
spec = {
|
||||
"tag": "test-in",
|
||||
"type": "vless",
|
||||
"port": 443,
|
||||
"sharePort": None,
|
||||
"listen": "::",
|
||||
"via": "direct",
|
||||
"users": [{"name": "", "uuid": "uuid-1", "uuidFile": None, "password": None, "passwordFile": None}],
|
||||
"flow": None,
|
||||
"method": "2022-blake3-aes-128-gcm",
|
||||
"transport": {"type": "raw", "path": "/", "host": None, "mode": None, "serviceName": ""},
|
||||
"tls": {"enable": False, "certificateFile": None, "keyFile": None, "serverName": None},
|
||||
"reality": {
|
||||
"enable": False,
|
||||
"dest": "www.microsoft.com:443",
|
||||
"serverNames": [],
|
||||
"privateKey": None,
|
||||
"privateKeyFile": None,
|
||||
"publicKey": None,
|
||||
"shortIds": [""],
|
||||
},
|
||||
"xrayJson": None,
|
||||
"jsonFile": None,
|
||||
}
|
||||
spec.update(overrides)
|
||||
return spec
|
||||
|
||||
|
||||
def reality(**overrides):
|
||||
settings = {
|
||||
"enable": True,
|
||||
"dest": "www.microsoft.com:443",
|
||||
"serverNames": ["www.microsoft.com"],
|
||||
"privateKey": "private-key",
|
||||
"privateKeyFile": None,
|
||||
"publicKey": "public-key",
|
||||
"shortIds": ["0123abcd"],
|
||||
}
|
||||
settings.update(overrides)
|
||||
return settings
|
||||
|
||||
|
||||
def link_params(link: str) -> dict:
|
||||
query = urllib.parse.urlsplit(link).query
|
||||
return dict(urllib.parse.parse_qsl(query))
|
||||
|
||||
|
||||
class RenderInboundTests(unittest.TestCase):
|
||||
def test_vless_reality_shape(self):
|
||||
ib = render_xray_inbound(listener(flow="xtls-rprx-vision", reality=reality()))
|
||||
self.assertEqual(ib["protocol"], "vless")
|
||||
self.assertEqual(ib["port"], 443)
|
||||
self.assertEqual(ib["listen"], "::")
|
||||
self.assertEqual(ib["settings"]["decryption"], "none")
|
||||
self.assertEqual(ib["settings"]["clients"][0]["id"], "uuid-1")
|
||||
self.assertEqual(ib["settings"]["clients"][0]["flow"], "xtls-rprx-vision")
|
||||
stream = ib["streamSettings"]
|
||||
self.assertEqual(stream["network"], "raw")
|
||||
self.assertEqual(stream["security"], "reality")
|
||||
self.assertEqual(stream["realitySettings"]["privateKey"], "private-key")
|
||||
self.assertEqual(stream["realitySettings"]["dest"], "www.microsoft.com:443")
|
||||
self.assertEqual(stream["realitySettings"]["shortIds"], ["0123abcd"])
|
||||
# The public key is a client-side concern; it must not leak into the server config.
|
||||
self.assertNotIn("publicKey", stream["realitySettings"])
|
||||
|
||||
def test_sniffing_is_route_only(self):
|
||||
# Domain rules (blockRu) need sniffing, but a server must not rewrite
|
||||
# the destination its clients asked for.
|
||||
ib = render_xray_inbound(listener())
|
||||
self.assertTrue(ib["sniffing"]["enabled"])
|
||||
self.assertTrue(ib["sniffing"]["routeOnly"])
|
||||
|
||||
def test_secrets_are_read_from_files(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
uuid_path = os.path.join(tmp, "uuid")
|
||||
key_path = os.path.join(tmp, "key")
|
||||
with open(uuid_path, "w", encoding="utf-8") as handle:
|
||||
handle.write("file-uuid\n")
|
||||
with open(key_path, "w", encoding="utf-8") as handle:
|
||||
handle.write("file-key\n")
|
||||
|
||||
ib = render_xray_inbound(
|
||||
listener(
|
||||
users=[{"name": "", "uuid": None, "uuidFile": uuid_path}],
|
||||
reality=reality(privateKey=None, privateKeyFile=key_path),
|
||||
)
|
||||
)
|
||||
self.assertEqual(ib["settings"]["clients"][0]["id"], "file-uuid")
|
||||
self.assertEqual(ib["streamSettings"]["realitySettings"]["privateKey"], "file-key")
|
||||
|
||||
def test_empty_secret_file_is_rejected(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
uuid_path = os.path.join(tmp, "uuid")
|
||||
with open(uuid_path, "w", encoding="utf-8") as handle:
|
||||
handle.write("\n")
|
||||
with self.assertRaisesRegex(ValueError, "is empty"):
|
||||
render_xray_inbound(listener(users=[{"uuid": None, "uuidFile": uuid_path}]))
|
||||
|
||||
def test_ws_transport(self):
|
||||
ib = render_xray_inbound(
|
||||
listener(
|
||||
transport={"type": "ws", "path": "/download", "host": "cdn.example.com", "serviceName": ""},
|
||||
tls={
|
||||
"enable": True,
|
||||
"certificateFile": "/cert.pem",
|
||||
"keyFile": "/key.pem",
|
||||
"serverName": "cdn.example.com",
|
||||
},
|
||||
)
|
||||
)
|
||||
stream = ib["streamSettings"]
|
||||
self.assertEqual(stream["network"], "ws")
|
||||
self.assertEqual(stream["wsSettings"], {"path": "/download", "host": "cdn.example.com"})
|
||||
self.assertEqual(stream["security"], "tls")
|
||||
self.assertEqual(
|
||||
stream["tlsSettings"]["certificates"][0],
|
||||
{"certificateFile": "/cert.pem", "keyFile": "/key.pem"},
|
||||
)
|
||||
|
||||
def test_grpc_transport(self):
|
||||
ib = render_xray_inbound(
|
||||
listener(transport={"type": "grpc", "path": "/", "host": None, "serviceName": "GunService"})
|
||||
)
|
||||
self.assertEqual(ib["streamSettings"]["grpcSettings"], {"serviceName": "GunService"})
|
||||
|
||||
def test_trojan_forces_tls(self):
|
||||
ib = render_xray_inbound(
|
||||
listener(
|
||||
type="trojan",
|
||||
users=[{"name": "", "password": "pw", "passwordFile": None}],
|
||||
tls={
|
||||
"enable": False,
|
||||
"certificateFile": "/cert.pem",
|
||||
"keyFile": "/key.pem",
|
||||
"serverName": None,
|
||||
},
|
||||
)
|
||||
)
|
||||
self.assertEqual(ib["settings"]["clients"][0]["password"], "pw")
|
||||
self.assertEqual(ib["streamSettings"]["security"], "tls")
|
||||
|
||||
def test_shadowsocks_single_user_uses_password(self):
|
||||
ib = render_xray_inbound(
|
||||
listener(type="shadowsocks", users=[{"name": "", "password": "psk", "passwordFile": None}])
|
||||
)
|
||||
self.assertEqual(ib["settings"]["password"], "psk")
|
||||
self.assertEqual(ib["settings"]["method"], "2022-blake3-aes-128-gcm")
|
||||
self.assertEqual(ib["settings"]["network"], "tcp,udp")
|
||||
|
||||
def test_shadowsocks_multi_user_uses_clients(self):
|
||||
ib = render_xray_inbound(
|
||||
listener(
|
||||
type="shadowsocks",
|
||||
users=[
|
||||
{"name": "a", "password": "psk-a", "passwordFile": None},
|
||||
{"name": "b", "password": "psk-b", "passwordFile": None},
|
||||
],
|
||||
)
|
||||
)
|
||||
self.assertNotIn("password", ib["settings"])
|
||||
self.assertEqual(len(ib["settings"]["clients"]), 2)
|
||||
|
||||
def test_socks_accounts_and_udp(self):
|
||||
ib = render_xray_inbound(
|
||||
listener(type="socks", users=[{"name": "me", "password": "pw", "passwordFile": None}])
|
||||
)
|
||||
self.assertEqual(ib["settings"]["accounts"], [{"user": "me", "pass": "pw"}])
|
||||
self.assertTrue(ib["settings"]["udp"])
|
||||
|
||||
def test_unsupported_type_fails(self):
|
||||
with self.assertRaisesRegex(ValueError, "unsupported type"):
|
||||
render_xray_inbound(listener(type="hysteria2"))
|
||||
|
||||
|
||||
class ShareLinkTests(unittest.TestCase):
|
||||
def test_vless_reality_link(self):
|
||||
link = build_share_link(
|
||||
listener(flow="xtls-rprx-vision", reality=reality()), "vpn.example.com"
|
||||
)
|
||||
self.assertTrue(link.startswith("vless://uuid-1@vpn.example.com:443?"))
|
||||
params = link_params(link)
|
||||
self.assertEqual(params["security"], "reality")
|
||||
self.assertEqual(params["pbk"], "public-key")
|
||||
self.assertEqual(params["sid"], "0123abcd")
|
||||
self.assertEqual(params["sni"], "www.microsoft.com")
|
||||
self.assertEqual(params["flow"], "xtls-rprx-vision")
|
||||
self.assertEqual(params["type"], "tcp")
|
||||
|
||||
def test_reality_link_without_public_key_fails(self):
|
||||
with self.assertRaisesRegex(ValueError, "reality.publicKey is required"):
|
||||
build_share_link(listener(reality=reality(publicKey=None)), "vpn.example.com")
|
||||
|
||||
def test_empty_short_id_is_omitted(self):
|
||||
link = build_share_link(listener(reality=reality(shortIds=[""])), "vpn.example.com")
|
||||
self.assertNotIn("sid=", link)
|
||||
|
||||
def test_ipv6_server_address_is_bracketed(self):
|
||||
link = build_share_link(listener(reality=reality()), "2001:db8::1")
|
||||
self.assertIn("@[2001:db8::1]:443?", link)
|
||||
|
||||
def test_label_becomes_fragment(self):
|
||||
spec = listener(reality=reality())
|
||||
spec["users"][0]["name"] = "my phone"
|
||||
link = build_share_link(spec, "vpn.example.com")
|
||||
self.assertTrue(link.endswith("#test-in%20%28my%20phone%29"))
|
||||
|
||||
def test_multi_user_links_select_each_user(self):
|
||||
spec = listener(
|
||||
users=[
|
||||
{"name": "phone", "uuid": "uuid-phone", "password": None, "passwordFile": None},
|
||||
{"name": "laptop", "uuid": "uuid-laptop", "password": None, "passwordFile": None},
|
||||
]
|
||||
)
|
||||
phone = build_share_link(spec, "vpn.example.com", 0)
|
||||
laptop = build_share_link(spec, "vpn.example.com", 1)
|
||||
self.assertTrue(phone.startswith("vless://uuid-phone@"))
|
||||
self.assertTrue(laptop.startswith("vless://uuid-laptop@"))
|
||||
self.assertTrue(phone.endswith("#test-in%20%28phone%29"))
|
||||
self.assertTrue(laptop.endswith("#test-in%20%28laptop%29"))
|
||||
|
||||
def test_multi_user_password_links_select_each_account(self):
|
||||
spec = listener(
|
||||
type="socks",
|
||||
users=[
|
||||
{"name": "phone", "password": "pw-phone", "uuid": None, "uuidFile": None},
|
||||
{"name": "laptop", "password": "pw-laptop", "uuid": None, "uuidFile": None},
|
||||
],
|
||||
)
|
||||
link = build_share_link(spec, "vpn.example.com", 1)
|
||||
userinfo = link[len("socks://") :].split("@", 1)[0]
|
||||
decoded = base64.urlsafe_b64decode(userinfo + "=" * (-len(userinfo) % 4)).decode()
|
||||
self.assertEqual(decoded, "laptop:pw-laptop")
|
||||
|
||||
def test_vmess_link_blob(self):
|
||||
spec = listener(
|
||||
type="vmess",
|
||||
transport={"type": "ws", "path": "/v", "host": "cdn.example.com", "serviceName": ""},
|
||||
tls={"enable": True, "certificateFile": "/c", "keyFile": "/k", "serverName": "cdn.example.com"},
|
||||
)
|
||||
link = build_share_link(spec, "vpn.example.com")
|
||||
self.assertTrue(link.startswith("vmess://"))
|
||||
payload = link[len("vmess://") :]
|
||||
payload += "=" * (-len(payload) % 4)
|
||||
blob = json.loads(base64.urlsafe_b64decode(payload))
|
||||
self.assertEqual(blob["add"], "vpn.example.com")
|
||||
self.assertEqual(blob["id"], "uuid-1")
|
||||
self.assertEqual(blob["net"], "ws")
|
||||
self.assertEqual(blob["tls"], "tls")
|
||||
|
||||
def test_shadowsocks_link_is_sip002(self):
|
||||
spec = listener(type="shadowsocks", users=[{"name": "", "password": "psk", "passwordFile": None}])
|
||||
link = build_share_link(spec, "vpn.example.com")
|
||||
userinfo = link[len("ss://") :].split("@", 1)[0]
|
||||
userinfo += "=" * (-len(userinfo) % 4)
|
||||
decoded = base64.urlsafe_b64decode(userinfo).decode()
|
||||
self.assertEqual(decoded, "2022-blake3-aes-128-gcm:psk")
|
||||
|
||||
|
||||
class RoundTripTests(unittest.TestCase):
|
||||
"""A generated link must parse back into a working outbound.
|
||||
|
||||
This is what makes the links usable, including by proxy-suite itself as a
|
||||
client, so the two halves are pinned against each other here.
|
||||
"""
|
||||
|
||||
def test_vless_reality_round_trip(self):
|
||||
link = build_share_link(
|
||||
listener(flow="xtls-rprx-vision", reality=reality()), "vpn.example.com"
|
||||
)
|
||||
ob = build_outbound(link, "round-trip", backend="xray")
|
||||
self.assertEqual(ob["protocol"], "vless")
|
||||
settings = ob["settings"]
|
||||
self.assertEqual(settings["address"], "vpn.example.com")
|
||||
self.assertEqual(settings["port"], 443)
|
||||
self.assertEqual(settings["id"], "uuid-1")
|
||||
self.assertEqual(settings["flow"], "xtls-rprx-vision")
|
||||
rs = ob["streamSettings"]["realitySettings"]
|
||||
self.assertEqual(rs["publicKey"], "public-key")
|
||||
self.assertEqual(rs["shortId"], "0123abcd")
|
||||
self.assertEqual(rs["serverName"], "www.microsoft.com")
|
||||
|
||||
def test_vless_ws_tls_round_trip(self):
|
||||
link = build_share_link(
|
||||
listener(
|
||||
transport={"type": "ws", "path": "/download", "host": "cdn.example.com", "serviceName": ""},
|
||||
tls={
|
||||
"enable": True,
|
||||
"certificateFile": "/c",
|
||||
"keyFile": "/k",
|
||||
"serverName": "cdn.example.com",
|
||||
},
|
||||
),
|
||||
"vpn.example.com",
|
||||
)
|
||||
ob = build_outbound(link, "round-trip", backend="sing-box")
|
||||
self.assertEqual(ob["type"], "vless")
|
||||
self.assertEqual(ob["transport"]["type"], "ws")
|
||||
self.assertEqual(ob["transport"]["path"], "/download")
|
||||
self.assertEqual(ob["tls"]["server_name"], "cdn.example.com")
|
||||
|
||||
def test_trojan_round_trip(self):
|
||||
link = build_share_link(
|
||||
listener(
|
||||
type="trojan",
|
||||
users=[{"name": "", "password": "pw", "passwordFile": None}],
|
||||
tls={"enable": False, "certificateFile": "/c", "keyFile": "/k", "serverName": None},
|
||||
),
|
||||
"vpn.example.com",
|
||||
)
|
||||
ob = build_outbound(link, "round-trip", backend="sing-box")
|
||||
self.assertEqual(ob["type"], "trojan")
|
||||
self.assertEqual(ob["password"], "pw")
|
||||
|
||||
def test_shadowsocks_round_trip(self):
|
||||
link = build_share_link(
|
||||
listener(type="shadowsocks", users=[{"name": "", "password": "psk", "passwordFile": None}]),
|
||||
"vpn.example.com",
|
||||
)
|
||||
ob = build_outbound(link, "round-trip", backend="sing-box")
|
||||
self.assertEqual(ob["type"], "shadowsocks")
|
||||
self.assertEqual(ob["method"], "2022-blake3-aes-128-gcm")
|
||||
self.assertEqual(ob["password"], "psk")
|
||||
|
||||
def test_vmess_round_trip(self):
|
||||
link = build_share_link(listener(type="vmess"), "vpn.example.com")
|
||||
ob = build_outbound(link, "round-trip", backend="sing-box")
|
||||
self.assertEqual(ob["type"], "vmess")
|
||||
self.assertEqual(ob["uuid"], "uuid-1")
|
||||
|
||||
|
||||
class BuildInboundsTests(unittest.TestCase):
|
||||
def test_spec_renders_inbounds_and_links(self):
|
||||
spec = {
|
||||
"serverAddress": "vpn.example.com",
|
||||
"shareLinks": True,
|
||||
"listeners": [
|
||||
listener(tag="a", reality=reality()),
|
||||
listener(tag="b", port=8443, type="socks", users=[{"name": "u", "password": "p"}]),
|
||||
],
|
||||
}
|
||||
result = build_inbounds(spec, "vpn.example.com")
|
||||
self.assertEqual([ib["tag"] for ib in result["inbounds"]], ["a", "b"])
|
||||
self.assertEqual([entry["tag"] for entry in result["links"]], ["a", "b"])
|
||||
self.assertEqual(result["links"][1]["port"], 8443)
|
||||
|
||||
def test_xhttp_mode_reaches_the_inbound_and_the_link(self):
|
||||
spec = listener(
|
||||
transport={"type": "xhttp", "path": "/p", "host": None, "mode": "packet-up", "serviceName": ""}
|
||||
)
|
||||
stream = render_xray_inbound(spec)["streamSettings"]
|
||||
self.assertEqual(stream["xhttpSettings"]["mode"], "packet-up")
|
||||
# Without it in the link the client picks a mode on its own, which is
|
||||
# what breaks XHTTP behind an HTTP/1.1 reverse proxy.
|
||||
self.assertEqual(link_params(build_share_link(spec, "vpn.example.com"))["mode"], "packet-up")
|
||||
|
||||
def test_share_port_overrides_the_bound_port(self):
|
||||
spec = {
|
||||
"serverAddress": "vpn.example.com",
|
||||
"shareLinks": True,
|
||||
"listeners": [
|
||||
listener(
|
||||
port=10002,
|
||||
sharePort=443,
|
||||
listen="127.0.0.1",
|
||||
tls={"enable": True, "certificateFile": "/c", "keyFile": "/k", "serverName": None},
|
||||
transport={"type": "ws", "path": "/vpnjantit", "host": None, "serviceName": ""},
|
||||
)
|
||||
],
|
||||
}
|
||||
result = build_inbounds(spec, "vpn.example.com")
|
||||
# The listener still binds where it was told to; only the link moves.
|
||||
self.assertEqual(result["inbounds"][0]["port"], 10002)
|
||||
self.assertEqual(result["links"][0]["port"], 443)
|
||||
link = result["links"][0]["link"]
|
||||
self.assertTrue(link.startswith("vless://uuid-1@vpn.example.com:443?"), link)
|
||||
self.assertEqual(link_params(link)["path"], "/vpnjantit")
|
||||
|
||||
def test_spec_emits_one_link_per_user(self):
|
||||
spec = {
|
||||
"serverAddress": "vpn.example.com",
|
||||
"shareLinks": True,
|
||||
"listeners": [
|
||||
listener(
|
||||
users=[
|
||||
{"name": "phone", "uuid": "uuid-phone", "password": None, "passwordFile": None},
|
||||
{"name": "laptop", "uuid": "uuid-laptop", "password": None, "passwordFile": None},
|
||||
]
|
||||
)
|
||||
],
|
||||
}
|
||||
result = build_inbounds(spec, "vpn.example.com")
|
||||
self.assertEqual([entry["user"] for entry in result["links"]], ["phone", "laptop"])
|
||||
self.assertTrue(result["links"][1]["link"].startswith("vless://uuid-laptop@"))
|
||||
|
||||
def test_share_links_disabled_emits_no_links(self):
|
||||
spec = {
|
||||
"serverAddress": "vpn.example.com",
|
||||
"shareLinks": False,
|
||||
"listeners": [listener(reality=reality(publicKey=None))],
|
||||
}
|
||||
result = build_inbounds(spec, "vpn.example.com")
|
||||
self.assertEqual(result["links"], [])
|
||||
self.assertEqual(len(result["inbounds"]), 1)
|
||||
|
||||
def test_raw_json_listener_passes_through_with_tag(self):
|
||||
spec = {
|
||||
"serverAddress": "vpn.example.com",
|
||||
"shareLinks": True,
|
||||
"listeners": [
|
||||
listener(
|
||||
tag="raw",
|
||||
type=None,
|
||||
xrayJson={"protocol": "dokodemo-door", "tag": "ignored", "port": 8080},
|
||||
)
|
||||
],
|
||||
}
|
||||
result = build_inbounds(spec, "vpn.example.com")
|
||||
self.assertEqual(result["inbounds"][0]["protocol"], "dokodemo-door")
|
||||
self.assertEqual(result["inbounds"][0]["tag"], "raw")
|
||||
self.assertEqual(result["links"], [])
|
||||
|
||||
def test_json_file_listener_is_read_at_runtime(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
path = os.path.join(tmp, "inbound.json")
|
||||
with open(path, "w", encoding="utf-8") as handle:
|
||||
json.dump({"protocol": "vless", "port": 2053, "settings": {"clients": []}}, handle)
|
||||
spec = {
|
||||
"serverAddress": "vpn.example.com",
|
||||
"shareLinks": True,
|
||||
"listeners": [listener(tag="secret-in", type=None, jsonFile=path)],
|
||||
}
|
||||
result = build_inbounds(spec, "vpn.example.com")
|
||||
self.assertEqual(result["inbounds"][0]["tag"], "secret-in")
|
||||
self.assertEqual(result["inbounds"][0]["port"], 2053)
|
||||
self.assertEqual(result["links"], [])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user