ps-core::links ports upstream's proxy_url_parsers.py and proxy_parsing.py: every scheme, each backend's refusals, XRay rendering, subscription decoding, tags and the server checks. Upstream's build-outbound tests are ported case for case, and tools/parity/links.py runs ~750 links through both implementations: no differences. config::privileged_changes names the edits only an administrator may make: anything that runs a program, passes arguments through, or names a local file, since the service runs as LocalSystem. Names that become paths or service names are validated. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
110 lines
5.5 KiB
Python
110 lines
5.5 KiB
Python
#!/usr/bin/env python3
|
|
"""Parity check: upstream's link parsers (scripts/proxy_parsing.py) against ps-core's.
|
|
|
|
Feeds the same links to both and reports every link where one accepts and the other
|
|
refuses, or both accept with different outbounds. Run from windows/:
|
|
python3 -I tools/parity/links.py
|
|
"""
|
|
|
|
import base64
|
|
import json
|
|
import random
|
|
import re
|
|
import subprocess
|
|
import sys
|
|
import urllib.parse
|
|
from pathlib import Path
|
|
|
|
ROOT = Path(__file__).resolve().parents[3]
|
|
sys.path.insert(0, str(ROOT / "scripts"))
|
|
from proxy_parsing import build_outbound # noqa: E402
|
|
|
|
PBK = "SbVKOEMjK0sIlbwg4akyBg5mL5KZwwB-ed4eEE7YnRc"
|
|
|
|
|
|
def corpus():
|
|
links = set()
|
|
# Every link literal in upstream's tests.
|
|
for name in ("test-build-outbound.py", "test-fetch-subscription.py"):
|
|
text = (ROOT / "scripts" / name).read_text()
|
|
links.update(re.findall(r'"((?:vless|vmess|trojan|ss|hy2|hysteria2|tuic|anytls|naive\+https|naive\+quic|socks[45]h?a?|https?)://[^"]*)"', text))
|
|
# VMess bodies, which the tests build in code.
|
|
for extra in (
|
|
{}, {"net": "ws", "path": "/ws", "host": "cdn.example.com", "tls": "tls"}, {"scy": ""}, {"aid": "7"},
|
|
{"aid": 70000}, {"net": "grpc", "path": "/svc"}, {"net": "http", "tls": "tls", "alpn": "h2,http/1.1"},
|
|
{"port": "0"}, {"port": 443.5}, {"add": "[2001:db8::1]"}, {"fp": "firefox", "tls": "tls"}, {"id": 5},
|
|
{"scy": "zero"}, {"net": "kcp"}, {"tls": "reality", "sni": "a.example.com"},
|
|
):
|
|
body = {"add": "example.com", "port": 443, "id": "00000000-0000-0000-0000-000000000000", "net": "tcp", **extra}
|
|
raw = json.dumps(body).encode()
|
|
links.add("vmess://" + base64.b64encode(raw).decode())
|
|
links.add("vmess://" + base64.urlsafe_b64encode(raw).decode().rstrip("=") + "#Remark")
|
|
# Shadowsocks in its three shapes.
|
|
for method, pw in (("aes-256-gcm", "pw"), ("chacha20-ietf-poly1305", "p@ss:w"), ("2022-blake3-aes-128-gcm", base64.b64encode(b"k" * 16).decode()), ("none", "")):
|
|
cred = f"{method}:{pw}".encode()
|
|
links.add(f"ss://{base64.urlsafe_b64encode(cred).decode().rstrip('=')}@ss.example.com:8388#n")
|
|
links.add(f"ss://{urllib.parse.quote(method)}:{urllib.parse.quote(pw)}@ss.example.com:8388")
|
|
links.add(f"ss://{base64.urlsafe_b64encode(cred + b'@[2001:db8::1]:8388').decode().rstrip('=')}#legacy")
|
|
# Mutations of a few rich links: drop, blank or duplicate parameters, change case.
|
|
rng = random.Random(1)
|
|
seeds = [
|
|
f"vless://uuid@example.com:443?type=ws&security=tls&sni=a.example.com&host=h.example.com&path=%2Fp&fp=chrome&alpn=h2,http/1.1&flow=xtls-rprx-vision",
|
|
f"vless://uuid@example.com:443?type=tcp&security=reality&pbk={PBK}&sid=ab12&fp=qq&sni=last.fm&spx=%2Fx",
|
|
"vless://uuid@example.com:443?type=xhttp&security=tls&mode=packet-up&host=h.example.com&path=%2Fx&x_padding_bytes=100-1000",
|
|
"trojan://p%40ss@example.com:443?type=grpc&serviceName=svc&sni=s.example.com&fp=firefox",
|
|
"hy2://pw@example.com:443?sni=s.example.com&obfs=salamander&obfs-password=m&mport=20000-30000&insecure=0",
|
|
"tuic://00000000-0000-0000-0000-000000000000:pw@example.com:443?sni=s.example.com&alpn=h3&congestion_control=cubic&udp_relay_mode=quic",
|
|
"anytls://pw@example.com:443?peer=p.example.com&allowInsecure=1&fp=edge",
|
|
"socks5://u%20x:p%3Aw@[2001:db8::2]:1080",
|
|
]
|
|
for seed in seeds:
|
|
links.add(seed)
|
|
base, _, query = seed.partition("?")
|
|
params = query.split("&") if query else []
|
|
for _ in range(60):
|
|
p = list(params)
|
|
op = rng.randrange(5)
|
|
if p and op == 0:
|
|
p.pop(rng.randrange(len(p)))
|
|
elif p and op == 1:
|
|
i = rng.randrange(len(p))
|
|
p[i] = p[i].split("=", 1)[0] + "="
|
|
elif p and op == 2:
|
|
p.append(rng.choice(p))
|
|
elif op == 3:
|
|
p.append(rng.choice(["type=h2", "type=quic", "type=httpupgrade", "security=none", "fp=random", "fp=unsafe", "ech=udp%3A%2F%2F1.1.1.1", "mode=bogus", "flow=", "sid=zz", "alpn=%5B%22h2%22%5D", "insecure=1", "pinSHA256=" + "ab" * 32]))
|
|
else:
|
|
base = base.upper() if rng.random() < 0.2 else base
|
|
links.add(base + ("?" + "&".join(p) if p else ""))
|
|
return sorted(links)
|
|
|
|
|
|
def main():
|
|
requests = [
|
|
{"url": url, "tag": "t", "backend": backend}
|
|
for url in corpus()
|
|
for backend in ("sing-box", "xray")
|
|
]
|
|
rust = subprocess.run(
|
|
["cargo", "run", "-q", "-p", "ps-core", "--example", "links_json"],
|
|
input="\n".join(json.dumps(r) for r in requests) + "\n",
|
|
capture_output=True, text=True, check=True, cwd=ROOT / "windows",
|
|
).stdout.splitlines()
|
|
mismatches = 0
|
|
for req, line in zip(requests, rust):
|
|
got = json.loads(line)
|
|
try:
|
|
want = {"ok": build_outbound(req["url"], req["tag"], backend=req["backend"])}
|
|
except Exception as exc: # noqa: BLE001 - every refusal counts
|
|
want = {"error": str(exc)}
|
|
if ("ok" in got) != ("ok" in want) or ("ok" in got and got["ok"] != want["ok"]):
|
|
mismatches += 1
|
|
print(f"MISMATCH {req['backend']} {req['url']}\n python: {json.dumps(want)[:300]}\n rust: {json.dumps(got)[:300]}")
|
|
accepted = sum("ok" in json.loads(line) for line in rust)
|
|
print(f"{len(requests)} cases ({accepted} accepted, {len(requests) - accepted} refused), {mismatches} mismatches")
|
|
sys.exit(1 if mismatches else 0)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|