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
+1
View File
@@ -26,6 +26,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
Self.pruneInbox() Self.pruneInbox()
setupMenuBarItem() setupMenuBarItem()
CodexUsageMonitor.shared.start() CodexUsageMonitor.shared.start()
NetCore.shared.startWatchingNetwork()
AgentWatch.shared.start() AgentWatch.shared.start()
AgentAuth.shared.start() AgentAuth.shared.start()
setupIsland() setupIsland()
@@ -110,6 +110,8 @@ final class IslandWindowController: NSWindowController {
dropView.autoresizingMask = [.width, .height] dropView.autoresizingMask = [.width, .height]
dropView.onDragEntered = { [weak self] loc in dropView.onDragEntered = { [weak self] loc in
Task { @MainActor in Task { @MainActor in
// Over an open terminal the file goes into its command line, not the shelf.
if TerminalStore.shared.activeTab != nil { return }
let iLoc = self?.windowToIsland(loc) ?? CGPoint(x: 320, y: 88) let iLoc = self?.windowToIsland(loc) ?? CGPoint(x: 320, y: 88)
AppState.shared.fileDragOver = true AppState.shared.fileDragOver = true
// enterZone sets isActive=true BEFORE hookExpand triggers re-render, // enterZone sets isActive=true BEFORE hookExpand triggers re-render,
@@ -121,6 +123,7 @@ final class IslandWindowController: NSWindowController {
} }
dropView.onDragUpdated = { [weak self] loc in dropView.onDragUpdated = { [weak self] loc in
Task { @MainActor in Task { @MainActor in
if TerminalStore.shared.activeTab != nil { return }
let iLoc = self?.windowToIsland(loc) ?? CGPoint(x: 320, y: 88) let iLoc = self?.windowToIsland(loc) ?? CGPoint(x: 320, y: 88)
UploadSequenceEngine.shared.updateCursor(x: iLoc.x, y: iLoc.y) UploadSequenceEngine.shared.updateCursor(x: iLoc.x, y: iLoc.y)
} }
@@ -135,6 +138,10 @@ final class IslandWindowController: NSWindowController {
} }
dropView.onFilesDropped = { urls in dropView.onFilesDropped = { urls in
Task { @MainActor in Task { @MainActor in
if let tab = TerminalStore.shared.activeTab {
TerminalStore.shared.insertPaths(urls, into: tab)
return
}
await FileDropHandler.handle(urls: urls, state: AppState.shared) await FileDropHandler.handle(urls: urls, state: AppState.shared)
} }
} }
+162 -17
View File
@@ -1,5 +1,6 @@
import SwiftUI import SwiftUI
import AppKit import AppKit
import Network
// MARK: - Networks (globe in the header) // MARK: - Networks (globe in the header)
// //
@@ -9,6 +10,7 @@ import AppKit
// • right column — client networks: groups "<client>-sw" switched between REJECT and // • right column — client networks: groups "<client>-sw" switched between REJECT and
// the client's WireGuard tunnel. // the client's WireGuard tunnel.
// Switching a group never reloads the core, so open connections (this chat) survive. // Switching a group never reloads the core, so open connections (this chat) survive.
// Traffic goes through "exit": the pick in "ai-out" while it answers, "auto" when it doesn't.
struct NetExit: Identifiable, Equatable { struct NetExit: Identifiable, Equatable {
var id: String // proxy name in the core var id: String // proxy name in the core
@@ -44,6 +46,14 @@ final class NetCore: ObservableObject {
@Published var amneziaConns: [NetExit] = [] @Published var amneziaConns: [NetExit] = []
@Published var amneziaNow = "" @Published var amneziaNow = ""
@Published var amneziaAutoPick = "" @Published var amneziaAutoPick = ""
/// What traffic really uses: "ai-out" (the pick) or "auto" when the pick stopped answering.
@Published var exitNow = ""
/// Connections taken out of the list (Amnezia keys and VLESS nodes), can be put back.
@Published var hidden: [NetExit] = []
/// Asked before hiding: the connection's proxy name.
@Published var pendingHide: String?
var fallbackActive: Bool { exitNow == "auto" && currentExit != "auto" }
/// Delays measured by the group test (covers the subscription nodes too). /// Delays measured by the group test (covers the subscription nodes too).
private var measured: [String: Int] = [:] private var measured: [String: Int] = [:]
@@ -60,7 +70,7 @@ final class NetCore: ObservableObject {
// //
// The core, its config, keys and API secret are root-only. BroV only talks to the // The core, its config, keys and API secret are root-only. BroV only talks to the
// narrow helper over /var/run/brov-netctl.sock (owner: this user, 0600): state, select, // narrow helper over /var/run/brov-netctl.sock (owner: this user, 0600): state, select,
// delay, tun, add_key, remove_key — nothing that could rewrite the core config. // delay, tun, add_key, hide, unhide — nothing that could point traffic elsewhere.
private nonisolated static let socketPath = "/var/run/brov-netctl.sock" private nonisolated static let socketPath = "/var/run/brov-netctl.sock"
@@ -136,6 +146,11 @@ final class NetCore: ObservableObject {
if let h = proxies[name]?["history"] as? [[String: Any]], let d = h.last?["delay"] as? Int { return d } if let h = proxies[name]?["history"] as? [[String: Any]], let d = h.last?["delay"] as? Int { return d }
return providerDelay[name] return providerDelay[name]
} }
exitNow = proxies["exit"]?["now"] as? String ?? ""
let hid = st["hidden"] as? [String: [String]] ?? [:]
hidden = ((hid["amnezia"] ?? []) + (hid["vless"] ?? [])).map {
NetExit(id: $0, title: Self.pretty($0).0, subtitle: Self.pretty($0).1, delay: nil)
}
amneziaNow = proxies["amnezia"]?["now"] as? String ?? "" amneziaNow = proxies["amnezia"]?["now"] as? String ?? ""
amneziaAutoPick = proxies["amnezia-auto"]?["now"] as? String ?? "" amneziaAutoPick = proxies["amnezia-auto"]?["now"] as? String ?? ""
let amneziaEffective = amneziaNow == "amnezia-auto" ? amneziaAutoPick : amneziaNow let amneziaEffective = amneziaNow == "amnezia-auto" ? amneziaAutoPick : amneziaNow
@@ -234,12 +249,65 @@ final class NetCore: ObservableObject {
return (true, "Ключ «\(name)» сохранён (\(server)), но сервер пока не отвечает. Он будет участвовать в выборе, когда оживёт.") return (true, "Ключ «\(name)» сохранён (\(server)), но сервер пока не отвечает. Он будет участвовать в выборе, когда оживёт.")
} }
func removeAmnezia(_ proxyName: String) async { /// Takes a connection out of the list and out of "auto" (nothing is deleted).
_ = await call(["cmd": "remove_key", "name": proxyName]) func hide(_ name: String) async {
SoundEngine.shared.play("close") await changeHidden(name, cmd: "hide")
}
func unhide(_ name: String) async {
await changeHidden(name, cmd: "unhide")
}
private func changeHidden(_ name: String, cmd: String) async {
busy = true
let r = await call(["cmd": cmd, "name": name], timeout: 40)
busy = false
if r?["ok"] as? Bool == true {
lastError = nil
measured.removeValue(forKey: name)
SoundEngine.shared.play(cmd == "hide" ? "close" : "pop")
} else {
lastError = "Не получилось: \(r?["error"] as? String ?? "помощник не ответил")."
}
try? await Task.sleep(for: .milliseconds(500))
await refresh() await refresh()
} }
/// VLESS nodes come from the subscription: hiding one rebuilds the core config.
static func needsReload(_ name: String) -> Bool { !name.hasPrefix("AWG ") }
// MARK: Network changes
//
// Moving between home / Saga / Planet9 Wi-Fi, waking from sleep or AmneziaVPN going on
// and off leaves the WireGuard tunnels talking from an address that no longer exists.
// Re-test everything a few seconds after the change so "auto" and "exit" re-pick at
// once instead of at the next scheduled check.
private var pathMonitor: NWPathMonitor?
private var recheckTask: Task<Void, Never>?
func startWatchingNetwork() {
guard pathMonitor == nil else { return }
let m = NWPathMonitor()
m.pathUpdateHandler = { _ in
Task { @MainActor in NetCore.shared.networkChanged() }
}
m.start(queue: DispatchQueue(label: "brov.net.path"))
pathMonitor = m
}
private func networkChanged() {
recheckTask?.cancel()
recheckTask = Task {
try? await Task.sleep(for: .seconds(4))
guard !Task.isCancelled else { return }
_ = await call(["cmd": "delay", "group": "auto"], timeout: 15)
_ = await call(["cmd": "delay", "group": "amnezia"], timeout: 15)
_ = await call(["cmd": "delay", "group": "exit"], timeout: 15)
await refresh()
}
}
static var amneziaRunning: Bool { static var amneziaRunning: Bool {
// The app holds routes; its background AmneziaVPN-service doesn't. // The app holds routes; its background AmneziaVPN-service doesn't.
NSWorkspace.shared.runningApplications.contains { $0.localizedName == "AmneziaVPN" } NSWorkspace.shared.runningApplications.contains { $0.localizedName == "AmneziaVPN" }
@@ -334,6 +402,16 @@ struct NetPanel: View {
} }
} }
if net.running, net.tunOn, NetCore.amneziaRunning {
Text("Открыто приложение AmneziaVPN, а ядро тоже перехватывает трафик — они мешают друг другу. Выключи что-то одно.")
.font(.system(size: 11.5)).foregroundColor(Color(hex: "#FB923C"))
.fixedSize(horizontal: false, vertical: true).frame(width: 444, alignment: .leading)
}
if net.running, net.fallbackActive {
Text("«\(NetCore.pretty(net.currentExit).0)» не отвечает — сейчас трафик идёт через Авто (\(NetCore.pretty(net.autoPick).0)). Вернётся сам, когда выбранный выход оживёт.")
.font(.system(size: 11.5)).foregroundColor(Color(hex: "#F5A524"))
.fixedSize(horizontal: false, vertical: true).frame(width: 444, alignment: .leading)
}
if let err = net.lastError { if let err = net.lastError {
Text(err).font(.system(size: 11.5)).foregroundColor(Color(hex: "#FB923C")) Text(err).font(.system(size: 11.5)).foregroundColor(Color(hex: "#FB923C"))
.fixedSize(horizontal: false, vertical: true).frame(width: 444, alignment: .leading) .fixedSize(horizontal: false, vertical: true).frame(width: 444, alignment: .leading)
@@ -361,6 +439,7 @@ struct NetPanel: View {
if e.id == "amnezia" { if e.id == "amnezia" {
AmneziaSection(net: net, exit: e) AmneziaSection(net: net, exit: e)
} else { } else {
RemovableRow(removable: e.id != "auto") { net.pendingHide = e.id } row: {
NetRow(title: e.title, subtitle: e.subtitle, delay: e.delay, NetRow(title: e.title, subtitle: e.subtitle, delay: e.delay,
isOn: net.currentExit == e.id, accent: "#D97757") { isOn: net.currentExit == e.id, accent: "#D97757") {
guard net.currentExit != e.id else { return } guard net.currentExit != e.id else { return }
@@ -369,6 +448,8 @@ struct NetPanel: View {
} }
} }
} }
if !net.hidden.isEmpty { HiddenSection(net: net) }
}
.frame(width: 230) .frame(width: 230)
Rectangle().fill(Color.white.opacity(0.08)).frame(width: 1) Rectangle().fill(Color.white.opacity(0.08)).frame(width: 1)
@@ -391,6 +472,18 @@ struct NetPanel: View {
} }
} }
.padding(14) .padding(14)
.confirmationDialog("Убрать «\(NetCore.pretty(net.pendingHide ?? "").0)»?",
isPresented: Binding(get: { net.pendingHide != nil }, set: { if !$0 { net.pendingHide = nil } })) {
Button("Убрать", role: .destructive) {
if let n = net.pendingHide { Task { await net.hide(n) } }
net.pendingHide = nil
}
Button("Отмена", role: .cancel) { net.pendingHide = nil }
} message: {
Text(NetCore.needsReload(net.pendingHide ?? "")
? "Узел пропадёт из списка и из «Авто». Ядро перечитает настройки — открытые соединения (и этот чат) на секунду переподключатся. Вернуть можно в «Убранные»."
: "Подключение пропадёт из списка и из «Авто». Ключ останется на Маке — вернуть можно в «Убранные».")
}
.task { .task {
await net.refresh() await net.refresh()
if net.running { await net.measure() } if net.running { await net.measure() }
@@ -453,7 +546,6 @@ struct AmneziaSection: View {
let exit: NetExit let exit: NetExit
@State private var expanded = false @State private var expanded = false
@State private var adding = false @State private var adding = false
@State private var confirmRemove: String?
var body: some View { var body: some View {
VStack(alignment: .leading, spacing: 2) { VStack(alignment: .leading, spacing: 2) {
@@ -484,14 +576,11 @@ struct AmneziaSection: View {
if expanded { if expanded {
VStack(alignment: .leading, spacing: 1) { VStack(alignment: .leading, spacing: 1) {
ForEach(net.amneziaConns) { c in ForEach(net.amneziaConns) { c in
RemovableRow(removable: c.id != "amnezia-auto") { net.pendingHide = c.id } row: {
NetRow(title: c.title, subtitle: c.subtitle, delay: c.delay, NetRow(title: c.title, subtitle: c.subtitle, delay: c.delay,
isOn: net.currentExit == "amnezia" && net.amneziaNow == c.id, accent: "#D97757") { isOn: net.currentExit == "amnezia" && net.amneziaNow == c.id, accent: "#D97757") {
Task { await net.select(amnezia: c.id) } Task { await net.select(amnezia: c.id) }
} }
.contextMenu {
if c.id != "amnezia-auto" {
Button("Удалить подключение…", role: .destructive) { confirmRemove = c.id }
}
} }
} }
Button { adding = true } label: { Button { adding = true } label: {
@@ -515,16 +604,72 @@ struct AmneziaSection: View {
} }
} }
} }
.confirmationDialog("Удалить подключение «\(NetCore.pretty(confirmRemove ?? "").0)»?",
isPresented: Binding(get: { confirmRemove != nil }, set: { if !$0 { confirmRemove = nil } })) {
Button("Удалить", role: .destructive) {
if let n = confirmRemove { Task { await net.removeAmnezia(n) } }
confirmRemove = nil
} }
Button("Отмена", role: .cancel) { confirmRemove = nil }
} message: {
Text("Ключ будет удалён с этого Мака. Вернуть можно, вставив его снова.")
} }
/// A row with a "−" that appears on hover: takes the connection out of the list.
struct RemovableRow<Row: View>: View {
let removable: Bool
let onRemove: () -> Void
@ViewBuilder let row: () -> Row
@State private var hovered = false
var body: some View {
HStack(spacing: 2) {
row()
if removable && hovered {
Button(action: onRemove) {
Image(systemName: "minus.circle.fill")
.font(.system(size: 12))
.foregroundColor(Color(hex: "#8E939C"))
}
.buttonStyle(.plain)
.help("Убрать из списка и из «Авто»")
.transition(.opacity)
}
}
.onHover { h in withAnimation(.easeOut(duration: 0.12)) { hovered = h } }
}
}
/// Connections taken out of the list, each with "Вернуть".
struct HiddenSection: View {
@ObservedObject var net: NetCore
@State private var expanded = false
var body: some View {
VStack(alignment: .leading, spacing: 2) {
Button { withAnimation(.easeOut(duration: 0.15)) { expanded.toggle() } } label: {
HStack(spacing: 4) {
Text("Убранные (\(net.hidden.count))").font(.system(size: 11, weight: .medium))
Image(systemName: expanded ? "chevron.up" : "chevron.down").font(.system(size: 8, weight: .bold))
}
.foregroundColor(Color(hex: "#8E939C"))
.padding(.horizontal, 8).padding(.vertical, 5)
.contentShape(Rectangle())
}
.buttonStyle(.plain)
if expanded {
ForEach(net.hidden) { h in
HStack(spacing: 8) {
VStack(alignment: .leading, spacing: 1) {
Text(h.title).font(.system(size: 12, weight: .medium)).foregroundColor(Color(hex: "#8E939C"))
Text(h.subtitle).font(.system(size: 10.5)).foregroundColor(Color(hex: "#5F646D")).lineLimit(1)
}
Spacer(minLength: 4)
Button { Task { await net.unhide(h.id) } } label: {
Text("Вернуть").font(.system(size: 11, weight: .medium))
.padding(.horizontal, 8).frame(height: 20)
.background(Capsule().fill(Color.white.opacity(0.08)))
}
.buttonStyle(.plain)
.disabled(net.busy)
}
.padding(.horizontal, 8).padding(.vertical, 3)
}
}
}
.padding(.top, 4)
} }
} }
+55
View File
@@ -127,6 +127,48 @@ final class TerminalStore: NSObject, LocalProcessTerminalViewDelegate {
} }
} }
/// The terminal tab on screen right now, if any (drops and the paperclip go there).
var activeTab: UUID? {
let s = AppState.shared
guard s.view == .terminal, s.mode == .expanded, let id = s.activeTabId,
s.tabs.first(where: { $0.id == id })?.kind == .terminal else { return nil }
return id
}
/// Types the files' paths at the prompt, shell-escaped like Terminal.app does on a drop.
/// Sent as a bracketed paste when the program asks for it (claude then attaches images).
func insertPaths(_ urls: [URL], into id: UUID) {
guard let v = views[id], !urls.isEmpty else { return }
let text = urls.map { Self.shellEscaped($0.path) }.joined(separator: " ") + " "
if v.getTerminal().bracketedPasteMode {
v.send(txt: "\u{1b}[200~" + text + "\u{1b}[201~")
} else {
v.send(txt: text)
}
v.window?.makeFirstResponder(v)
}
func choosePaths(for id: UUID) {
let panel = NSOpenPanel()
panel.canChooseFiles = true
panel.canChooseDirectories = true
panel.allowsMultipleSelection = true
panel.prompt = "Вставить"
panel.message = "Пути выбранных файлов появятся в терминале"
NSApp.activate(ignoringOtherApps: true)
if panel.runModal() == .OK { insertPaths(panel.urls, into: id) }
}
static func shellEscaped(_ path: String) -> String {
let special = Set(" \t!\"#$&'()*,;<=>?[\\]^`{|}~")
var out = ""
for ch in path {
if special.contains(ch) { out.append("\\") }
out.append(ch)
}
return out
}
private func tabId(of source: TerminalView) -> UUID? { private func tabId(of source: TerminalView) -> UUID? {
views.first(where: { $0.value === source })?.key views.first(where: { $0.value === source })?.key
} }
@@ -184,6 +226,19 @@ struct TerminalScreen: View {
TerminalTabView(tabId: id) TerminalTabView(tabId: id)
.padding(.horizontal, 10) .padding(.horizontal, 10)
.padding(.vertical, 8) .padding(.vertical, 8)
.overlay(alignment: .topTrailing) {
Button { TerminalStore.shared.choosePaths(for: id) } label: {
Image(systemName: "paperclip")
.font(.system(size: 11, weight: .semibold))
.foregroundColor(Color(hex: "#8E939C"))
.frame(width: 24, height: 24)
.background(Circle().fill(Color.white.opacity(0.08)))
}
.buttonStyle(.plain)
.help("Вставить путь к файлу (или перетащи файл в терминал)")
.padding(.top, 8)
.padding(.trailing, 14)
}
} }
} }
.padding(.top, 4) .padding(.top, 4)
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/saga.conf WireGuard client config -> only 192.168.8.0/24
src/planet9.conf WireGuard client config -> only 192.168.68.0/24 src/planet9.conf WireGuard client config -> only 192.168.68.0/24
src/vless.sub 3x-ui subscription URL (all VLESS nodes) 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. 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 WireGuard when away. Optional: only if src/home.conf exists.
"home": ("home.conf", ["192.168.10.0/24"], "DIRECT"), "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", AI_DOMAINS = ["anthropic.com", "claude.ai", "claude.com", "openai.com", "chatgpt.com",
"oaistatic.com", "oaiusercontent.com", "github.com", "githubusercontent.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): def mid(v, default):
"""'100-120' -> 110 (mihomo takes single ints for timers).""" """'100-120' -> 110 (mihomo takes single ints for timers)."""
if v is None or v == "": 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. # 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")) 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") 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: with open(os.open(prov, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600), "w") as f:
f.write(y({"proxies": awg}) + "\n") f.write(y({"proxies": awg}) + "\n")
@@ -156,9 +176,18 @@ def main():
for name, (_, nets, _) in clients.items(): for name, (_, nets, _) in clients.items():
# Through a switch group: BroV turns client networks on/off without a reload. # 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"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", 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 = { cfg = {
"mixed-port": 7890, "allow-lan": False, "mode": "rule", "log-level": "error", "ipv6": False, "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"], "fake-ip-filter": ["*.lan", "*.local", "+.duckdns.org"],
"default-nameserver": ["77.88.8.8", "1.1.1.1"], "default-nameserver": ["77.88.8.8", "1.1.1.1"],
"proxy-server-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"]}, "direct-nameserver": ["77.88.8.8", "77.88.8.1"]},
"proxies": proxies, "proxies": proxies,
"proxy-providers": { "proxy-providers": {"amnezia-keys": awg_prov, "vless-cluster": vless},
"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-groups": [ "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. # 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"]},
# Fastest alive exit among every Amnezia connection and every VLESS node; # Fastest alive exit among every Amnezia connection and every VLESS node;
# switches only when another one is 100+ ms faster. # 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"],
"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. # Amnezia: "amnezia-auto" (fastest connection) or one fixed connection.
{"name": "amnezia", "type": "select", "proxies": ["amnezia-auto"], "use": ["amnezia-keys"]}, {"name": "amnezia", "type": "select", "proxies": ["amnezia-auto"], "use": ["amnezia-keys"]},
{"name": "amnezia-auto", "type": "url-test", "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: off (REJECT) until switched on in BroV.
# Client networks: first option = "off" (REJECT, or DIRECT for home). # 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" write_plist "$CTL_LABEL" /usr/bin/python3 "$ROOT/netctl.py" "$USER_UID"
rm -f /Library/Logs/BroV/netcore.log 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 "→ Запускаю службы" echo "→ Запускаю службы"
for label in "$CORE_LABEL" "$CTL_LABEL"; do for label in "$CORE_LABEL" "$CTL_LABEL"; do
launchctl bootout "system/$label" 2>/dev/null || true launchctl bootout "system/$label" 2>/dev/null || true
+89 -16
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 to this helper over a Unix socket that only the installing user may open, and the helper
allows exactly these operations: 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 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 tun {on} traffic capture on/off
add_key {text} vpn:// Amnezia key: checked by gen.py, stored, provider reloaded 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 One JSON object per line in, one per line out. Nothing here can rewrite the core config
or point traffic elsewhere. or point traffic elsewhere.
@@ -36,10 +38,14 @@ API = "http://127.0.0.1:9097"
TEST_URL = "https://www.gstatic.com/generate_204" TEST_URL = "https://www.gstatic.com/generate_204"
SELECT_GROUPS = {"ai-out", "amnezia", "saga-sw", "planet9-sw", "home-sw"} 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"} CLIENT_TUNNELS = {"saga", "planet9", "home"}
MAX_REQUEST = 64 * 1024 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 ALLOWED_UID = int(sys.argv[1]) if len(sys.argv) > 1 else -1
gen_lock = threading.Lock() gen_lock = threading.Lock()
@@ -82,7 +88,7 @@ def cmd_state(_):
lst = [] lst = []
providers[prov] = [{"name": x.get("name"), "history": (x.get("history") or [])[-1:]} for x in 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) 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): def cmd_select(r):
@@ -154,25 +160,92 @@ def cmd_add_key(r):
"proxy": proxy, "delay": provider_reload_and_test(proxy)} "proxy": proxy, "delay": provider_reload_and_test(proxy)}
def cmd_remove_key(r): def load_hidden():
name = r.get("name", "") try:
m = re.fullmatch(r"AWG ([a-z0-9-]+)", name) if isinstance(name, str) else None with open(HIDDEN) as f:
if not m: 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": "неверное имя подключения"} 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: with gen_lock:
if api("GET", "/proxies/amnezia").get("now") == name: 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"}) api("PUT", "/proxies/amnezia", {"name": "amnezia-auto"})
os.remove(path) 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() gen()
if kind == "amnezia":
api("PUT", "/providers/proxies/amnezia-keys") api("PUT", "/providers/proxies/amnezia-keys")
return {"ok": True} 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, 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 # MARK: - Socket server