"""Find V2Ray configs that actually work with OpenCode from this machine. OpenCode blocks/flags some exit IPs (403 / 429). This tool downloads the subscription sources, tests every config against the real OpenCode endpoint through sing-box, and writes the ones that answer 200 to a txt file you can import into any client. Usage: python find_opencode_configs.py # full run python find_opencode_configs.py --limit 40 # quick test python find_opencode_configs.py --workers 24 Requires sing-box.exe (auto-detected from PattN, or set SING_BOX env var). """ import argparse import base64 import concurrent.futures as futures import json import os import re import socket import subprocess import sys import tempfile import time import urllib.parse as up import urllib.request from urllib.error import HTTPError, URLError TEST_URL = "https://opencode.ai/zen/v1/models" FALLBACK_URL = "https://models.opencode.ai/api.json" PORT_BASE = 22100 PROBE_TIMEOUT = 10 HERE = os.path.dirname(os.path.abspath(__file__)) SB_CANDIDATES = [ os.environ.get("SING_BOX", ""), os.path.join(HERE, "sing-box.exe"), r"C:\Users\F.Naghibi\Downloads\PattN-windows-64\bin\sing_box\sing-box.exe", r"C:\Program Files\sing-box\sing-box.exe", ] UTLS_FP = {"chrome", "firefox", "safari", "ios", "android", "edge", "360", "qq", "random", "randomized"} def find_sing_box(): for c in SB_CANDIDATES: if c and os.path.isfile(c): return c raise SystemExit("sing-box.exe not found. Put it next to this script or set SING_BOX.") def fetch(url, timeout=40): req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"}) with urllib.request.urlopen(req, timeout=timeout) as r: return r.read().decode("utf-8", "replace") def b64d(s): s = s.strip().replace("-", "+").replace("_", "/") s += "=" * (-len(s) % 4) try: return base64.b64decode(s).decode("utf-8", "replace") except Exception: # noqa: BLE001 return "" def tls_block(p, host): sec = (p.get("security") or "none").lower() if sec not in ("tls", "reality"): return None t = {"enabled": True} sni = p.get("sni") or p.get("peer") or (p.get("host") if p.get("type") in ("ws", "httpupgrade") else "") if sni: t["server_name"] = sni if p.get("alpn"): alpn = [a.strip() for a in up.unquote(p["alpn"]).split(",") if a.strip()] if alpn: t["alpn"] = alpn fp = (p.get("fp") or "").lower() if fp in UTLS_FP: t["utls"] = {"enabled": True, "fingerprint": fp} ech = (p.get("ech") or "").strip() if ech: # "cloudflare-ech.com+udp://1.1.1.1" -> ask DNS for the ECHConfigList qsn = re.split(r"[+\s]", ech)[0].strip() if qsn and re.match(r"^[A-Za-z0-9._-]+$", qsn): t["ech"] = {"enabled": True, "query_server_name": qsn} if sec == "reality": if not p.get("pbk"): return None t["reality"] = {"enabled": True, "public_key": p["pbk"], "short_id": p.get("sid", "")} t.setdefault("utls", {"enabled": True, "fingerprint": "chrome"}) return t def transport_block(p): net = (p.get("type") or "tcp").lower() host = p.get("host", "") or "" path = p.get("path") or "/" if net in ("tcp", "raw"): return None if net == "ws": if not path.startswith("/"): path = "/" + path t = {"type": "ws", "path": path} if host: t["headers"] = {"Host": host} return t if net == "grpc": return {"type": "grpc", "service_name": p.get("serviceName") or path.lstrip("/")} if net == "httpupgrade": t = {"type": "httpupgrade", "path": path} if host: t["host"] = host return t return None def parse_link(link): link = link.strip() if not link or link.startswith("#"): return None try: if link.startswith("vless://"): u = up.urlsplit(link) p = {k: v[0] for k, v in up.parse_qs(u.query).items()} if not u.hostname or not u.port: return None ob = {"type": "vless", "server": u.hostname, "server_port": u.port, "uuid": up.unquote(u.username or "")} if not ob["uuid"]: return None if p.get("flow"): ob["flow"] = p["flow"] t = tls_block(p, u.hostname) if t: ob["tls"] = t tr = transport_block(p) if tr: ob["transport"] = tr return ob if link.startswith("trojan://"): u = up.urlsplit(link) p = {k: v[0] for k, v in up.parse_qs(u.query).items()} if not u.hostname or not u.port: return None p.setdefault("security", "tls") ob = {"type": "trojan", "server": u.hostname, "server_port": u.port, "password": up.unquote(u.username or "")} t = tls_block(p, u.hostname) if t: ob["tls"] = t tr = transport_block(p) if tr: ob["transport"] = tr return ob if link.startswith("vmess://"): raw = b64d(link[8:]) j = json.loads(raw) host = j.get("add") port = int(j.get("port") or 0) if not host or not port: return None ob = {"type": "vmess", "server": host, "server_port": port, "uuid": j.get("id"), "security": j.get("scy") or "auto", "alter_id": int(j.get("aid") or 0)} net = (j.get("net") or "tcp").lower() tls = str(j.get("tls") or "").lower() == "tls" if tls: t = {"enabled": True} if j.get("sni"): t["server_name"] = j["sni"] if j.get("alpn"): t["alpn"] = [a for a in str(j["alpn"]).split(",") if a] if str(j.get("fp") or "").lower() in UTLS_FP: t["utls"] = {"enabled": True, "fingerprint": str(j["fp"]).lower()} ob["tls"] = t if net == "ws": path = j.get("path") or "/" tr = {"type": "ws", "path": path if path.startswith("/") else "/" + path} if j.get("host"): tr["headers"] = {"Host": j["host"]} ob["transport"] = tr elif net == "grpc": ob["transport"] = {"type": "grpc", "service_name": j.get("path") or ""} return ob if link.startswith("ss://"): body = link[5:].split("#")[0] if "@" not in body: decoded = b64d(body) if "@" not in decoded: return None body = decoded cred, hostport = body.rsplit("@", 1) if ":" not in cred: cred = b64d(cred) method, password = cred.split(":", 1) host, port = hostport.rsplit(":", 1) return {"type": "shadowsocks", "server": host, "server_port": int(port), "method": method, "password": password} except Exception: # noqa: BLE001 return None return None def free_port_start(): for base in (22100, 23100, 24100, 25100): ok = True for i in range(0, 40): s = socket.socket() try: s.bind(("127.0.0.1", base + i)) except OSError: ok = False finally: s.close() if not ok: break if ok: return base raise SystemExit("no free port range") def build_config(items, base_port): inbounds, outbounds, rules = [], [{"type": "direct", "tag": "direct"}], [] for i, ob in enumerate(items): tag = "p%d" % i o = dict(ob) o["tag"] = tag outbounds.append(o) inbounds.append({"type": "mixed", "tag": "in%d" % i, "listen": "127.0.0.1", "listen_port": base_port + i}) rules.append({"inbound": ["in%d" % i], "outbound": tag}) return { "log": {"level": "error"}, "dns": {"servers": [{"type": "local", "tag": "local"}]}, "inbounds": inbounds, "outbounds": outbounds, "route": {"rules": rules, "final": "direct", "default_domain_resolver": "local"}, } def probe(port, url): proxy = urllib.request.ProxyHandler({"http": f"http://127.0.0.1:{port}", "https": f"http://127.0.0.1:{port}"}) opener = urllib.request.build_opener(proxy) t0 = time.time() try: req = urllib.request.Request(url, headers={"User-Agent": "opencode-probe"}) with opener.open(req, timeout=PROBE_TIMEOUT) as r: r.read(64) return r.status, round((time.time() - t0) * 1000) except HTTPError as e: return e.code, round((time.time() - t0) * 1000) except (URLError, socket.timeout, OSError): return 0, round((time.time() - t0) * 1000) def check_config(sb, path): r = subprocess.run([sb, "check", "-c", path], capture_output=True, text=True) return r.returncode == 0, (r.stderr or r.stdout or "")[:300] def test_group(sb, items, base_port, workers, results): """Test a group; split it if sing-box refuses the combined config.""" if not items: return cfg = build_config([ob for _, ob in items], base_port) cfg_path = os.path.join(tempfile.gettempdir(), "oc_probe.json") with open(cfg_path, "w", encoding="utf-8") as fh: json.dump(cfg, fh) ok, err = check_config(sb, cfg_path) if not ok: if len(items) == 1: results.append((items[0][0], -1, 0)) return mid = len(items) // 2 test_group(sb, items[:mid], base_port, workers, results) test_group(sb, items[mid:], base_port, workers, results) return proc = subprocess.Popen([sb, "run", "-c", cfg_path], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0)) try: time.sleep(3.5) if proc.poll() is not None: # process died on startup - retest individually if len(items) > 1: mid = len(items) // 2 test_group(sb, items[:mid], base_port, workers, results) test_group(sb, items[mid:], base_port, workers, results) return results.append((items[0][0], -1, 0)) return def job(idx_item): idx, (link, _ob) = idx_item code, ms = probe(base_port + idx, TEST_URL) return link, code, ms with futures.ThreadPoolExecutor(max_workers=workers) as ex: results.extend(ex.map(job, list(enumerate(items)))) finally: proc.terminate() try: proc.wait(timeout=5) except Exception: # noqa: BLE001 proc.kill() def main(): ap = argparse.ArgumentParser() ap.add_argument("--limit", type=int, default=0, help="test only the first N configs") ap.add_argument("--workers", type=int, default=20) ap.add_argument("--chunk", type=int, default=25) args = ap.parse_args() sb = find_sing_box() print(f"sing-box : {sb}") srcs = [ln.strip() for ln in open(os.path.join(HERE, "sources.txt"), encoding="utf-8") if ln.strip() and not ln.startswith("#")] print(f"sources : {len(srcs)}") links = [] for s in srcs: try: text = fetch(s) found = re.findall(r"(?:vless|trojan|vmess|ss)://[^\s\"'<>]+", text) if not found: # many subscriptions are base64-encoded decoded = b64d(text) found = re.findall(r"(?:vless|trojan|vmess|ss)://[^\s\"'<>]+", decoded) print(f" {s.split('/')[-1]:24s} {len(found)} links") links.extend(found) except Exception as exc: # noqa: BLE001 print(f" {s.split('/')[-1]:24s} FAILED: {exc}") seen, unique = set(), [] for ln in links: if ln not in seen: seen.add(ln) unique.append(ln) if args.limit: unique = unique[: args.limit] print(f"unique : {len(unique)}\n") base = free_port_start() working, report = [], [] started = time.time() for ci in range(0, len(unique), args.chunk): chunk = unique[ci:ci + args.chunk] parsed = [] for ln in chunk: ob = parse_link(ln) if ob: parsed.append((ln, ob)) if not parsed: continue results = [] test_group(sb, parsed, base, args.workers, results) for ln, code, ms in results: tag = "OK" if code == 200 else str(code) if code > 0 else ("INVALID" if code < 0 else "DEAD") report.append(f"{tag:>7} {ms:>6}ms {ln}") if code == 200: working.append((ms, ln)) done = min(ci + args.chunk, len(unique)) print(f" tested {done}/{len(unique)} working={len(working)} " f"({int(time.time() - started)}s)") working.sort() out_txt = os.path.join(HERE, "opencode-working.txt") with open(out_txt, "w", encoding="utf-8") as fh: fh.write("".join(link + "\n" for _, link in working)) out_rep = os.path.join(HERE, "opencode-report.txt") with open(out_rep, "w", encoding="utf-8") as fh: fh.write("\n".join(report)) print(f"\nDONE working={len(working)}/{len(unique)} in {int(time.time() - started)}s") print(f" -> {out_txt}") print(f" -> {out_rep}") if __name__ == "__main__": main()