another round of refactoring
This commit is contained in:
23 files changed
+1362
-1090
No files matched your search
+11
-23
@@ -1,18 +1,11 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Read a proxy URL from stdin, emit a sing-box outbound JSON object to stdout.
|
||||
|
||||
Usage:
|
||||
echo "vless://..." | build-outbound.py --tag my-server [--routing-mark 2]
|
||||
|
||||
Supported schemes: vless, vmess, trojan, ss, hysteria2, hy2, tuic,
|
||||
socks5, socks5h, socks4, socks4a, http, https
|
||||
"""
|
||||
"""Read a proxy URL from stdin and emit a sing-box outbound JSON object."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
from proxy_url_parsers import PARSERS
|
||||
|
||||
from proxy_parsing import build_outbound
|
||||
|
||||
|
||||
def main() -> None:
|
||||
@@ -24,22 +17,17 @@ def main() -> None:
|
||||
args = ap.parse_args()
|
||||
|
||||
url = sys.stdin.read().strip()
|
||||
scheme = url.split("://")[0].lower()
|
||||
|
||||
if scheme not in PARSERS:
|
||||
print(f"error: unsupported scheme '{scheme}'", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
try:
|
||||
ob = PARSERS[scheme](url, args.tag)
|
||||
except Exception as e:
|
||||
print(f"error: failed to parse {scheme} URL: {e}", file=sys.stderr)
|
||||
outbound = build_outbound(url, args.tag, args.routing_mark)
|
||||
except ValueError as exc:
|
||||
print(f"error: {exc}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
except Exception as exc:
|
||||
scheme = url.split("://", 1)[0].lower()
|
||||
print(f"error: failed to parse {scheme} URL: {exc}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
if args.routing_mark is not None:
|
||||
ob["routing_mark"] = args.routing_mark
|
||||
|
||||
print(json.dumps(ob))
|
||||
print(json.dumps(outbound))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -1,119 +1,11 @@
|
||||
#!/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
|
||||
"""
|
||||
"""Read a subscription URL from stdin and emit a JSON array of outbounds."""
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
from proxy_url_parsers import PARSERS
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 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
|
||||
from proxy_parsing import decode_subscription, fetch_raw, parse_subscription
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import base64
|
||||
import re
|
||||
import sys
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
from proxy_url_parsers import PARSERS
|
||||
|
||||
|
||||
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:
|
||||
scheme = detect_scheme(url)
|
||||
if scheme not in PARSERS:
|
||||
raise ValueError(f"unsupported scheme '{scheme}'")
|
||||
|
||||
outbound = PARSERS[scheme](url, tag)
|
||||
if routing_mark is not None:
|
||||
outbound["routing_mark"] = routing_mark
|
||||
return outbound
|
||||
|
||||
|
||||
def fetch_raw(url: str) -> bytes:
|
||||
request = urllib.request.Request(
|
||||
url,
|
||||
headers={"User-Agent": "v2rayN/6.0"},
|
||||
)
|
||||
with urllib.request.urlopen(request, timeout=30) as response:
|
||||
return response.read()
|
||||
|
||||
|
||||
def decode_subscription(data: bytes) -> list[str]:
|
||||
text = None
|
||||
stripped = data.strip()
|
||||
try:
|
||||
pad = b"=" * (-len(stripped) % 4)
|
||||
decoded = base64.b64decode(stripped + pad).decode("utf-8")
|
||||
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_tag(remark: str) -> str:
|
||||
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:
|
||||
return f"{prefix}-{slugify_tag(urllib.parse.unquote(remark))}"
|
||||
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 index, line in enumerate(lines):
|
||||
scheme = detect_scheme(line)
|
||||
if scheme not in PARSERS:
|
||||
continue
|
||||
|
||||
remark = line.split("#", 1)[1] if "#" in line else ""
|
||||
base_tag = make_tag(tag_prefix, remark, index)
|
||||
tag = base_tag
|
||||
|
||||
if tag in seen_tags:
|
||||
suffix = 2
|
||||
while f"{base_tag}-{suffix}" in seen_tags:
|
||||
suffix += 1
|
||||
tag = f"{base_tag}-{suffix}"
|
||||
|
||||
try:
|
||||
outbound = build_outbound(line, tag, routing_mark)
|
||||
except Exception as exc:
|
||||
print(f"warning: skipping entry {index} ({scheme}): {exc}", file=sys.stderr)
|
||||
continue
|
||||
|
||||
seen_tags.add(tag)
|
||||
outbounds.append(outbound)
|
||||
|
||||
return outbounds
|
||||
@@ -2,32 +2,13 @@
|
||||
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from proxy_parsing import build_outbound
|
||||
|
||||
|
||||
SCRIPT = Path(os.environ.get("BUILD_OUTBOUND_SCRIPT", Path(__file__).with_name("build-outbound.py")))
|
||||
|
||||
|
||||
def run_parser(url: str, *, expect_ok: bool = True):
|
||||
env = dict(os.environ)
|
||||
env["PYTHONDONTWRITEBYTECODE"] = "1"
|
||||
proc = subprocess.run(
|
||||
[sys.executable, str(SCRIPT), "--tag", "test-outbound"],
|
||||
input=url,
|
||||
text=True,
|
||||
capture_output=True,
|
||||
check=False,
|
||||
env=env,
|
||||
)
|
||||
if expect_ok:
|
||||
if proc.returncode != 0:
|
||||
raise AssertionError(proc.stderr)
|
||||
return json.loads(proc.stdout)
|
||||
return proc
|
||||
def run_parser(url: str):
|
||||
return build_outbound(url, "test-outbound")
|
||||
|
||||
|
||||
class BuildOutboundTests(unittest.TestCase):
|
||||
@@ -97,9 +78,8 @@ class BuildOutboundTests(unittest.TestCase):
|
||||
self.assertEqual(ob["tls"]["server_name"], "proxy.example.com")
|
||||
|
||||
def test_invalid_scheme_fails(self):
|
||||
proc = run_parser("wireguard://example.com", expect_ok=False)
|
||||
self.assertNotEqual(proc.returncode, 0)
|
||||
self.assertIn("unsupported scheme", proc.stderr)
|
||||
with self.assertRaisesRegex(ValueError, "unsupported scheme"):
|
||||
run_parser("wireguard://example.com")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -1,51 +1,8 @@
|
||||
#!/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
|
||||
# ---------------------------------------------------------------------------
|
||||
from proxy_parsing import decode_subscription, parse_subscription
|
||||
|
||||
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(
|
||||
@@ -60,26 +17,9 @@ def _make_b64_payload(*uris: str) -> bytes:
|
||||
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
|
||||
def run_fetcher(server_data: bytes, tag_prefix: str = "test", *, routing_mark: int | None = None):
|
||||
lines = decode_subscription(server_data)
|
||||
return parse_subscription(lines, tag_prefix, routing_mark)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -145,15 +85,13 @@ class FetchSubscriptionTests(unittest.TestCase):
|
||||
|
||||
def test_routing_mark_applied(self):
|
||||
payload = _make_b64_payload(VLESS_URI, SS_URI)
|
||||
obs = run_fetcher(payload, extra_args=["--routing-mark", "2"])
|
||||
obs = run_fetcher(payload, 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)
|
||||
self.assertEqual(run_fetcher(payload), [])
|
||||
|
||||
def test_index_tag_fallback_when_no_remark(self):
|
||||
# URIs without a remark should get index-based tags
|
||||
|
||||
Reference in new issue
Block a user