feat: json exports/imports

This commit is contained in:
fufsob committed 2026-09-15 04:53:39 +00:00
1 parent d7108abf0c
commit aa19042ee5
18 files changed
+778 -42

No files matched your search

+9 -2
View File
@@ -20,6 +20,9 @@ def main() -> None:
)
ap.add_argument("--backend", choices=["sing-box", "xray", "hybrid"], default="sing-box")
ap.add_argument("--routing-mark", type=int, default=None, dest="routing_mark")
ap.add_argument(
"--links-out", default=None, dest="links_out", help="Also write {tag: original URI} here, for sharing."
)
args = ap.parse_args()
url = sys.stdin.read().strip()
@@ -34,17 +37,21 @@ def main() -> None:
sys.exit(1)
lines = decode_subscription(raw)
links: dict[str, str] = {}
if args.backend == "hybrid":
outbounds = parse_hybrid_subscription(lines, args.tag_prefix, args.routing_mark)
outbounds = parse_hybrid_subscription(lines, args.tag_prefix, args.routing_mark, links)
has_outbounds = bool(outbounds["singBox"] or outbounds["xray"])
else:
outbounds = parse_subscription(lines, args.tag_prefix, args.routing_mark, args.backend)
outbounds = parse_subscription(lines, args.tag_prefix, args.routing_mark, args.backend, links)
has_outbounds = bool(outbounds)
if not has_outbounds:
print("error: subscription contained no parseable proxy URIs", file=sys.stderr)
sys.exit(1)
if args.links_out:
with open(args.links_out, "w", encoding="utf-8") as handle:
json.dump(links, handle)
print(json.dumps(outbounds))
+14
View File
@@ -13,6 +13,8 @@ import hashlib
import json
import urllib.parse
from proxy_parsing import build_outbound
UUID_TYPES = ("vless", "vmess")
PASSWORD_TYPES = ("trojan", "shadowsocks", "socks", "http")
UDP_TYPES = ("shadowsocks", "socks")
@@ -313,6 +315,17 @@ def build_listener(listener: dict, server_address: str, share_links: bool) -> di
return {"tag": tag, "type": listener["type"], "port": _share_port(listener), "inbound": inbound, "links": links}
def client_outbound(link: str, tag: str) -> dict | None:
"""What a client dials for this link: sing-box JSON, or XRay's where sing-box has
no such transport (XHTTP, ECH). None when neither parser reads the link (socks://)."""
for backend in ("sing-box", "xray"):
try:
return build_outbound(link, tag, backend=backend)
except ValueError:
pass
return None
def subscription_token(name: str, secrets: list[str]) -> str:
"""Name of a user's subscription file, and so the secret part of its URL.
@@ -348,6 +361,7 @@ def build_inbounds(spec: dict, server_address: str) -> dict:
"type": rendered.get("type", ""),
"port": rendered.get("port", 0),
"link": link,
"outbound": client_outbound(link, rendered["tag"]),
}
)
entry = by_user.setdefault(name, {"links": [], "secrets": []})
+13 -2
View File
@@ -276,8 +276,13 @@ def _subscription_tag(line: str, tag_prefix: str, index: int, seen_tags: set[str
def parse_subscription(
lines: list[str], tag_prefix: str, routing_mark: int | None, backend: str = "sing-box"
lines: list[str],
tag_prefix: str,
routing_mark: int | None,
backend: str = "sing-box",
links: dict[str, str] | None = None,
) -> list[dict]:
"""links, when given, collects tag -> the line it came from, to share it back."""
outbounds = []
seen_tags: set[str] = set()
@@ -296,12 +301,14 @@ def parse_subscription(
seen_tags.add(tag)
outbounds.append(outbound)
if links is not None:
links[tag] = line
return outbounds
def parse_hybrid_subscription(
lines: list[str], tag_prefix: str, routing_mark: int | None = None
lines: list[str], tag_prefix: str, routing_mark: int | None = None, links: dict[str, str] | None = None
) -> dict[str, list[dict]]:
outbounds: dict[str, list[dict]] = {"singBox": [], "xray": []}
seen_tags: set[str] = set()
@@ -317,6 +324,8 @@ def parse_hybrid_subscription(
outbound = build_outbound(line, tag, routing_mark, "sing-box")
outbounds["singBox"].append(outbound)
seen_tags.add(tag)
if links is not None:
links[tag] = line
continue
except Exception as sing_box_exc:
sing_box_error = sing_box_exc
@@ -333,5 +342,7 @@ def parse_hybrid_subscription(
outbounds["xray"].append(outbound)
seen_tags.add(tag)
if links is not None:
links[tag] = line
return outbounds
+11 -1
View File
@@ -7,7 +7,7 @@ import tempfile
import unittest
import urllib.parse
from proxy_inbound import build_inbounds, build_share_link, render_xray_inbound, subscription_token
from proxy_inbound import build_inbounds, build_share_link, client_outbound, render_xray_inbound, subscription_token
from proxy_parsing import build_outbound
@@ -357,6 +357,16 @@ class BuildInboundsTests(unittest.TestCase):
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)
self.assertEqual(result["links"][0]["outbound"]["type"], "vless")
# v2rayN's socks:// is a link, but not one the outbound parsers take.
self.assertIsNone(result["links"][1]["outbound"])
def test_client_outbound_falls_back_to_xray(self):
link = build_share_link(
listener(transport={"type": "xhttp", "path": "/p", "host": None, "mode": "auto", "serviceName": ""}),
"vpn.example.com",
)
self.assertEqual(client_outbound(link, "x")["protocol"], "vless")
def test_xhttp_mode_reaches_the_inbound_and_the_link(self):
spec = listener(
+9
View File
@@ -61,6 +61,15 @@ class FetchSubscriptionTests(unittest.TestCase):
obs = run_fetcher(payload, tag_prefix="mysub")
self.assertTrue(obs[0]["tag"].startswith("mysub-"))
def test_links_map_tags_to_lines(self):
lines = [VLESS_URI, INVALID_URI, VLESS_XHTTP_URI]
links: dict[str, str] = {}
obs = parse_subscription(lines, "sub", None, "sing-box", links)
self.assertEqual(links, {obs[0]["tag"]: VLESS_URI})
links = {}
hybrid = parse_hybrid_subscription(lines, "sub", None, links)
self.assertEqual(links, {hybrid["singBox"][0]["tag"]: VLESS_URI, hybrid["xray"][0]["tag"]: VLESS_XHTTP_URI})
def test_remark_used_in_tag(self):
uri_with_remark = VLESS_URI + "#My Server DE"
payload = _make_b64_payload(uri_with_remark)