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
+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