diff --git a/modules/proxy-suite/service/script-blocks/subscriptions.nix b/modules/proxy-suite/service/script-blocks/subscriptions.nix index 9330d13..d53a3cf 100644 --- a/modules/proxy-suite/service/script-blocks/subscriptions.nix +++ b/modules/proxy-suite/service/script-blocks/subscriptions.nix @@ -33,7 +33,10 @@ let let urlSource = mkSubscriptionUrlSource sub; in - '' + # Both call sites append their own `> "$CACHE_FILE.tmp"`, so this must not + # end in a newline: that would close the pipeline and turn the redirect + # into a separate command that just truncates the cache to zero bytes. + lib.removeSuffix "\n" '' printf '%s' "$(cat "${urlSource}")" \ | PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${fetchSubscriptionPy} ${subscriptionBackendArg} --tag-prefix ${lib.escapeShellArg sub.tag} ''; diff --git a/nix/checks/subscriptions-runtime.nix b/nix/checks/subscriptions-runtime.nix index 6ea2444..fab149e 100644 --- a/nix/checks/subscriptions-runtime.nix +++ b/nix/checks/subscriptions-runtime.nix @@ -96,6 +96,18 @@ in true ) + # The fetcher's stdout has to land in the cache file. A newline between the + # pipeline and the redirect closes the pipeline, leaving a bare redirect + # that truncates the cache to zero bytes while the JSON goes to the journal. + ( + assert pkgs.lib.hasInfix ''--tag-prefix community > "$CACHE_FILE.tmp"'' + subscriptionOnlyStartScript; + assert pkgs.lib.hasInfix + ''--tag-prefix community > "/var/lib/proxy-suite/subscriptions/sing-box/community.json.tmp"'' + subscriptionOnlyUpdateScript; + true + ) + # Invalid cache files are ignored and refreshed. ( assert pkgs.lib.hasInfix "_proxy_suite_valid_subscription_cache()" subscriptionOnlyStartScript; diff --git a/scripts/proxy_parsing.py b/scripts/proxy_parsing.py index a555a5e..9d3ace0 100644 --- a/scripts/proxy_parsing.py +++ b/scripts/proxy_parsing.py @@ -238,7 +238,10 @@ def decode_subscription(data: bytes) -> list[str]: def slugify_tag(remark: str) -> str: - slug = re.sub(r"[^a-zA-Z0-9_-]", "-", remark) + # \w is Unicode-aware: non-Latin remarks (e.g. Cyrillic country names) keep + # their letters instead of collapsing to a bare "proxy" tag. Tags only ever + # reach JSON configs and the Clash API, both UTF-8 safe. + slug = re.sub(r"[^\w-]", "-", remark) slug = re.sub(r"-{2,}", "-", slug).strip("-") return slug[:60] or "proxy" diff --git a/scripts/proxy_url_parsers.py b/scripts/proxy_url_parsers.py index b2169c6..5c5c5ba 100644 --- a/scripts/proxy_url_parsers.py +++ b/scripts/proxy_url_parsers.py @@ -8,6 +8,7 @@ import urllib.parse SUPPORTED_VLESS_TRANSPORTS = { "", "tcp", + "raw", "ws", "grpc", "h2", @@ -38,11 +39,13 @@ def _split_host_port(hostpart: str) -> tuple[str, str]: def _parse_url_parts(url: str, scheme: str) -> tuple[str, str, str, dict]: rest = url[len(f"{scheme}://") :] rest, _, _ = rest.partition("#") - if "@" in rest: - userinfo, _, rest = rest.rpartition("@") - else: - userinfo = "" - hostpart, _, query = rest.partition("?") + # Split the query off before the userinfo: share links routinely carry '@' + # inside their parameters (Telegram=@handle, path=/x/?@channel), and an + # rpartition over the whole string swallows the host along with the userinfo. + authority, _, query = rest.partition("?") + userinfo, _, hostpart = authority.rpartition("@") + # "host:443/?type=tcp" – a trailing path is not part of the port. + hostpart, _, _ = hostpart.partition("/") host, port = _split_host_port(hostpart) return userinfo, host, port, _qs(query) @@ -68,7 +71,7 @@ def _mk_transport( ) -> "dict | None": normalized = transport_type.lower() - if normalized in ("", "tcp"): + if normalized in ("", "tcp", "raw"): return None if normalized == "ws": return { @@ -114,11 +117,41 @@ def _mk_transport( return None +def _require(params: dict, name: str, security: str) -> str: + if name not in params: + raise ValueError(f"{security} link is missing the '{name}' parameter") + return params[name] + + +# sing-box's uTLS build refuses to start on a fingerprint it does not know, so +# one bad share link would otherwise take the whole config down with it. XRay's +# set is larger (it has "unsafe"), so only an explicitly-XRay entry skips this. +SING_BOX_FINGERPRINTS = { + "chrome", + "firefox", + "edge", + "safari", + "360", + "qq", + "ios", + "android", + "random", + "randomized", +} + + def _mk_tls( - server_name: str, fp: "str | None" = None, alpn: "str | None" = None + server_name: str, + fp: "str | None" = None, + alpn: "str | None" = None, + backend: str = "sing-box", ) -> dict: tls: dict = {"enabled": True, "server_name": server_name} if fp: + if backend != "xray" and fp not in SING_BOX_FINGERPRINTS: + raise ValueError( + f"unsupported uTLS fingerprint '{fp}': sing-box would refuse to start" + ) tls["utls"] = {"enabled": True, "fingerprint": fp} if alpn: tls["alpn"] = alpn.split(",") @@ -163,17 +196,24 @@ def parse_vless(url: str, tag: str, backend: str = "sing-box") -> dict: } if security == "reality": - ob["tls"] = _mk_tls(params.get("sni", host), fp=params.get("fp", "chrome")) + ob["tls"] = _mk_tls( + params.get("sni", host), + fp=params.get("fp") or "chrome", + backend=backend, + ) ob["tls"]["reality"] = { "enabled": True, - "public_key": params["pbk"], + "public_key": _require(params, "pbk", "reality"), "short_id": params.get("sid", ""), } if backend == "xray" and params.get("spx"): ob["tls"]["reality"]["spider_x"] = params["spx"] elif security == "tls": ob["tls"] = _mk_tls( - params.get("sni", host), fp=params.get("fp"), alpn=params.get("alpn") + params.get("sni", host), + fp=params.get("fp"), + alpn=params.get("alpn"), + backend=backend, ) if backend == "xray" and "ech" in params: ob["tls"]["ech_config_list"] = urllib.parse.unquote(params["ech"]) diff --git a/scripts/test-build-outbound.py b/scripts/test-build-outbound.py index 7502dbc..1dca71d 100644 --- a/scripts/test-build-outbound.py +++ b/scripts/test-build-outbound.py @@ -53,6 +53,50 @@ class BuildOutboundTests(unittest.TestCase): ob["streamSettings"]["realitySettings"]["spiderX"], "/-/en/gp/bestsellers" ) + def test_vless_raw_transport_is_tcp(self): + # XRay renamed the tcp network to "raw"; it is still plain TCP. + ob = run_parser( + "vless://uuid@example.com:443?type=raw&security=reality&pbk=pubkey&fp=chrome&sni=cdn.example.com" + ) + self.assertNotIn("transport", ob) + + def test_at_sign_in_query_does_not_eat_the_host(self): + ob = run_parser( + "vless://uuid@example.com:443?type=tcp&security=reality&pbk=pubkey" + "&fp=chrome&sni=cdn.example.com&Telegram=@somechannel,@somechannel" + ) + self.assertEqual(ob["server"], "example.com") + self.assertEqual(ob["server_port"], 443) + + def test_trailing_path_is_not_part_of_the_port(self): + ob = run_parser( + "vless://uuid@example.com:23576/?type=tcp&security=reality&pbk=pubkey&fp=chrome&sni=cdn.example.com" + ) + self.assertEqual(ob["server_port"], 23576) + + def test_reality_empty_fingerprint_falls_back_to_chrome(self): + # sing-box's REALITY client refuses to start without a uTLS block. + ob = run_parser( + "vless://uuid@example.com:443?type=tcp&security=reality&pbk=pubkey&fp=&sni=cdn.example.com" + ) + self.assertEqual(ob["tls"]["utls"]["fingerprint"], "chrome") + + def test_xray_only_fingerprint_rejected_for_sing_box(self): + url = ( + "vless://uuid@example.com:443?type=tcp&security=reality&pbk=pubkey" + "&fp=unsafe&sni=cdn.example.com" + ) + with self.assertRaises(ValueError): + run_parser(url) + self.assertEqual( + run_xray_parser(url)["streamSettings"]["realitySettings"]["fingerprint"], + "unsafe", + ) + + def test_reality_without_pbk_is_rejected_clearly(self): + with self.assertRaisesRegex(ValueError, "pbk"): + run_parser("vless://uuid@example.com:443?security=reality&type=tcp") + def test_vless_httpupgrade_transport(self): ob = run_parser( "vless://uuid@example.com:443?type=httpupgrade&security=tls&sni=cdn.example.com&host=cdn.example.com&path=%2Fupgrade" diff --git a/scripts/test-fetch-subscription.py b/scripts/test-fetch-subscription.py index 46c4541..66d6418 100644 --- a/scripts/test-fetch-subscription.py +++ b/scripts/test-fetch-subscription.py @@ -68,6 +68,19 @@ class FetchSubscriptionTests(unittest.TestCase): self.assertRegex(tag, r"^[a-zA-Z0-9_/\-]+$") + def test_non_latin_remark_kept_in_tag(self): + # Flag emoji + Cyrillic remarks must stay distinguishable, not all + # collapse to the "proxy" fallback. + payload = _make_b64_payload( + VLESS_URI + "#\U0001F1E9\U0001F1EA \u0413\u0435\u0440\u043c\u0430\u043d\u0438\u044f", + SS_URI + "#\U0001F1EF\U0001F1F5 \u042f\u043f\u043e\u043d\u0438\u044f", + ) + obs = run_fetcher(payload, tag_prefix="sub") + self.assertEqual( + [ob["tag"] for ob in obs], + ["sub-\u0413\u0435\u0440\u043c\u0430\u043d\u0438\u044f", "sub-\u042f\u043f\u043e\u043d\u0438\u044f"], + ) + def test_tag_deduplication(self): # Two entries with the same remark → distinct tags uri1 = VLESS_URI + "#Server"