feat: share-variants
This commit is contained in:
13 files changed
+593
-25
No files matched your search
@@ -47,6 +47,8 @@ TYPES = UUID_TYPES + PASSWORD_TYPES
|
||||
TRANSPORTS = ("raw", "ws", "grpc", "httpupgrade", "xhttp")
|
||||
XHTTP_MODES = ("auto", "packet-up", "stream-up", "stream-one")
|
||||
ALPNS = ("h3", "h2", "http/1.1")
|
||||
# As the shareFingerprint option takes them (options/types/inbounds.nix).
|
||||
FINGERPRINTS = ("chrome", "firefox", "safari", "ios", "android", "edge", "360", "qq", "random", "randomized")
|
||||
# Shadowsocks 2022 keys, by method: bytes of base64 key.
|
||||
SS2022_KEY_BYTES = {
|
||||
"2022-blake3-aes-128-gcm": 16,
|
||||
@@ -203,6 +205,7 @@ LISTENER_SCHEMA = {
|
||||
"port": _is_port,
|
||||
"sharePort": _nullable(_is_port),
|
||||
"shareAddress": _nullable(_nonspace),
|
||||
"shareFingerprint": _nullable(_one_of(*FINGERPRINTS)),
|
||||
"address": _nonspace,
|
||||
"acceptProxyProtocol": _is_bool,
|
||||
"via": _nullable(_nonspace),
|
||||
@@ -538,6 +541,8 @@ def _render_listener(tag: str, entry: dict, runtime: dict) -> dict:
|
||||
tls["serverName"] = certificate.get("serverName")
|
||||
hysteria = filled.setdefault("hysteria", {})
|
||||
hysteria["portHopping"] = None
|
||||
# Declared listeners only: the module's assertions are what check them.
|
||||
filled["shareVariants"] = []
|
||||
hysteria.setdefault("salamander", {})["passwordFile"] = None
|
||||
filled["serverPasswordFile"] = None
|
||||
filled["xrayJson"] = None
|
||||
@@ -1044,7 +1049,8 @@ def listener_from_flags(kind: str, args: argparse.Namespace) -> dict:
|
||||
"""A listener entry from `add <tag> <type> [flags]`."""
|
||||
entry: dict = {"type": kind}
|
||||
for flag, key in (("port", "port"), ("listen", "address"), ("via", "via"), ("share_port", "sharePort"),
|
||||
("share_address", "shareAddress"), ("order", "order"), ("method", "method")):
|
||||
("share_address", "shareAddress"), ("fingerprint", "shareFingerprint"), ("order", "order"),
|
||||
("method", "method")):
|
||||
if getattr(args, flag) is not None:
|
||||
entry[key] = getattr(args, flag)
|
||||
if args.flow:
|
||||
@@ -1232,7 +1238,7 @@ def main(argv: list[str] | None = None) -> int:
|
||||
add.add_argument("tag")
|
||||
add.add_argument("source", help="a listener type, a JSON file, or - for JSON on stdin")
|
||||
for flag, kind in (("--port", int), ("--listen", str), ("--via", str), ("--share-port", int), ("--share-address", str),
|
||||
("--order", int), ("--method", str), ("--flow", str), ("--transport", str), ("--path", str),
|
||||
("--fingerprint", str), ("--order", int), ("--method", str), ("--flow", str), ("--transport", str), ("--path", str),
|
||||
("--host", str), ("--mode", str), ("--service-name", str), ("--tls", str), ("--alpn", str),
|
||||
("--sni", str), ("--reality", str), ("--reality-dest", str), ("--short-id", str),
|
||||
("--masquerade", str)):
|
||||
|
||||
@@ -274,7 +274,10 @@ def _link_transport_params(listener: dict) -> dict:
|
||||
return params
|
||||
|
||||
|
||||
def _link_security_params(listener: dict, server_address: str) -> dict:
|
||||
def _link_security_params(listener: dict, server_address: str, fingerprint: str | None) -> dict:
|
||||
"""The link's security: the TLS or REALITY of the listener it dials (`listener`, the
|
||||
front of one behind a fallback), with the browser fingerprint the link's own listener
|
||||
names, if any."""
|
||||
reality = listener["reality"]
|
||||
tls = listener["tls"]
|
||||
if reality["enable"]:
|
||||
@@ -289,8 +292,9 @@ def _link_security_params(listener: dict, server_address: str) -> dict:
|
||||
"security": "reality",
|
||||
"pbk": reality["publicKey"],
|
||||
"sni": server_names[0] if server_names else server_address,
|
||||
"fp": "chrome",
|
||||
}
|
||||
if fingerprint:
|
||||
params["fp"] = fingerprint
|
||||
if short_ids and short_ids[0]:
|
||||
params["sid"] = short_ids[0]
|
||||
return params
|
||||
@@ -298,8 +302,9 @@ def _link_security_params(listener: dict, server_address: str) -> dict:
|
||||
params = {
|
||||
"security": "tls",
|
||||
"sni": tls.get("serverName") or server_address,
|
||||
"fp": "chrome",
|
||||
}
|
||||
if fingerprint:
|
||||
params["fp"] = fingerprint
|
||||
# A client left to its own ALPN offers h2 and http/1.1, and so never
|
||||
# reaches an HTTP/3-only listener at all.
|
||||
if tls.get("alpn"):
|
||||
@@ -333,13 +338,32 @@ def _vmess_link(
|
||||
return "vmess://" + _b64(json.dumps(blob, separators=(",", ":")))
|
||||
|
||||
|
||||
def _apply_variant(params: dict, variant: dict, listener_type: str) -> None:
|
||||
"""Rewrite a link's query for a share variant: only what the client sends changes."""
|
||||
if variant.get("fingerprint") is not None and params.get("security") in ("tls", "reality"):
|
||||
params["fp"] = variant["fingerprint"]
|
||||
if variant.get("alpn") is not None:
|
||||
if variant["alpn"]:
|
||||
params["alpn"] = ",".join(variant["alpn"])
|
||||
else:
|
||||
params.pop("alpn", None)
|
||||
if variant.get("mode") is not None and params.get("type") == "xhttp":
|
||||
params["mode"] = variant["mode"]
|
||||
if variant.get("serverName") is not None and "sni" in params:
|
||||
params["sni"] = variant["serverName"]
|
||||
if listener_type == "hysteria2" and variant.get("portHopping") is False:
|
||||
params.pop("mport", None)
|
||||
|
||||
|
||||
def build_share_link(
|
||||
listener: dict, server_address: str, user_index: int = 0, onion_address: str = ""
|
||||
listener: dict, server_address: str, user_index: int = 0, onion_address: str = "", variant: dict | None = None
|
||||
) -> str:
|
||||
"""Build the client-facing share URL for a listener.
|
||||
|
||||
With an onion address the link dials that instead, through the client's Tor; the TLS
|
||||
and REALITY names stay those of server_address, which the listener still answers to.
|
||||
A share variant (listener["shareVariants"]) changes what the client sends: fingerprint,
|
||||
ALPN, xhttp mode, the address it dials and the SNI, hysteria2's port hopping.
|
||||
"""
|
||||
tag = listener["tag"]
|
||||
listener_type = listener["type"]
|
||||
@@ -358,9 +382,13 @@ def build_share_link(
|
||||
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}, onion)" if onion_address else f"{tag} ({user_name})"
|
||||
variant = variant or {}
|
||||
if variant:
|
||||
label = f"{tag} {variant['name']} ({user_name})"
|
||||
else:
|
||||
label = f"{tag} ({user_name}, onion)" if onion_address else f"{tag} ({user_name})"
|
||||
fragment = urllib.parse.quote(label, safe="")
|
||||
endpoint_address = onion_address or server_address
|
||||
endpoint_address = onion_address or variant.get("address") or server_address
|
||||
host = f"[{endpoint_address}]" if ":" in endpoint_address else endpoint_address
|
||||
endpoint = f"{host}:{_share_port(front)}"
|
||||
|
||||
@@ -397,13 +425,15 @@ def build_share_link(
|
||||
hopping = (listener.get("hysteria") or {}).get("portHopping")
|
||||
if hopping:
|
||||
params["mport"] = hopping
|
||||
_apply_variant(params, variant, listener_type)
|
||||
query = urllib.parse.urlencode(params, quote_via=urllib.parse.quote)
|
||||
return f"hysteria2://{urllib.parse.quote(secret, safe='')}@{endpoint}?{query}#{fragment}"
|
||||
|
||||
params = _link_transport_params(listener)
|
||||
params.update(_link_security_params(front, server_address))
|
||||
params.update(_link_security_params(front, server_address, listener.get("shareFingerprint")))
|
||||
if listener_type == "vless" and listener.get("flow"):
|
||||
params["flow"] = listener["flow"]
|
||||
_apply_variant(params, variant, listener_type)
|
||||
query = urllib.parse.urlencode(params, quote_via=urllib.parse.quote)
|
||||
return f"{listener_type}://{secret}@{endpoint}?{query}#{fragment}"
|
||||
|
||||
@@ -475,12 +505,27 @@ def build_listener(
|
||||
if share_links and onion_address
|
||||
else []
|
||||
)
|
||||
variant_links = (
|
||||
[
|
||||
(
|
||||
variant["name"],
|
||||
[
|
||||
build_share_link(listener, server_address, index, variant=variant)
|
||||
for index in range(len(listener["users"]))
|
||||
],
|
||||
)
|
||||
for variant in listener.get("shareVariants") or []
|
||||
]
|
||||
if share_links
|
||||
else []
|
||||
)
|
||||
return {
|
||||
"tag": tag,
|
||||
"type": listener["type"],
|
||||
"port": _share_port(listener.get("front") or listener),
|
||||
"inbound": inbound,
|
||||
"links": links,
|
||||
"variantLinks": variant_links,
|
||||
"onionLinks": onion_links,
|
||||
}
|
||||
|
||||
@@ -513,7 +558,8 @@ def build_inbounds(spec: dict, server_address: str, onion_address: str = "") ->
|
||||
|
||||
A subscription gathers one user's links from every listener -- users are
|
||||
matched by name -- as base64 of the newline-joined links, which is what
|
||||
v2rayNG, Hiddify and NekoBox import. Listeners in spec["onionListeners"] get a
|
||||
v2rayNG, Hiddify and NekoBox import. A listener's share variants follow its own
|
||||
link, each with "variant": its name. Listeners in spec["onionListeners"] get a
|
||||
second link per user to onion_address, with "variant": "onion", in both.
|
||||
"""
|
||||
inbounds = []
|
||||
@@ -524,6 +570,8 @@ def build_inbounds(spec: dict, server_address: str, onion_address: str = "") ->
|
||||
rendered = build_listener(listener, server_address, spec.get("shareLinks", True), onion)
|
||||
inbounds.append(rendered["inbound"])
|
||||
variants = [(rendered["links"], {})]
|
||||
for name, variant_links in rendered.get("variantLinks") or []:
|
||||
variants.append((variant_links, {"variant": name}))
|
||||
if rendered.get("onionLinks"):
|
||||
variants.append((rendered["onionLinks"], {"variant": "onion"}))
|
||||
for variant_links, extra in variants:
|
||||
|
||||
@@ -18,6 +18,7 @@ def listener(**overrides):
|
||||
"type": "vless",
|
||||
"port": 443,
|
||||
"sharePort": None,
|
||||
"shareFingerprint": "chrome",
|
||||
"acceptProxyProtocol": False,
|
||||
"listen": "::",
|
||||
"via": "direct",
|
||||
@@ -489,6 +490,25 @@ class RoundTripTests(unittest.TestCase):
|
||||
self.assertEqual([m["type"] for m in masks], ["udphop", "salamander"])
|
||||
self.assertEqual(masks[0]["settings"]["remotePorts"], "20000-30000")
|
||||
|
||||
def test_share_fingerprint_names_the_browser_or_leaves_it_to_the_client(self):
|
||||
tls = {"enable": True, "certificateFile": "/c", "keyFile": "/k", "serverName": None}
|
||||
self.assertEqual(link_params(build_share_link(listener(tls=tls), "vpn.example.com"))["fp"], "chrome")
|
||||
firefox = build_share_link(listener(tls=tls, shareFingerprint="firefox"), "vpn.example.com")
|
||||
self.assertEqual(link_params(firefox)["fp"], "firefox")
|
||||
self.assertEqual(build_outbound(firefox, "fp", backend="xray")["streamSettings"]["tlsSettings"]["fingerprint"], "firefox")
|
||||
self.assertNotIn("fp", link_params(build_share_link(listener(tls=tls, shareFingerprint=None), "vpn.example.com")))
|
||||
# REALITY's too; without TLS there is no handshake to shape.
|
||||
self.assertEqual(link_params(build_share_link(listener(reality=reality(), shareFingerprint="safari"), "vpn.example.com"))["fp"], "safari")
|
||||
self.assertNotIn("fp", link_params(build_share_link(listener(shareFingerprint="safari"), "vpn.example.com")))
|
||||
# A variant's own fingerprint wins, and one is added where the listener names none.
|
||||
variant = {"name": "ff", "fingerprint": "firefox"}
|
||||
self.assertEqual(link_params(build_share_link(listener(tls=tls, shareFingerprint="safari"), "vpn.example.com", variant=variant))["fp"], "firefox")
|
||||
self.assertEqual(link_params(build_share_link(listener(tls=tls, shareFingerprint=None), "vpn.example.com", variant=variant))["fp"], "firefox")
|
||||
self.assertEqual(
|
||||
link_params(build_share_link(listener(tls=tls, shareFingerprint="safari"), "vpn.example.com", variant={"name": "plain"}))["fp"],
|
||||
"safari",
|
||||
)
|
||||
|
||||
def test_share_address_is_dialled_and_the_default_sni(self):
|
||||
tls = {"enable": True, "certificateFile": "/c", "keyFile": "/k", "serverName": None}
|
||||
front = listener(shareAddress="cdn.example.com", tls=tls, flow="xtls-rprx-vision")
|
||||
@@ -794,6 +814,75 @@ class BuildInboundsTests(unittest.TestCase):
|
||||
self.assertEqual([e for e in without["links"] if e.get("variant")], [])
|
||||
self.assertEqual(without["inbounds"], result["inbounds"])
|
||||
|
||||
def test_share_variants_change_only_what_the_client_sends(self):
|
||||
tls = {"enable": True, "certificateFile": "/c", "keyFile": "/k", "serverName": "x.example.com", "alpn": ["h2"]}
|
||||
users = [{"name": "alice", "uuid": "uuid-1", "uuidFile": None, "password": "pw", "passwordFile": None}]
|
||||
xhttp = {"type": "xhttp", "path": "/x", "host": None, "mode": None, "serviceName": "", "trustedXForwardedFor": []}
|
||||
variants = [
|
||||
{"name": "firefox", "fingerprint": "firefox"},
|
||||
{"name": "h1", "alpn": ["http/1.1"]},
|
||||
{"name": "any-alpn", "alpn": []},
|
||||
{"name": "stream-one", "mode": "stream-one"},
|
||||
{"name": "fresh", "address": "img.example.com", "serverName": "img.example.com"},
|
||||
]
|
||||
spec = {
|
||||
"serverAddress": "vpn.example.com",
|
||||
"shareLinks": True,
|
||||
"listeners": [
|
||||
listener(tag="xh", users=users, port=10005, sharePort=443, tls=tls, transport=xhttp, shareVariants=variants),
|
||||
listener(
|
||||
tag="hy2",
|
||||
type="hysteria2",
|
||||
users=users,
|
||||
tls=dict(tls, alpn=None),
|
||||
hysteria={"masquerade": None, "portHopping": "20000-20010"},
|
||||
shareVariants=[{"name": "no-hop", "portHopping": False}],
|
||||
),
|
||||
],
|
||||
}
|
||||
result = build_inbounds(spec, "vpn.example.com")
|
||||
# The listeners render as without variants: they change links only.
|
||||
self.assertEqual(
|
||||
result["inbounds"],
|
||||
build_inbounds({**spec, "listeners": [dict(l, shareVariants=[]) for l in spec["listeners"]]}, "vpn.example.com")["inbounds"],
|
||||
)
|
||||
by_variant = {(e["tag"], e.get("variant", "")): e for e in result["links"]}
|
||||
self.assertEqual(
|
||||
[(e["tag"], e.get("variant", "")) for e in result["links"]],
|
||||
[("xh", ""), ("xh", "firefox"), ("xh", "h1"), ("xh", "any-alpn"), ("xh", "stream-one"), ("xh", "fresh"), ("hy2", ""), ("hy2", "no-hop")],
|
||||
)
|
||||
base = link_params(by_variant[("xh", "")]["link"])
|
||||
self.assertEqual((base["fp"], base["alpn"], base.get("mode")), ("chrome", "h2", None))
|
||||
|
||||
def params(variant):
|
||||
entry = by_variant[("xh", variant)]
|
||||
self.assertIn(f"xh {variant} (alice)", urllib.parse.unquote(urllib.parse.urlsplit(entry["link"]).fragment))
|
||||
return link_params(entry["link"])
|
||||
|
||||
self.assertEqual(params("firefox"), dict(base, fp="firefox"))
|
||||
self.assertEqual(params("h1"), dict(base, alpn="http/1.1"))
|
||||
self.assertEqual(params("any-alpn"), {k: v for k, v in base.items() if k != "alpn"})
|
||||
self.assertEqual(params("stream-one"), dict(base, mode="stream-one"))
|
||||
self.assertEqual(params("fresh"), dict(base, sni="img.example.com"))
|
||||
self.assertTrue(by_variant[("xh", "fresh")]["link"].startswith("vless://uuid-1@img.example.com:443?"))
|
||||
|
||||
# Each reads back into a client config that sends what it says.
|
||||
stream = by_variant[("xh", "firefox")]["outbound"]["streamSettings"]
|
||||
self.assertEqual(stream["tlsSettings"]["fingerprint"], "firefox")
|
||||
self.assertEqual(by_variant[("xh", "h1")]["outbound"]["streamSettings"]["tlsSettings"]["alpn"], ["http/1.1"])
|
||||
self.assertEqual(by_variant[("xh", "stream-one")]["outbound"]["streamSettings"]["xhttpSettings"]["mode"], "stream-one")
|
||||
|
||||
hop = link_params(by_variant[("hy2", "")]["link"])
|
||||
self.assertEqual(hop["mport"], "20000-20010")
|
||||
self.assertEqual(link_params(by_variant[("hy2", "no-hop")]["link"]), {k: v for k, v in hop.items() if k != "mport"})
|
||||
self.assertNotIn("server_ports", by_variant[("hy2", "no-hop")]["outbound"])
|
||||
|
||||
# One subscription, every link in that order, and the same token as without variants.
|
||||
body = base64.b64decode(result["subscriptions"][0]["body"]).decode().split("\n")
|
||||
self.assertEqual(body, [e["link"] for e in result["links"]])
|
||||
plain = build_inbounds({**spec, "listeners": [dict(l, shareVariants=[]) for l in spec["listeners"]]}, "vpn.example.com")
|
||||
self.assertEqual(result["subscriptions"][0]["token"], plain["subscriptions"][0]["token"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -230,7 +230,7 @@ class RuntimeTest(unittest.TestCase):
|
||||
|
||||
def test_reality_listener_gets_generated_keys(self):
|
||||
args = rt.main.__globals__["argparse"].Namespace(
|
||||
port=20001, listen=None, via=None, share_port=None, share_address=None, order=None, method=None,
|
||||
port=20001, listen=None, via=None, share_port=None, share_address=None, fingerprint="firefox", order=None, method=None,
|
||||
flow="vision", transport=None, path=None, host=None, mode=None, service_name=None, tls=None, alpn=None,
|
||||
sni=None, reality="www.example.com,example.com", reality_dest=None, short_id=None, masquerade=None,
|
||||
salamander=False, user=["bob"],
|
||||
@@ -238,6 +238,7 @@ class RuntimeTest(unittest.TestCase):
|
||||
entry = rt.listener_from_flags("vless", args)
|
||||
self.assertEqual(entry["reality"]["dest"], "www.example.com:443")
|
||||
self.assertEqual(entry["flow"], "xtls-rprx-vision")
|
||||
self.assertEqual(entry["shareFingerprint"], "firefox")
|
||||
rt.cmd_add(self.spec, self.spool, "friends", entry, self.xray)
|
||||
saved = self.state()["listeners"]["friends"]
|
||||
self.assertEqual((saved["reality"]["privateKey"], saved["reality"]["publicKey"]), ("private-x", "public-x"))
|
||||
@@ -245,6 +246,7 @@ class RuntimeTest(unittest.TestCase):
|
||||
merged, result, _ = rt.merge(self.spec)
|
||||
friends = next(l for l in merged["listeners"] if l["tag"] == "friends")
|
||||
self.assertEqual(friends["listen"], "::")
|
||||
self.assertEqual(friends["shareFingerprint"], "firefox")
|
||||
self.assertEqual(friends["via"], "proxy")
|
||||
self.assertTrue(friends["runtime"])
|
||||
self.assertEqual(result["listeners"], ["friends"])
|
||||
@@ -259,6 +261,7 @@ class RuntimeTest(unittest.TestCase):
|
||||
({"type": "vless", "port": 20001, "tls": {"certificateFile": "/etc/shadow"}}, "not something a runtime entry can set"),
|
||||
({"type": "vless", "port": 20001, "xrayJson": {}}, "not something a runtime entry can set"),
|
||||
({"type": "amneziawg", "port": 20001}, "type: invalid value"),
|
||||
({"type": "vless", "port": 20001, "shareFingerprint": "netscape"}, "shareFingerprint: invalid value"),
|
||||
({"type": "hysteria2", "port": 20001, "hysteria": {"portHopping": "1-2"}}, "not something"),
|
||||
({"type": "vless", "port": 20001, "fallbacks": [{"dest": 22}]}, "not in inbounds.runtime.fallbackDests"),
|
||||
({"type": "vless", "port": 20001, "fallbacks": [{"listener": "vless-in"}]}, "must be another runtime listener"),
|
||||
|
||||
Reference in new issue
Block a user