diff --git a/CLAUDE.md b/CLAUDE.md index 0e9e121..73eed8f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -30,7 +30,7 @@ DerivedData must stay outside ~/Documents (iCloud adds Finder attributes and cod ## Network core (globe 🌐 in the header) - mihomo runs as root: LaunchDaemon `local.maksar.brov.netd`, binary + config + keys + API secret in `/Library/Application Support/BroV/` (root, 0700). Nothing user-writable is read by root. - BroV never sees the config or the API secret: it talks to the narrow root helper `scripts/netcore/netctl.py` (LaunchDaemon `local.maksar.brov.netctl`, socket `/var/run/brov-netctl.sock`, only the installing user) — commands: state, select, delay, tun (on = clean core restart, refused while the AmneziaVPN app is open; also points the Mac DNS into the core), add_key, hide, unhide. -- `scripts/netcore/gen.py` builds the config (Amnezia keys → provider `keys/amnezia.yaml`, WireGuard clients, VLESS subscription). Install/update: `sudo sh scripts/netcore/install.sh` (verifies the mihomo SHA256, migrates keys). Never commit keys, configs or the guide (`~/.brov-secrets`). +- `scripts/netcore/gen.py` builds the config (Amnezia keys → provider `keys/amnezia.yaml`, single vless:// links added in BroV → provider `vless-keys` from `keys/vless.txt`, WireGuard clients, VLESS subscription). Install/update: `sudo sh scripts/netcore/install.sh` (verifies the mihomo SHA256, migrates keys). Never commit keys, configs or the guide (`~/.brov-secrets`). - Reloading the whole core config drops every connection (including this chat); group switches and provider reloads don't. ## BroV Ops (homelab manager, `ops/`) diff --git a/NotchBuddy/Sources/App/NetPanel.swift b/NotchBuddy/Sources/App/NetPanel.swift index 192e970..00f532d 100644 --- a/NotchBuddy/Sources/App/NetPanel.swift +++ b/NotchBuddy/Sources/App/NetPanel.swift @@ -229,10 +229,13 @@ final class NetCore: ObservableObject { await refresh() } - /// Sends a pasted vpn:// key to the helper (it checks, stores and tests it as root). + /// Sends a pasted vpn:// (Amnezia) or vless:// key to the helper (it checks, stores and + /// tests it as root). func addAmneziaKey(_ text: String) async -> (ok: Bool, message: String) { let key = text.trimmingCharacters(in: .whitespacesAndNewlines) - guard key.hasPrefix("vpn://") else { return (false, "Ключ должен начинаться с vpn://") } + guard key.hasPrefix("vpn://") || key.hasPrefix("vless://") else { + return (false, "Ключ должен начинаться с vpn:// (Амнезия) или vless://") + } guard let r = await call(["cmd": "add_key", "text": key], timeout: 30) else { return (false, "Помощник сетевого ядра не отвечает.") } @@ -689,8 +692,8 @@ struct AddAmneziaKeyView: View { var body: some View { VStack(alignment: .leading, spacing: 10) { - Text("Новое подключение Амнезии").font(.system(size: 13, weight: .semibold)) - Text("Вставь ключ vpn:// из приложения Amnezia (Поделиться → AmneziaWG или ключ целиком).") + Text("Новое подключение").font(.system(size: 13, weight: .semibold)) + Text("Вставь ключ vpn:// из приложения Amnezia или ссылку vless://. VLESS появится среди выходов и войдёт в «Авто»; первый такой ключ перезапустит ядро — соединения на секунду переподключатся.") .font(.system(size: 11)).foregroundColor(Color(hex: "#8E939C")) .fixedSize(horizontal: false, vertical: true) TextEditor(text: $text) diff --git a/scripts/netcore/gen.py b/scripts/netcore/gen.py index 655b8ce..1959e98 100755 --- a/scripts/netcore/gen.py +++ b/scripts/netcore/gen.py @@ -6,6 +6,7 @@ keys/*.vpnkey one vpn:// key per Amnezia connection (AmneziaWG 2/3); BroV src/saga.conf WireGuard client config -> only 192.168.8.0/24 src/planet9.conf WireGuard client config -> only 192.168.68.0/24 src/vless.sub 3x-ui subscription URL (all VLESS nodes) +keys/vless.txt single vless:// links added in BroV (one per line, e.g. a client's server) tun.json {"on": bool}: traffic capture as the user left it (survives restarts) hidden.json connections removed in BroV: {"amnezia": [...], "vless": [...]} (proxy names). Hidden ones stay on disk and can be returned from the panel. @@ -195,6 +196,15 @@ def main(): if hid["vless"]: # Hidden nodes stay in the subscription, the core just skips them. vless["exclude-filter"] = "^(?:" + "|".join(rx(n) for n in hid["vless"]) + ")$" + # Single VLESS links added in BroV: a provider of their own (only when there are any — + # mihomo refuses an empty provider file). + extra_prov = {} + vless_file = os.path.join(KEYS, "vless.txt") + if os.path.exists(vless_file) and any(l.strip().startswith("vless://") for l in open(vless_file)): + extra_prov["vless-keys"] = {"type": "file", "path": "./keys/vless.txt", + "health-check": {"enable": True, "url": TEST_URL, "interval": 300}} + if hid["vless"]: + extra_prov["vless-keys"]["exclude-filter"] = vless["exclude-filter"] awg_prov = {"type": "file", "path": "./keys/amnezia.yaml", "health-check": {"enable": True, "url": TEST_URL, "interval": 300}} @@ -212,7 +222,7 @@ def main(): "nameserver": ["https://1.1.1.1/dns-query#exit", "https://8.8.8.8/dns-query#exit"], "direct-nameserver": ["77.88.8.8", "77.88.8.1"]}, "proxies": proxies, - "proxy-providers": {"amnezia-keys": awg_prov, "vless-cluster": vless}, + "proxy-providers": {"amnezia-keys": awg_prov, "vless-cluster": vless, **extra_prov}, "proxy-groups": [ # What traffic actually uses: the exit picked in BroV while it answers, "auto" # when it doesn't (a pinned connection that dies no longer takes the Mac offline). @@ -221,10 +231,10 @@ def main(): {"name": "exit", "type": "fallback", "proxies": ["ai-out", "auto"], "url": TEST_URL, "interval": 30, "timeout": 4000, "max-failed-times": 3, "lazy": False}, # What BroV's globe panel switches: "auto", the Amnezia group, or one VLESS node. - {"name": "ai-out", "type": "select", "proxies": ["auto", "amnezia"], "use": ["vless-cluster"]}, + {"name": "ai-out", "type": "select", "proxies": ["auto", "amnezia"], "use": ["vless-cluster", *extra_prov]}, # Fastest alive exit among every Amnezia connection and every VLESS node; # switches only when another one is 100+ ms faster. - {"name": "auto", "type": "url-test", "use": ["amnezia-keys", "vless-cluster"], + {"name": "auto", "type": "url-test", "use": ["amnezia-keys", "vless-cluster", *extra_prov], "url": TEST_URL, "interval": 60, "timeout": 4000, "max-failed-times": 3, "tolerance": 100, "lazy": False}, # Amnezia: "amnezia-auto" (fastest connection) or one fixed connection. diff --git a/scripts/netcore/netctl.py b/scripts/netcore/netctl.py index 471152b..2a1b057 100644 --- a/scripts/netcore/netctl.py +++ b/scripts/netcore/netctl.py @@ -10,7 +10,7 @@ allows exactly these operations: select {group, name} ai-out / amnezia / saga-sw / planet9-sw / home-sw, name must be a member delay {group}|{proxy} speed test of exit / ai-out / amnezia, or of a client tunnel tun {on} traffic capture on (fresh core start) / off; remembered - add_key {text} vpn:// Amnezia key: checked by gen.py, stored, provider reloaded + add_key {text} vpn:// Amnezia key (checked by gen.py) or a vless:// link: stored, core updated hide {name} take an Amnezia connection or a VLESS node out of the list and out of "auto" (the key / subscription stay, nothing is deleted) unhide {name} put it back @@ -83,7 +83,7 @@ def cmd_state(_): for name, p in proxies.items(): keep[name] = {"now": p.get("now"), "all": p.get("all"), "history": (p.get("history") or [])[-1:]} providers = {} - for prov in ("vless-cluster", "amnezia-keys"): + for prov in ("vless-cluster", "vless-keys", "amnezia-keys"): try: lst = api("GET", "/providers/proxies/" + prov).get("proxies", []) except Exception: @@ -224,10 +224,72 @@ def provider_reload_and_test(proxy): return 0 +VLESS_FILE = os.path.join(KEYS, "vless.txt") + + +def provider_names(name): + try: + return [x.get("name") for x in api("GET", "/providers/proxies/" + name).get("proxies", [])] + except Exception: + return [] + + +def add_vless(text): + """A single vless:// link → keys/vless.txt (provider vless-keys). The first one creates + the provider: a full core reload (connections drop for a second); later ones only + reload the provider.""" + u = urllib.parse.urlsplit(text) + q = urllib.parse.parse_qs(u.query) + try: + port = u.port + except ValueError: + port = None + if (u.scheme != "vless" or not re.fullmatch(r"[0-9a-fA-F-]{36}", u.username or "") or not u.hostname + or not port or any(c in text for c in "\n\r '\"")): + return {"ok": False, "error": "не похоже на ссылку vless://uuid@сервер:порт?…"} + if q.get("security", [""])[0] == "reality" and not q.get("pbk"): + return {"ok": False, "error": "у Reality-ссылки нет ключа pbk"} + with gen_lock: + lines = [l.strip() for l in open(VLESS_FILE)] if os.path.exists(VLESS_FILE) else [] + lines = [l for l in lines if l.startswith("vless://")] + if any(urllib.parse.urlsplit(l)._replace(fragment="") == u._replace(fragment="") for l in lines): + return {"ok": False, "error": "этот ключ уже добавлен"} + taken = set(provider_names("vless-cluster")) | {urllib.parse.unquote(urllib.parse.urlsplit(l).fragment) for l in lines} + base = urllib.parse.unquote(u.fragment).strip() or u.hostname + name, n = base, 2 + while name in taken: + name, n = f"{base} {n}", n + 1 + line = urllib.parse.urlunsplit(u._replace(fragment=urllib.parse.quote(name))) + first = not lines + tmp = VLESS_FILE + ".tmp" + fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o600) + with os.fdopen(fd, "w") as f: + f.write("\n".join(lines + [line]) + "\n") + os.rename(tmp, VLESS_FILE) + gen() + if first: + reload_core() + else: + api("PUT", "/providers/proxies/vless-keys") + delay = 0 + try: + delay = api("GET", "/providers/proxies/vless-keys/%s/healthcheck?url=%s&timeout=6000" + % (q_(name), q_(TEST_URL)), timeout=10).get("delay", 0) + except Exception: + pass + return {"ok": True, "name": name, "server": "%s:%s" % (u.hostname, port), "proxy": name, "delay": delay} + + +def q_(s): + return urllib.parse.quote(s, safe="") + + def cmd_add_key(r): text = r.get("text") + if isinstance(text, str) and text.strip().startswith("vless://") and len(text) < 4000: + return add_vless(text.strip()) if not isinstance(text, str) or not text.strip().startswith("vpn://") or len(text) > 20000: - return {"ok": False, "error": "ключ должен начинаться с vpn://"} + return {"ok": False, "error": "ключ должен начинаться с vpn:// (Амнезия) или vless://"} with gen_lock: pending = os.path.join(KEYS, ".pending.vpnkey") fd = os.open(pending, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o600) @@ -293,7 +355,7 @@ def change_hidden(name, hide): return {"ok": False, "error": "такого подключения нет"} kind = "amnezia" else: - vless = [x.get("name") for x in api("GET", "/providers/proxies/vless-cluster").get("proxies", [])] + vless = provider_names("vless-cluster") + provider_names("vless-keys") if hide and name not in vless: return {"ok": False, "error": "такого узла нет"} if not hide and name not in h["vless"]: