Terminal: drop files / paperclip; net core: fallback exit, re-test on network change, hide/unhide connections

- term.macOS: dropping files over an open terminal or the paperclip types their
  shell-escaped paths (bracketed paste when the program asks for it).
- Traffic now goes through a fallback group "exit": the pick while it answers,
  "auto" when it doesn't. A pinned connection that dies no longer cuts the Mac off.
- Faster checks (exit 30 s, auto 60 s, 3 failures trigger a re-test) and a re-test
  of every group 4 s after any network change (Wi-Fi switch, sleep, AmneziaVPN).
- hide/unhide instead of deleting keys: Amnezia connections and VLESS nodes leave the
  list and "auto"; kept on disk, returned from "Убранные".
- Core logs are owner-only (they can contain the subscription URL).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
maksarsanjeev
2026-10-09 23:25:47 +03:00
parent 9e02402555
commit 422c538df6
9 changed files with 373 additions and 56 deletions
Binary file not shown.
Binary file not shown.
+44 -14
View File
@@ -6,6 +6,8 @@ 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)
hidden.json connections removed in BroV: {"amnezia": [...], "vless": [...]} (proxy
names). Hidden ones stay on disk and can be returned from the panel.
Secrets stay in this private folder; nothing here goes to git.
"""
@@ -28,10 +30,26 @@ CLIENTS = { # name: (conf file, routed subnets, what "off" means)
# home WireGuard when away. Optional: only if src/home.conf exists.
"home": ("home.conf", ["192.168.10.0/24"], "DIRECT"),
}
TEST_URL = "https://www.gstatic.com/generate_204"
AI_DOMAINS = ["anthropic.com", "claude.ai", "claude.com", "openai.com", "chatgpt.com",
"oaistatic.com", "oaiusercontent.com", "github.com", "githubusercontent.com"]
def hidden():
try:
with open(os.path.join(CORE, "hidden.json")) as f:
h = json.load(f)
return {"amnezia": [str(x) for x in h.get("amnezia", [])], "vless": [str(x) for x in h.get("vless", [])]}
except (OSError, ValueError, AttributeError):
return {"amnezia": [], "vless": []}
def rx(name):
"""Literal regex for a node name (backslash only before ASCII punctuation: valid in Go
regexp and regexp2 alike)."""
return "".join("\\" + c if c in "\\.^$|?*+()[]{}" else c for c in name)
def mid(v, default):
"""'100-120' -> 110 (mihomo takes single ints for timers)."""
if v is None or v == "":
@@ -141,7 +159,9 @@ def main():
# Amnezia connections live in their own provider file so BroV can add keys live.
keyfiles = sorted(f for f in os.listdir(KEYS) if f.endswith(".vpnkey"))
awg = [amnezia(os.path.join(KEYS, f), "AWG " + f[:-len(".vpnkey")]) for f in keyfiles]
hid = hidden()
awg = [amnezia(os.path.join(KEYS, f), "AWG " + f[:-len(".vpnkey")]) for f in keyfiles
if "AWG " + f[:-len(".vpnkey")] not in hid["amnezia"]]
prov = os.path.join(KEYS, "amnezia.yaml")
with open(os.open(prov, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600), "w") as f:
f.write(y({"proxies": awg}) + "\n")
@@ -156,9 +176,18 @@ def main():
for name, (_, nets, _) in clients.items():
# Through a switch group: BroV turns client networks on/off without a reload.
rules += [f"IP-CIDR,{n},{name}-sw,no-resolve" for n in nets]
rules += [f"DOMAIN-SUFFIX,{d},ai-out" for d in AI_DOMAINS]
rules += [f"DOMAIN-SUFFIX,{d},exit" for d in AI_DOMAINS]
rules += ["DOMAIN-SUFFIX,ru,DIRECT", "DOMAIN-SUFFIX,su,DIRECT", "DOMAIN-SUFFIX,xn--p1ai,DIRECT",
"MATCH,ai-out"]
"MATCH,exit"]
vless = {
# Fetch the list directly: the nodes themselves are dialled directly anyway.
"type": "http", "url": sub, "interval": 43200, "path": "./providers/vless.yaml", "proxy": "DIRECT",
"health-check": {"enable": True, "url": TEST_URL, "interval": 300}}
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"]) + ")$"
awg_prov = {"type": "file", "path": "./keys/amnezia.yaml",
"health-check": {"enable": True, "url": TEST_URL, "interval": 300}}
cfg = {
"mixed-port": 7890, "allow-lan": False, "mode": "rule", "log-level": "error", "ipv6": False,
@@ -171,28 +200,29 @@ def main():
"fake-ip-filter": ["*.lan", "*.local", "+.duckdns.org"],
"default-nameserver": ["77.88.8.8", "1.1.1.1"],
"proxy-server-nameserver": ["77.88.8.8", "1.1.1.1"],
"nameserver": ["https://1.1.1.1/dns-query#ai-out", "https://8.8.8.8/dns-query#ai-out"],
"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": {"type": "file", "path": "./keys/amnezia.yaml",
"health-check": {"enable": True, "url": "https://www.gstatic.com/generate_204",
"interval": 300}},
"vless-cluster": {
# Fetch the list directly: the nodes themselves are dialled directly anyway.
"type": "http", "url": sub, "interval": 43200, "path": "./providers/vless.yaml", "proxy": "DIRECT",
"health-check": {"enable": True, "url": "https://www.gstatic.com/generate_204", "interval": 300}}},
"proxy-providers": {"amnezia-keys": awg_prov, "vless-cluster": vless},
"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).
# Back to the pick as soon as it answers again. Checked every 30 s and right after
# 3 failed connections.
{"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"]},
# 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"],
"url": "https://www.gstatic.com/generate_204", "interval": 120, "tolerance": 100, "lazy": False},
"url": TEST_URL, "interval": 60, "timeout": 4000, "max-failed-times": 3,
"tolerance": 100, "lazy": False},
# Amnezia: "amnezia-auto" (fastest connection) or one fixed connection.
{"name": "amnezia", "type": "select", "proxies": ["amnezia-auto"], "use": ["amnezia-keys"]},
{"name": "amnezia-auto", "type": "url-test", "use": ["amnezia-keys"],
"url": "https://www.gstatic.com/generate_204", "interval": 120, "tolerance": 100, "lazy": False},
"url": TEST_URL, "interval": 60, "timeout": 4000, "max-failed-times": 3,
"tolerance": 100, "lazy": False},
] + [
# Client networks: off (REJECT) until switched on in BroV.
# Client networks: first option = "off" (REJECT, or DIRECT for home).
+6
View File
@@ -120,6 +120,12 @@ write_plist "$CORE_LABEL" "$BIN" -d "$CORE" -f "$CORE/config.yaml"
write_plist "$CTL_LABEL" /usr/bin/python3 "$ROOT/netctl.py" "$USER_UID"
rm -f /Library/Logs/BroV/netcore.log
# Logs may contain the subscription URL: owner-only.
for label in "$CORE_LABEL" "$CTL_LABEL"; do
touch "/Library/Logs/BroV/$label.log"
chmod 600 "/Library/Logs/BroV/$label.log"
done
echo "→ Запускаю службы"
for label in "$CORE_LABEL" "$CTL_LABEL"; do
launchctl bootout "system/$label" 2>/dev/null || true
+91 -18
View File
@@ -6,12 +6,14 @@ The core (mihomo) runs as root with its config, keys and API secret in
to this helper over a Unix socket that only the installing user may open, and the helper
allows exactly these operations:
state groups, provider nodes with delays, TUN on/off
state groups, provider nodes with delays, hidden connections, TUN on/off
select {group, name} ai-out / amnezia / saga-sw / planet9-sw / home-sw, name must be a member
delay {group}|{proxy} speed test of ai-out / amnezia, or of the saga / planet9 / home tunnel
delay {group}|{proxy} speed test of exit / ai-out / amnezia, or of a client tunnel
tun {on} traffic capture on/off
add_key {text} vpn:// Amnezia key: checked by gen.py, stored, provider reloaded
remove_key {name} "AWG <slug>" connection
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
One JSON object per line in, one per line out. Nothing here can rewrite the core config
or point traffic elsewhere.
@@ -36,10 +38,14 @@ API = "http://127.0.0.1:9097"
TEST_URL = "https://www.gstatic.com/generate_204"
SELECT_GROUPS = {"ai-out", "amnezia", "saga-sw", "planet9-sw", "home-sw"}
DELAY_GROUPS = {"ai-out", "amnezia"}
DELAY_GROUPS = {"exit", "ai-out", "auto", "amnezia"}
CLIENT_TUNNELS = {"saga", "planet9", "home"}
MAX_REQUEST = 64 * 1024
HIDDEN = os.path.join(CORE, "hidden.json")
CONFIG = os.path.join(CORE, "config.yaml")
MIHOMO = os.path.join(ROOT, "mihomo")
ALLOWED_UID = int(sys.argv[1]) if len(sys.argv) > 1 else -1
gen_lock = threading.Lock()
@@ -82,7 +88,7 @@ def cmd_state(_):
lst = []
providers[prov] = [{"name": x.get("name"), "history": (x.get("history") or [])[-1:]} for x in lst]
tun = api("GET", "/configs").get("tun", {}).get("enable", False)
return {"ok": True, "proxies": keep, "providers": providers, "tun": tun}
return {"ok": True, "proxies": keep, "providers": providers, "tun": tun, "hidden": load_hidden()}
def cmd_select(r):
@@ -154,25 +160,92 @@ def cmd_add_key(r):
"proxy": proxy, "delay": provider_reload_and_test(proxy)}
def cmd_remove_key(r):
name = r.get("name", "")
m = re.fullmatch(r"AWG ([a-z0-9-]+)", name) if isinstance(name, str) else None
if not m:
def load_hidden():
try:
with open(HIDDEN) as f:
h = json.load(f)
return {"amnezia": list(h.get("amnezia", [])), "vless": list(h.get("vless", []))}
except (OSError, ValueError, AttributeError):
return {"amnezia": [], "vless": []}
def save_hidden(h):
tmp = HIDDEN + ".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:
json.dump(h, f, ensure_ascii=False)
os.rename(tmp, HIDDEN)
def awg_key_exists(name):
m = re.fullmatch(r"AWG ([a-z0-9-]+)", name)
path = os.path.join(KEYS, m.group(1) + ".vpnkey") if m else ""
return bool(m) and os.path.isfile(path) and not os.path.islink(path)
def reload_core():
"""Full config reload (needed for the VLESS filter): drops open connections for a moment.
The new config is checked first; TUN stays as the user left it."""
check = subprocess.run([MIHOMO, "-t", "-d", CORE, "-f", CONFIG], capture_output=True, text=True, timeout=30)
if check.returncode != 0:
raise RuntimeError("ядро не приняло новый конфиг")
tun = api("GET", "/configs").get("tun", {}).get("enable", False)
api("PUT", "/configs?force=true", {"path": CONFIG}, timeout=20)
if not tun:
api("PATCH", "/configs", {"tun": {"enable": False}})
def change_hidden(name, hide):
if not isinstance(name, str) or not name or len(name) > 200 or "\n" in name:
return {"ok": False, "error": "неверное имя подключения"}
path = os.path.join(KEYS, m.group(1) + ".vpnkey")
if not os.path.isfile(path) or os.path.islink(path):
return {"ok": False, "error": "такого подключения нет"}
with gen_lock:
if api("GET", "/proxies/amnezia").get("now") == name:
api("PUT", "/proxies/amnezia", {"name": "amnezia-auto"})
os.remove(path)
h = load_hidden()
if name.startswith("AWG "):
if not awg_key_exists(name):
return {"ok": False, "error": "такого подключения нет"}
kind = "amnezia"
else:
vless = [x.get("name") for x in api("GET", "/providers/proxies/vless-cluster").get("proxies", [])]
if hide and name not in vless:
return {"ok": False, "error": "такого узла нет"}
if not hide and name not in h["vless"]:
return {"ok": False, "error": "этот узел не скрыт"}
kind = "vless"
if hide:
# Leave the connection before it disappears.
if kind == "amnezia" and api("GET", "/proxies/amnezia").get("now") == name:
api("PUT", "/proxies/amnezia", {"name": "amnezia-auto"})
if kind == "vless" and api("GET", "/proxies/ai-out").get("now") == name:
api("PUT", "/proxies/ai-out", {"name": "auto"})
if name not in h[kind]:
h[kind].append(name)
else:
h[kind] = [x for x in h[kind] if x != name]
before = load_hidden()
save_hidden(h)
gen()
api("PUT", "/providers/proxies/amnezia-keys")
return {"ok": True}
if kind == "amnezia":
api("PUT", "/providers/proxies/amnezia-keys")
else:
try:
reload_core()
except Exception:
save_hidden(before) # keep disk and core in step
gen()
raise
return {"ok": True, "reloaded": kind == "vless"}
def cmd_hide(r):
return change_hidden(r.get("name"), True)
def cmd_unhide(r):
return change_hidden(r.get("name"), False)
COMMANDS = {"state": cmd_state, "select": cmd_select, "delay": cmd_delay, "tun": cmd_tun,
"add_key": cmd_add_key, "remove_key": cmd_remove_key}
"add_key": cmd_add_key, "hide": cmd_hide, "unhide": cmd_unhide}
# MARK: - Socket server