basic subscription implementation

This commit is contained in:
FUFSoB committed 2026-04-12 17:41:27 +05:00
1 parent aa5428fc9b
commit 2fb920d812
7 files changed
+1258 -31

No files matched your search

+487
View File
@@ -0,0 +1,487 @@
#!/usr/bin/env python3
"""
Read a subscription URL from stdin, fetch it, decode it, and emit a JSON array
of sing-box outbound objects to stdout.
Usage:
echo "https://example.com/sub" | fetch-subscription.py --tag-prefix my-sub
echo "https://example.com/sub" | fetch-subscription.py --tag-prefix my-sub --routing-mark 2
The subscription endpoint must return either:
- A base64-encoded blob that decodes to newline-separated proxy URIs, or
- Plain newline-separated proxy URIs directly.
Supported URI schemes: vless, vmess, trojan, ss, hysteria2, hy2, tuic,
socks5, socks5h, socks4, socks4a, http, https
"""
import argparse
import base64
import json
import re
import sys
import urllib.parse
import urllib.request
# ---------------------------------------------------------------------------
# Proxy URL parsers (identical to build-outbound.py)
# ---------------------------------------------------------------------------
def _qs(query: str) -> dict:
return dict(urllib.parse.parse_qsl(query))
def parse_vless(url: str, tag: str) -> dict:
rest = url[len("vless://"):]
rest, _, _ = rest.partition("#")
userinfo, _, rest = rest.partition("@")
hostpart, _, query = rest.partition("?")
host, _, port = hostpart.rpartition(":")
params = _qs(query)
ob: dict = {
"type": "vless",
"tag": tag,
"server": host,
"server_port": int(port),
"uuid": userinfo,
"packet_encoding": "xudp",
}
security = params.get("security", "none")
transport = params.get("type", "tcp")
if security == "reality":
ob["tls"] = {
"enabled": True,
"server_name": params.get("sni", host),
"utls": {"enabled": True, "fingerprint": params.get("fp", "chrome")},
"reality": {
"enabled": True,
"public_key": params["pbk"],
"short_id": params.get("sid", ""),
},
}
elif security == "tls":
ob["tls"] = {
"enabled": True,
"server_name": params.get("sni", host),
}
if params.get("fp"):
ob["tls"]["utls"] = {"enabled": True, "fingerprint": params["fp"]}
if params.get("alpn"):
ob["tls"]["alpn"] = params["alpn"].split(",")
if transport == "ws":
ob["transport"] = {
"type": "ws",
"path": urllib.parse.unquote(params.get("path", "/")),
"headers": {"Host": params.get("host", host)},
}
elif transport == "grpc":
ob["transport"] = {
"type": "grpc",
"service_name": urllib.parse.unquote(params.get("serviceName", "")),
}
elif transport == "h2":
ob["transport"] = {
"type": "http",
"host": [params.get("host", host)],
"path": urllib.parse.unquote(params.get("path", "/")),
}
flow = urllib.parse.unquote(params.get("flow", ""))
if flow:
ob["flow"] = flow
return ob
def parse_vmess(url: str, tag: str) -> dict:
b64 = url[len("vmess://"):]
pad = "=" * (-len(b64) % 4)
try:
data = json.loads(base64.b64decode(b64 + pad))
except Exception:
data = json.loads(base64.urlsafe_b64decode(b64 + pad))
host = str(data["add"])
port = int(data["port"])
net = data.get("net", "tcp")
tls_field = str(data.get("tls", ""))
sni = str(data.get("sni") or data.get("host") or host)
ob: dict = {
"type": "vmess",
"tag": tag,
"server": host,
"server_port": port,
"uuid": data["id"],
"security": data.get("scy", "auto"),
"alter_id": int(data.get("aid", 0)),
}
if tls_field in ("tls", "reality"):
ob["tls"] = {"enabled": True, "server_name": sni}
if data.get("fp"):
ob["tls"]["utls"] = {"enabled": True, "fingerprint": str(data["fp"])}
if data.get("alpn"):
ob["tls"]["alpn"] = str(data["alpn"]).split(",")
path = str(data.get("path") or "/")
h_host = str(data.get("host") or host)
if net == "ws":
ob["transport"] = {
"type": "ws",
"path": path,
"headers": {"Host": h_host},
}
elif net == "grpc":
ob["transport"] = {
"type": "grpc",
"service_name": path.lstrip("/"),
}
elif net in ("h2", "http"):
ob["transport"] = {
"type": "http",
"host": [h_host],
"path": path,
}
return ob
def parse_trojan(url: str, tag: str) -> dict:
rest = url[len("trojan://"):]
rest, _, _ = rest.partition("#")
userinfo, _, rest = rest.partition("@")
password = urllib.parse.unquote(userinfo)
hostpart, _, query = rest.partition("?")
host, _, port = hostpart.rpartition(":")
params = _qs(query)
transport = params.get("type", "tcp")
ob: dict = {
"type": "trojan",
"tag": tag,
"server": host,
"server_port": int(port),
"password": password,
"tls": {
"enabled": True,
"server_name": params.get("sni", host),
},
}
if params.get("fp"):
ob["tls"]["utls"] = {"enabled": True, "fingerprint": params["fp"]}
if params.get("alpn"):
ob["tls"]["alpn"] = params["alpn"].split(",")
if transport == "ws":
ob["transport"] = {
"type": "ws",
"path": urllib.parse.unquote(params.get("path", "/")),
"headers": {"Host": params.get("host", host)},
}
elif transport == "grpc":
ob["transport"] = {
"type": "grpc",
"service_name": urllib.parse.unquote(params.get("serviceName", "")),
}
return ob
def parse_shadowsocks(url: str, tag: str) -> dict:
rest = url[len("ss://"):]
rest, _, _ = rest.partition("#")
userinfo, _, rest = rest.partition("@")
hostpart, _, _ = rest.partition("?")
host, _, port = hostpart.rpartition(":")
pad = "=" * (-len(userinfo) % 4)
try:
decoded = base64.urlsafe_b64decode(userinfo + pad).decode()
if ":" not in decoded:
raise ValueError
method, password = decoded.split(":", 1)
except Exception:
plain = urllib.parse.unquote(userinfo)
method, password = plain.split(":", 1)
return {
"type": "shadowsocks",
"tag": tag,
"server": host,
"server_port": int(port),
"method": method,
"password": password,
}
def parse_hysteria2(url: str, tag: str) -> dict:
scheme = "hysteria2" if url.startswith("hysteria2://") else "hy2"
rest = url[len(scheme) + 3:]
rest, _, _ = rest.partition("#")
userinfo, _, rest = rest.partition("@")
hostpart, _, query = rest.partition("?")
host, _, port = hostpart.rpartition(":")
params = _qs(query)
ob: dict = {
"type": "hysteria2",
"tag": tag,
"server": host,
"server_port": int(port),
"password": urllib.parse.unquote(userinfo),
"tls": {
"enabled": True,
"server_name": params.get("sni", host),
"insecure": params.get("insecure", "0") == "1",
},
}
if params.get("obfs") == "salamander":
ob["obfs"] = {"type": "salamander", "password": params.get("obfs-password", "")}
return ob
def parse_tuic(url: str, tag: str) -> dict:
rest = url[len("tuic://"):]
rest, _, _ = rest.partition("#")
userinfo, _, rest = rest.partition("@")
uuid, _, password = userinfo.partition(":")
hostpart, _, query = rest.partition("?")
host, _, port = hostpart.rpartition(":")
params = _qs(query)
alpn_raw = params.get("alpn", "h3")
alpn = [a for a in alpn_raw.split(",") if a]
return {
"type": "tuic",
"tag": tag,
"server": host,
"server_port": int(port),
"uuid": uuid,
"password": urllib.parse.unquote(password),
"congestion_control": params.get("congestion_control", "bbr"),
"udp_relay_mode": params.get("udp_relay_mode", "native"),
"tls": {
"enabled": True,
"server_name": params.get("sni", host),
"alpn": alpn,
},
}
def parse_socks(url: str, tag: str) -> dict:
scheme = url.split("://")[0].lower()
version = "4" if scheme.startswith("socks4") else "5"
rest = url[len(scheme) + 3:]
rest, _, _ = rest.partition("#")
ob: dict = {
"type": "socks",
"tag": tag,
"version": version,
}
if "@" in rest:
userinfo, _, rest = rest.partition("@")
if ":" in userinfo:
username, _, password = userinfo.partition(":")
ob["username"] = urllib.parse.unquote(username)
ob["password"] = urllib.parse.unquote(password)
hostpart = rest.split("?")[0]
host, _, port = hostpart.rpartition(":")
ob["server"] = host
ob["server_port"] = int(port)
return ob
def parse_http_proxy(url: str, tag: str) -> dict:
scheme = url.split("://")[0].lower()
rest = url[len(scheme) + 3:]
rest, _, _ = rest.partition("#")
ob: dict = {
"type": "http",
"tag": tag,
}
if "@" in rest:
userinfo, _, rest = rest.partition("@")
if ":" in userinfo:
username, _, password = userinfo.partition(":")
ob["username"] = urllib.parse.unquote(username)
ob["password"] = urllib.parse.unquote(password)
hostpart = rest.split("?")[0]
host, _, port = hostpart.rpartition(":")
ob["server"] = host
ob["server_port"] = int(port)
if scheme == "https":
ob["tls"] = {"enabled": True, "server_name": host}
return ob
PARSERS = {
"vless": parse_vless,
"vmess": parse_vmess,
"trojan": parse_trojan,
"ss": parse_shadowsocks,
"hysteria2": parse_hysteria2,
"hy2": parse_hysteria2,
"tuic": parse_tuic,
"socks5": parse_socks,
"socks5h": parse_socks,
"socks4": parse_socks,
"socks4a": parse_socks,
"http": parse_http_proxy,
"https": parse_http_proxy,
}
# ---------------------------------------------------------------------------
# Subscription fetching & parsing
# ---------------------------------------------------------------------------
def fetch_raw(url: str) -> bytes:
req = urllib.request.Request(
url,
headers={"User-Agent": "v2rayN/6.0"},
)
with urllib.request.urlopen(req, timeout=30) as resp:
return resp.read()
def decode_subscription(data: bytes) -> list[str]:
"""
Return a list of proxy URI strings from a raw subscription response.
Tries base64 decode first (standard v2rayN format), falls back to UTF-8 plain text.
"""
# Standard format: response is base64-encoded, decodes to newline-separated URIs.
text = None
stripped = data.strip()
try:
# Pad to a multiple of 4 before decoding.
pad = b"=" * (-len(stripped) % 4)
decoded = base64.b64decode(stripped + pad).decode("utf-8")
# Sanity-check: decoded content should contain at least one known scheme.
if any(f"{scheme}://" in decoded for scheme in PARSERS):
text = decoded
except Exception:
pass
if text is None:
text = data.decode("utf-8", errors="replace")
return [line.strip() for line in text.splitlines() if line.strip()]
def slugify(remark: str) -> str:
"""Convert a free-form remark into a tag-safe slug (max 60 chars)."""
slug = re.sub(r"[^a-zA-Z0-9_-]", "-", remark)
slug = re.sub(r"-{2,}", "-", slug).strip("-")
return slug[:60] or "proxy"
def make_tag(prefix: str, remark: str, index: int) -> str:
if remark:
slug = slugify(urllib.parse.unquote(remark))
return f"{prefix}-{slug}"
return f"{prefix}-{index}"
def parse_subscription(lines: list[str], tag_prefix: str, routing_mark: int | None) -> list[dict]:
outbounds = []
seen_tags: set[str] = set()
for i, line in enumerate(lines):
scheme = line.split("://")[0].lower()
if scheme not in PARSERS:
continue
# Extract remark from the #fragment at the end of the URI.
remark = ""
if "#" in line:
remark = line.split("#", 1)[1]
base_tag = make_tag(tag_prefix, remark, i)
# Deduplicate: append -<index> until unique.
tag = base_tag
if tag in seen_tags:
n = 2
while f"{base_tag}-{n}" in seen_tags:
n += 1
tag = f"{base_tag}-{n}"
seen_tags.add(tag)
try:
ob = PARSERS[scheme](line, tag)
except Exception as exc:
print(f"warning: skipping entry {i} ({scheme}): {exc}", file=sys.stderr)
continue
if routing_mark is not None:
ob["routing_mark"] = routing_mark
outbounds.append(ob)
return outbounds
# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------
def main() -> None:
ap = argparse.ArgumentParser(
description="Fetch a proxy subscription URL from stdin and emit a sing-box outbound JSON array."
)
ap.add_argument("--tag-prefix", required=True, dest="tag_prefix",
help="Prefix for outbound tags, e.g. 'my-sub'.")
ap.add_argument("--routing-mark", type=int, default=None, dest="routing_mark")
args = ap.parse_args()
url = sys.stdin.read().strip()
if not url:
print("error: no URL provided on stdin", file=sys.stderr)
sys.exit(1)
try:
raw = fetch_raw(url)
except Exception as exc:
print(f"error: failed to fetch subscription: {exc}", file=sys.stderr)
sys.exit(1)
lines = decode_subscription(raw)
outbounds = parse_subscription(lines, args.tag_prefix, args.routing_mark)
if not outbounds:
print("error: subscription contained no parseable proxy URIs", file=sys.stderr)
sys.exit(1)
print(json.dumps(outbounds))
if __name__ == "__main__":
main()
+180
View File
@@ -0,0 +1,180 @@
#!/usr/bin/env python3
import base64
import json
import os
import subprocess
import sys
import threading
import time
import unittest
from http.server import BaseHTTPRequestHandler, HTTPServer
from pathlib import Path
SCRIPT = Path(os.environ.get("FETCH_SUBSCRIPTION_SCRIPT", Path(__file__).with_name("fetch-subscription.py")))
# ---------------------------------------------------------------------------
# Tiny embedded HTTP server for test fixtures
# ---------------------------------------------------------------------------
class _FixtureHandler(BaseHTTPRequestHandler):
def do_GET(self):
body = self.server.response_data
self.send_response(200)
self.send_header("Content-Type", "text/plain")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *args):
pass # silence access log during tests
def _start_server(data: bytes):
"""Start an ephemeral HTTP server on a random port. Returns (server, port)."""
srv = HTTPServer(("127.0.0.1", 0), _FixtureHandler)
srv.response_data = data
thread = threading.Thread(target=srv.serve_forever, daemon=True)
thread.start()
# Give the server a moment to enter its accept loop.
time.sleep(0.05)
return srv, srv.server_address[1]
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
VLESS_URI = "vless://uuid@example.com:443?security=reality&pbk=pubkey&fp=chrome&sni=cdn.example.com&sid=abcd"
SS_URI = "ss://{}@ss.example.com:8388".format(
base64.urlsafe_b64encode(b"chacha20-ietf-poly1305:passw0rd").decode().rstrip("=")
)
HY2_URI = "hy2://secret@hy.example.com:443?sni=hy.example.com"
INVALID_URI = "wireguard://example.com:51820"
def _make_b64_payload(*uris: str) -> bytes:
text = "\n".join(uris)
return base64.b64encode(text.encode())
def run_fetcher(server_data: bytes, tag_prefix: str = "test", *, expect_ok: bool = True, extra_args: list = None):
srv, port = _start_server(server_data)
url = f"http://127.0.0.1:{port}/sub"
env = dict(os.environ, PYTHONDONTWRITEBYTECODE="1")
cmd = [sys.executable, str(SCRIPT), "--tag-prefix", tag_prefix] + (extra_args or [])
proc = subprocess.run(
cmd,
input=url,
text=True,
capture_output=True,
check=False,
env=env,
)
srv.shutdown()
srv.server_close()
if expect_ok:
if proc.returncode != 0:
raise AssertionError(f"Expected success, got:\n{proc.stderr}")
return json.loads(proc.stdout)
return proc
# ---------------------------------------------------------------------------
# Tests
# ---------------------------------------------------------------------------
class FetchSubscriptionTests(unittest.TestCase):
def test_base64_payload_mixed_protocols(self):
payload = _make_b64_payload(VLESS_URI, SS_URI, HY2_URI)
obs = run_fetcher(payload)
self.assertEqual(len(obs), 3)
types = {ob["type"] for ob in obs}
self.assertEqual(types, {"vless", "shadowsocks", "hysteria2"})
def test_plain_text_payload(self):
payload = "\n".join([VLESS_URI, SS_URI]).encode()
obs = run_fetcher(payload)
self.assertEqual(len(obs), 2)
def test_tag_prefix_applied(self):
payload = _make_b64_payload(VLESS_URI)
obs = run_fetcher(payload, tag_prefix="mysub")
self.assertTrue(obs[0]["tag"].startswith("mysub-"))
def test_remark_used_in_tag(self):
uri_with_remark = VLESS_URI + "#My Server DE"
payload = _make_b64_payload(uri_with_remark)
obs = run_fetcher(payload, tag_prefix="sub")
# Remark should be slugified and appear in tag
self.assertIn("My-Server-DE", obs[0]["tag"])
def test_remark_special_chars_slugified(self):
uri_with_remark = VLESS_URI + "#Server @ 🇩🇪 #1"
payload = _make_b64_payload(uri_with_remark)
obs = run_fetcher(payload, tag_prefix="sub")
tag = obs[0]["tag"]
# Tag must contain only safe characters
import re
self.assertRegex(tag, r"^[a-zA-Z0-9_/\-]+$")
def test_tag_deduplication(self):
# Two entries with the same remark → distinct tags
uri1 = VLESS_URI + "#Server"
uri2 = SS_URI + "#Server"
payload = _make_b64_payload(uri1, uri2)
obs = run_fetcher(payload, tag_prefix="sub")
tags = [ob["tag"] for ob in obs]
self.assertEqual(len(tags), len(set(tags)), "Tags must be unique")
def test_invalid_lines_skipped(self):
payload = _make_b64_payload(INVALID_URI, VLESS_URI)
obs = run_fetcher(payload)
self.assertEqual(len(obs), 1)
self.assertEqual(obs[0]["type"], "vless")
def test_invalid_lines_warn_on_stderr(self):
# A syntactically invalid URI for a known scheme should warn, not crash.
broken_vless = "vless://not-a-valid-vless-url"
payload = _make_b64_payload(broken_vless, SS_URI)
obs = run_fetcher(payload)
self.assertEqual(len(obs), 1)
def test_routing_mark_applied(self):
payload = _make_b64_payload(VLESS_URI, SS_URI)
obs = run_fetcher(payload, extra_args=["--routing-mark", "2"])
for ob in obs:
self.assertEqual(ob["routing_mark"], 2)
def test_all_invalid_fails(self):
payload = _make_b64_payload(INVALID_URI, "not-a-uri-at-all")
proc = run_fetcher(payload, expect_ok=False)
self.assertNotEqual(proc.returncode, 0)
self.assertIn("no parseable proxy URIs", proc.stderr)
def test_index_tag_fallback_when_no_remark(self):
# URIs without a remark should get index-based tags
payload = _make_b64_payload(VLESS_URI, SS_URI)
obs = run_fetcher(payload, tag_prefix="sub")
for ob in obs:
# Tags follow the pattern sub-<index>
self.assertRegex(ob["tag"], r"^sub-\d+$")
def test_empty_lines_ignored(self):
text = f"\n\n{VLESS_URI}\n\n{SS_URI}\n\n"
payload = base64.b64encode(text.encode())
obs = run_fetcher(payload)
self.assertEqual(len(obs), 2)
def test_trailing_whitespace_in_uris(self):
text = f"{VLESS_URI} \r\n{SS_URI} \r\n"
payload = base64.b64encode(text.encode())
obs = run_fetcher(payload)
self.assertEqual(len(obs), 2)
if __name__ == "__main__":
unittest.main()