Skip to content

Force Proxy to any Windows/MacOS/Linux Application TCP and UDP traffic

#44 - Added macos multi proxy in UI and sys extension

AnoF-Cyber70f4fb40a961
diff --git a/MacOS/ProxyBridge/ProxyBridge/ProxyBridgeViewModel.swift b/MacOS/ProxyBridge/ProxyBridge/ProxyBridgeViewModel.swift
index 403bd4c..ea2431c 100644
--- a/MacOS/ProxyBridge/ProxyBridge/ProxyBridgeViewModel.swift
+++ b/MacOS/ProxyBridge/ProxyBridge/ProxyBridgeViewModel.swift
@@ -11,7 +11,7 @@ class ProxyBridgeViewModel: NSObject, ObservableObject {
var tunnelSession: NETunnelProviderSession?
private var logTimer: Timer?
- private(set) var proxyConfig: ProxyConfig?
+ @Published private(set) var proxyConfigs: [ProxyConfig] = []
private let maxLogEntries = 1000
// trim to 80% when limit hit to avoid trimming on each entry
@@ -29,12 +29,24 @@ class ProxyBridgeViewModel: NSObject, ObservableObject {
private var connectionIdCounter: Int = 0
private var activityIdCounter: Int = 0
- struct ProxyConfig {
+ struct ProxyConfig: Identifiable, Codable {
+ let id: String
let type: String
let host: String
let port: Int
let username: String?
let password: String?
+
+ var displayName: String { "\(type.uppercased()) \(host):\(port)" }
+
+ init(id: String = UUID().uuidString, type: String, host: String, port: Int, username: String?, password: String?) {
+ self.id = id
+ self.type = type
+ self.host = host
+ self.port = port
+ self.username = username
+ self.password = password
+ }
}
struct ConnectionLog: Identifiable {
@@ -92,37 +104,60 @@ class ProxyBridgeViewModel: NSObject, ObservableObject {
}
private func loadProxyConfig() {
- if let type = UserDefaults.standard.string(forKey: "proxyType"),
- let host = UserDefaults.standard.string(forKey: "proxyHost"),
- let port = UserDefaults.standard.object(forKey: "proxyPort") as? Int {
- let username = UserDefaults.standard.string(forKey: "proxyUsername")
- let password = UserDefaults.standard.string(forKey: "proxyPassword")
-
- proxyConfig = ProxyConfig(
- type: type,
- host: host,
- port: port,
- username: username,
- password: password
- )
+ if let data = UserDefaults.standard.data(forKey: "proxyConfigs"),
+ let configs = try? JSONDecoder().decode([ProxyConfig].self, from: data) {
+ proxyConfigs = configs
}
}
-
- private func saveProxyConfig(_ config: ProxyConfig) {
- UserDefaults.standard.set(config.type, forKey: "proxyType")
- UserDefaults.standard.set(config.host, forKey: "proxyHost")
- UserDefaults.standard.set(config.port, forKey: "proxyPort")
-
- if let username = config.username {
- UserDefaults.standard.set(username, forKey: "proxyUsername")
- } else {
- UserDefaults.standard.removeObject(forKey: "proxyUsername")
+
+ private func saveProxyConfigs() {
+ if let data = try? JSONEncoder().encode(proxyConfigs) {
+ UserDefaults.standard.set(data, forKey: "proxyConfigs")
}
-
- if let password = config.password {
- UserDefaults.standard.set(password, forKey: "proxyPassword")
- } else {
- UserDefaults.standard.removeObject(forKey: "proxyPassword")
+ }
+
+ func addProxyConfig(_ config: ProxyConfig) {
+ proxyConfigs.append(config)
+ saveProxyConfigs()
+ if let session = tunnelSession {
+ sendProxyConfigsToExtension(session: session)
+ }
+ }
+
+ func updateProxyConfig(_ config: ProxyConfig) {
+ if let index = proxyConfigs.firstIndex(where: { $0.id == config.id }) {
+ proxyConfigs[index] = config
+ saveProxyConfigs()
+ if let session = tunnelSession {
+ sendProxyConfigsToExtension(session: session)
+ }
+ }
+ }
+
+ func rulesUsingProxy(id: String) -> Int {
+ let saved = UserDefaults.standard.array(forKey: "proxyRules") as? [[String: Any]] ?? []
+ return saved.filter { ($0["action"] as? String) == id }.count
+ }
+
+ func removeProxyConfig(_ config: ProxyConfig) {
+ // reset any rules pointing to this config to DIRECT so they don't silently go direct anyway
+ if var saved = UserDefaults.standard.array(forKey: "proxyRules") as? [[String: Any]] {
+ var changed = false
+ for i in saved.indices where (saved[i]["action"] as? String) == config.id {
+ saved[i]["action"] = "DIRECT"
+ changed = true
+ }
+ if changed {
+ UserDefaults.standard.set(saved, forKey: "proxyRules")
+ if let session = tunnelSession {
+ RuleManager.loadRulesFromUserDefaults(session: session) { _, _ in }
+ }
+ }
+ }
+ proxyConfigs.removeAll { $0.id == config.id }
+ saveProxyConfigs()
+ if let session = tunnelSession {
+ sendProxyConfigsToExtension(session: session)
}
}
@@ -209,9 +244,8 @@ class ProxyBridgeViewModel: NSObject, ObservableObject {
observer = nil
self.setupLogPolling(session: session)
-
- if let config = self.proxyConfig {
- self.sendProxyConfigToExtension(config, session: session)
+ if !self.proxyConfigs.isEmpty {
+ self.sendProxyConfigsToExtension(session: session)
}
RuleManager.loadRulesFromUserDefaults(session: session) { success, count in
@@ -378,44 +412,30 @@ class ProxyBridgeViewModel: NSObject, ObservableObject {
}
}
- func setProxyConfig(_ config: ProxyConfig) {
- proxyConfig = config
- saveProxyConfig(config)
-
- guard let session = tunnelSession else {
- addLog("ERROR", "Extension not connected")
- return
- }
-
- sendProxyConfigToExtension(config, session: session)
- }
-
- private func sendProxyConfigToExtension(_ config: ProxyConfig, session: NETunnelProviderSession) {
- var message: [String: Any] = [
- "action": "setProxyConfig",
- "proxyType": config.type,
- "proxyHost": config.host,
- "proxyPort": config.port
- ]
-
- if let username = config.username {
- message["proxyUsername"] = username
- }
- if let password = config.password {
- message["proxyPassword"] = password
+
+ func sendProxyConfigsToExtension(session: NETunnelProviderSession) {
+ let configsArray: [[String: Any]] = proxyConfigs.map { config in
+ var dict: [String: Any] = [
+ "id": config.id,
+ "proxyType": config.type,
+ "proxyHost": config.host,
+ "proxyPort": config.port
+ ]
+ if let u = config.username { dict["proxyUsername"] = u }
+ if let p = config.password { dict["proxyPassword"] = p }
+ return dict
}
-
+ let message: [String: Any] = ["action": "setProxyConfigs", "configs": configsArray]
guard let data = try? JSONSerialization.data(withJSONObject: message) else {
- addLog("ERROR", "Failed to encode proxy config")
+ addLog("ERROR", "Failed to encode proxy configs")
return
}
-
try? session.sendProviderMessage(data) { [weak self] response in
if let responseData = response,
let json = try? JSONSerialization.jsonObject(with: responseData) as? [String: Any],
let status = json["status"] as? String, status == "ok" {
DispatchQueue.main.async {
- self?.addLog("INFO", "Proxy configured: \(config.type)://\(config.host):\(config.port)")
+ self?.addLog("INFO", "Proxy configs sent: \(self?.proxyConfigs.count ?? 0) config(s)")
}
}
}
diff --git a/MacOS/ProxyBridge/ProxyBridge/ProxyRulesView.swift b/MacOS/ProxyBridge/ProxyBridge/ProxyRulesView.swift
index 617237a..212bd41 100644
--- a/MacOS/ProxyBridge/ProxyBridge/ProxyRulesView.swift
+++ b/MacOS/ProxyBridge/ProxyBridge/ProxyRulesView.swift
@@ -210,11 +210,11 @@ struct ProxyRulesView: View {
.width(80)
TableColumn("Action") { rule in
- Text(rule.action)
+ Text(actionDisplayName(rule.action))
.foregroundColor(actionColor(rule.action))
.fontWeight(.semibold)
}
- .width(80)
+ .width(160)
}
.padding()
}
@@ -242,10 +242,17 @@ struct ProxyRulesView: View {
private func actionColor(_ action: String) -> Color {
switch action {
- case "PROXY": return .green
case "BLOCK": return .red
case "DIRECT": return .blue
- default: return .primary
+ default: return .green // any proxy config UUID
+ }
+ }
+
+ private func actionDisplayName(_ action: String) -> String {
+ switch action {
+ case "DIRECT", "BLOCK": return action
+ default:
+ return viewModel.proxyConfigs.first(where: { $0.id == action })?.displayName ?? action
}
}
@@ -368,27 +375,31 @@ struct RuleEditorView: View {
@ObservedObject var viewModel: ProxyBridgeViewModel
var existingRule: ProxyRule?
var onSave: () -> Void
-
+
@Environment(\.dismiss) private var dismiss
-
+
@State private var processNames: String
@State private var targetHosts: String
@State private var targetPorts: String
@State private var selectedProtocol: String
@State private var selectedAction: String
-
+ @State private var saveError: String = ""
+ @State private var isSaving = false
+
private var isEditMode: Bool { existingRule != nil }
init(viewModel: ProxyBridgeViewModel, existingRule: ProxyRule? = nil, onSave: @escaping () -> Void) {
self.viewModel = viewModel
self.existingRule = existingRule
self.onSave = onSave
-
+
_processNames = State(initialValue: existingRule?.processNames ?? "*")
_targetHosts = State(initialValue: existingRule?.targetHosts ?? "*")
_targetPorts = State(initialValue: existingRule?.targetPorts ?? "*")
_selectedProtocol = State(initialValue: existingRule?.ruleProtocol ?? "TCP")
- _selectedAction = State(initialValue: existingRule?.action ?? "PROXY")
+ // default to first proxy config if there is one, otherwise direct
+ let defaultAction = existingRule?.action ?? viewModel.proxyConfigs.first?.id ?? "DIRECT"
+ _selectedAction = State(initialValue: defaultAction)
}
var body: some View {
@@ -435,11 +446,33 @@ struct RuleEditorView: View {
Text("Action")
.fontWeight(.medium)
Picker("", selection: $selectedAction) {
- Text("PROXY").tag("PROXY")
Text("DIRECT").tag("DIRECT")
Text("BLOCK").tag("BLOCK")
+ if !viewModel.proxyConfigs.isEmpty {
+ Divider()
+ ForEach(viewModel.proxyConfigs) { config in
+ Text(config.displayName).tag(config.id)
+ }
+ }
+ }
+ .pickerStyle(.menu)
+ if selectedProtocol == "UDP" || selectedProtocol == "BOTH" {
+ let isHttp = viewModel.proxyConfigs.first(where: { $0.id == selectedAction })?.type.lowercased() == "http"
+ if isHttp {
+ HStack(spacing: 4) {
+ Image(systemName: "exclamationmark.triangle.fill").foregroundColor(.yellow)
+ Text("UDP only works with SOCKS5 proxy. HTTP proxies do not support UDP.")
+ .font(.caption).foregroundColor(.secondary)
+ }
+ }
+ }
+ if viewModel.proxyConfigs.isEmpty {
+ HStack(spacing: 4) {
+ Image(systemName: "info.circle").foregroundColor(.secondary)
+ Text("No proxy servers configured — add one in Proxy Settings.")
+ .font(.caption).foregroundColor(.secondary)
+ }
}
- .pickerStyle(.segmented)
}
}
}
@@ -453,16 +486,25 @@ struct RuleEditorView: View {
Spacer()
- Button("Save Rule") {
+ Button(isSaving ? "Saving…" : "Save Rule") {
saveRule()
}
.keyboardShortcut(.defaultAction)
.buttonStyle(.borderedProminent)
+ .disabled(isSaving)
}
.padding(.horizontal)
+
+ if !saveError.isEmpty {
+ HStack(spacing: 6) {
+ Image(systemName: "exclamationmark.triangle.fill").foregroundColor(.red)
+ Text(saveError).font(.caption).foregroundColor(.red)
+ }
+ .padding(.horizontal)
+ }
}
.padding()
- .frame(width: 600, height: 550)
+ .frame(width: 600, height: 580)
}
@ViewBuilder
@@ -479,8 +521,12 @@ struct RuleEditorView: View {
}
private func saveRule() {
- guard let session = viewModel.tunnelSession else { return }
-
+ guard let session = viewModel.tunnelSession else {
+ saveError = "Proxy is not running. Start the proxy before saving rules."
+ return
+ }
+ saveError = ""
+ isSaving = true
if let existing = existingRule {
updateExistingRule(session: session, ruleId: existing.id)
} else {
@@ -499,10 +545,14 @@ struct RuleEditorView: View {
action: selectedAction,
enabled: true
) { [self] success, _ in
- if success { dismissOnSuccess() }
+ DispatchQueue.main.async {
+ isSaving = false
+ if success { onSave(); dismiss() }
+ else { saveError = "Extension rejected the update. Check the proxy is running." }
+ }
}
}
-
+
private func addNewRule(session: NETunnelProviderSession) {
RuleManager.addRule(
session: session,
@@ -513,14 +563,11 @@ struct RuleEditorView: View {
action: selectedAction,
enabled: true
) { [self] success, _, _ in
- if success { dismissOnSuccess() }
- }
- }
-
- private func dismissOnSuccess() {
- DispatchQueue.main.async {
- onSave()
- dismiss()
+ DispatchQueue.main.async {
+ isSaving = false
+ if success { onSave(); dismiss() }
+ else { saveError = "Extension rejected the rule. Check the proxy is running." }
+ }
}
}
}
diff --git a/MacOS/ProxyBridge/ProxyBridge/ProxySettingsView.swift b/MacOS/ProxyBridge/ProxyBridge/ProxySettingsView.swift
index ab3ab8c..94734e7 100644
--- a/MacOS/ProxyBridge/ProxyBridge/ProxySettingsView.swift
+++ b/MacOS/ProxyBridge/ProxyBridge/ProxySettingsView.swift
@@ -1,32 +1,49 @@
import SwiftUI
+import Darwin
struct ProxySettingsView: View {
@ObservedObject var viewModel: ProxyBridgeViewModel
@Environment(\.dismiss) private var dismiss
-
- @State private var proxyType = ""
- @State private var proxyHost = ""
- @State private var proxyPort = ""
- @State private var username = ""
- @State private var password = ""
- @State private var validationError = ""
-
- private let proxyTypes = ["http", "socks5"]
- private var isSaveDisabled: Bool {
- proxyType.isEmpty || proxyHost.isEmpty || proxyPort.isEmpty || !validationError.isEmpty
- }
-
+
+ @State private var showAddProxy = false
+ @State private var editingConfig: ProxyBridgeViewModel.ProxyConfig?
+ @State private var deletingConfig: ProxyBridgeViewModel.ProxyConfig?
+ @State private var affectedRulesCount = 0
+ @State private var testResults: [String: String] = [:]
+
var body: some View {
VStack(spacing: 0) {
headerView
- formContent
+ Divider()
+ listContent
Divider()
footerButtons
}
- .frame(width: 600, height: 600)
- .onAppear(perform: loadCurrentSettings)
+ .frame(minWidth: 760, idealWidth: 760, maxWidth: .infinity, minHeight: 440, idealHeight: 480, maxHeight: .infinity)
+ .alert("Delete Proxy?", isPresented: Binding(
+ get: { deletingConfig != nil },
+ set: { if !$0 { deletingConfig = nil } }
+ )) {
+ Button("Delete", role: .destructive) {
+ if let c = deletingConfig { viewModel.removeProxyConfig(c) }
+ deletingConfig = nil
+ }
+ Button("Cancel", role: .cancel) { deletingConfig = nil }
+ } message: {
+ if affectedRulesCount > 0 {
+ Text("\(affectedRulesCount) rule\(affectedRulesCount == 1 ? "" : "s") use this proxy and will be set to Direct.")
+ } else {
+ Text("This proxy will be permanently removed.")
+ }
+ }
+ .sheet(isPresented: $showAddProxy) {
+ ProxyConfigEditorView(viewModel: viewModel, existing: nil)
+ }
+ .sheet(item: $editingConfig) { config in
+ ProxyConfigEditorView(viewModel: viewModel, existing: config)
+ }
}
-
+
private var headerView: some View {
HStack {
Image(systemName: "network")
@@ -36,129 +53,266 @@ struct ProxySettingsView: View {
.font(.title2)
.fontWeight(.semibold)
Spacer()
+ Button(action: { showAddProxy = true }) {
+ HStack(spacing: 4) {
+ Image(systemName: "plus")
+ Text("Add")
+ }
+ .padding(.horizontal, 14)
+ .padding(.vertical, 7)
+ }
+ .buttonStyle(.borderedProminent)
}
.padding()
.background(Color(NSColor.controlBackgroundColor))
}
-
- private var formContent: some View {
- Form {
- Section {
- formPicker(label: "Proxy Type", selection: $proxyType, required: true)
- formTextField(label: "Proxy IP/Domain", placeholder: "127.0.0.1 or proxy.example.com", text: $proxyHost, required: true)
- .onChange(of: proxyHost) { _ in validateInputs() }
- formTextField(label: "Proxy Port", placeholder: "8080", text: $proxyPort, required: true)
- .onChange(of: proxyPort) { _ in validateInputs() }
- formTextField(label: "Username", placeholder: "Leave empty if no auth required", text: $username)
- formSecureField(label: "Password", placeholder: "Leave empty if no auth required", text: $password)
-
- if !validationError.isEmpty {
- HStack {
- Image(systemName: "exclamationmark.triangle.fill")
- .foregroundColor(.red)
- Text(validationError)
- .font(.caption)
- .foregroundColor(.red)
+
+ @ViewBuilder
+ private var listContent: some View {
+ if viewModel.proxyConfigs.isEmpty {
+ Spacer()
+ VStack(spacing: 12) {
+ Image(systemName: "network.slash")
+ .font(.system(size: 48))
+ .foregroundColor(.gray)
+ Text("No proxy servers configured")
+ .font(.title3)
+ .foregroundColor(.gray)
+ Text("Click 'Add' to configure your first proxy server")
+ .font(.subheadline)
+ .foregroundColor(.secondary)
+ }
+ Spacer()
+ } else {
+ Table(viewModel.proxyConfigs) {
+ TableColumn("Type") { config in
+ Text(config.type.uppercased())
+ .foregroundColor(typeColor(config.type))
+ .fontWeight(.semibold)
+ }
+ .width(70)
+
+ TableColumn("Server") { config in
+ Text("\(config.host):\(config.port)")
+ .fontDesign(.monospaced)
+ }
+ .width(min: 180, ideal: 220, max: .infinity)
+
+ TableColumn("Auth") { config in
+ if config.username != nil {
+ Image(systemName: "lock.fill").foregroundColor(.secondary)
+ } else {
+ Text("—").foregroundColor(.secondary)
+ }
+ }
+ .width(40)
+
+ TableColumn("Test") { config in
+ HStack(spacing: 6) {
+ Button(action: { testConnection(config) }) {
+ Label("Test", systemImage: "link")
+ }
+ .buttonStyle(.borderless)
+ if let result = testResults[config.id] {
+ Text(result)
+ .font(.caption2)
+ .foregroundColor(result == "OK" ? .green : .red)
+ }
}
- .padding(.top, 4)
}
-
- HStack {
- Text("* Required fields")
- .font(.caption)
- .foregroundColor(.secondary)
- Spacer()
+ .width(min: 80, ideal: 100)
+
+ TableColumn("") { config in
+ HStack(spacing: 12) {
+ Button(action: { editingConfig = config }) {
+ Image(systemName: "pencil")
+ }
+ .buttonStyle(.borderless)
+ .foregroundColor(.blue)
+ .help("Edit")
+
+ Button(action: { confirmDelete(config) }) {
+ Image(systemName: "trash")
+ }
+ .buttonStyle(.borderless)
+ .foregroundColor(.red)
+ .help("Delete")
+ }
}
- .padding(.top, 4)
+ .width(60)
}
+ .padding()
}
- .formStyle(.grouped)
}
-
+
private var footerButtons: some View {
- HStack(spacing: 12) {
+ HStack {
Spacer()
- Button("Cancel") {
- dismiss()
- }
- .keyboardShortcut(.cancelAction)
-
- Button("Save Changes") {
- saveSettings()
- dismiss()
- }
- .buttonStyle(.borderedProminent)
- .keyboardShortcut(.defaultAction)
- .disabled(isSaveDisabled)
+ Button("Done") { dismiss() }
+ .keyboardShortcut(.defaultAction)
+ .buttonStyle(.borderedProminent)
}
.padding()
.background(Color(NSColor.controlBackgroundColor))
}
-
- @ViewBuilder
- private func formPicker(label: String, selection: Binding<String>, required: Bool = false) -> some View {
- VStack(alignment: .leading, spacing: 8) {
- labelWithRequiredMark(label: label, required: required)
- Picker("Select proxy type", selection: selection) {
- Text("Select proxy type").tag("")
- ForEach(proxyTypes, id: \.self) { type in
- Text(type.uppercased()).tag(type)
- }
+
+ private func confirmDelete(_ config: ProxyBridgeViewModel.ProxyConfig) {
+ affectedRulesCount = viewModel.rulesUsingProxy(id: config.id)
+ deletingConfig = config
+ }
+
+ private func typeColor(_ type: String) -> Color {
+ type.lowercased() == "socks5" ? .cyan : .orange
+ }
+
+ private func testConnection(_ config: ProxyBridgeViewModel.ProxyConfig) {
+ testResults[config.id] = "..."
+ DispatchQueue.global().async {
+ let result = checkTCPReachability(host: config.host, port: config.port)
+ DispatchQueue.main.async {
+ testResults[config.id] = result ? "OK" : "FAIL"
}
- .pickerStyle(.menu)
}
- .padding(.vertical, 8)
}
-
- @ViewBuilder
- private func formTextField(label: String, placeholder: String, text: Binding<String>, required: Bool = false) -> some View {
- VStack(alignment: .leading, spacing: 8) {
- labelWithRequiredMark(label: label, required: required)
- TextField(placeholder, text: text)
- .textFieldStyle(.roundedBorder)
+
+ private func checkTCPReachability(host: String, port: Int) -> Bool {
+ let sock = socket(AF_INET, SOCK_STREAM, 0)
+ guard sock >= 0 else { return false }
+ defer { Darwin.close(sock) }
+
+ var addr = sockaddr_in()
+ addr.sin_family = sa_family_t(AF_INET)
+ addr.sin_port = in_port_t(port).bigEndian
+ inet_pton(AF_INET, host, &addr.sin_addr)
+
+ return withUnsafePointer(to: &addr) { ptr in
+ ptr.withMemoryRebound(to: sockaddr.self, capacity: 1) { sockPtr in
+ connect(sock, sockPtr, socklen_t(MemoryLayout<sockaddr_in>.size)) == 0
+ }
}
- .padding(.vertical, 8)
}
-
- @ViewBuilder
- private func formSecureField(label: String, placeholder: String, text: Binding<String>, required: Bool = false) -> some View {
- VStack(alignment: .leading, spacing: 8) {
- labelWithRequiredMark(label: label, required: required)
- SecureField(placeholder, text: text)
- .textFieldStyle(.roundedBorder)
- }
- .padding(.vertical, 8)
+}
+
+struct ProxyConfigEditorView: View {
+ @ObservedObject var viewModel: ProxyBridgeViewModel
+ var existing: ProxyBridgeViewModel.ProxyConfig?
+ @Environment(\.dismiss) private var dismiss
+
+ @State private var proxyType = "socks5"
+ @State private var proxyHost = ""
+ @State private var proxyPort = ""
+ @State private var username = ""
+ @State private var password = ""
+ @State private var validationError = ""
+
+ private let proxyTypes = ["http", "socks5"]
+ private var isSaveDisabled: Bool {
+ proxyHost.isEmpty || proxyPort.isEmpty || !validationError.isEmpty
}
-
- @ViewBuilder
- private func labelWithRequiredMark(label: String, required: Bool) -> some View {
- HStack {
- Text(label)
- .fontWeight(.medium)
- if required {
- Text("*")
- .foregroundColor(.red)
+
+ var body: some View {
+ VStack(spacing: 0) {
+ HStack {
+ Image(systemName: "network")
+ .font(.title2)
+ .foregroundColor(.accentColor)
+ Text(existing == nil ? "Add Proxy" : "Edit Proxy")
+ .font(.title2)
+ .fontWeight(.semibold)
+ Spacer()
+ }
+ .padding()
+ .background(Color(NSColor.controlBackgroundColor))
+
+ Divider()
+
+ Form {
+ Section {
+ VStack(alignment: .leading, spacing: 8) {
+ HStack { Text("Proxy Type").fontWeight(.medium); Text("*").foregroundColor(.red) }
+ Picker("Select proxy type", selection: $proxyType) {
+ ForEach(proxyTypes, id: \.self) { type in
+ Text(type.uppercased()).tag(type)
+ }
+ }
+ .pickerStyle(.menu)
+ }
+ .padding(.vertical, 8)
+
+ formTextField(label: "Proxy IP/Domain", placeholder: "127.0.0.1 or proxy.example.com", text: $proxyHost, required: true)
+ .onChange(of: proxyHost) { _ in validateInputs() }
+ formTextField(label: "Proxy Port", placeholder: "1080", text: $proxyPort, required: true)
+ .onChange(of: proxyPort) { _ in validateInputs() }
+ formTextField(label: "Username", placeholder: "Leave empty if no auth", text: $username)
+ VStack(alignment: .leading, spacing: 8) {
+ Text("Password").fontWeight(.medium)
+ SecureField("Leave empty if no auth", text: $password)
+ .textFieldStyle(.roundedBorder)
+ }
+ .padding(.vertical, 8)
+
+ if !validationError.isEmpty {
+ HStack {
+ Image(systemName: "exclamationmark.triangle.fill").foregroundColor(.red)
+ Text(validationError).font(.caption).foregroundColor(.red)
+ }
+ .padding(.top, 4)
+ }
+ }
+ }
+ .formStyle(.grouped)
+
+ Divider()
+
+ HStack(spacing: 12) {
+ Spacer()
+ Button("Cancel") { dismiss() }.keyboardShortcut(.cancelAction)
+ Button("Save") { save(); dismiss() }
+ .buttonStyle(.borderedProminent)
+ .keyboardShortcut(.defaultAction)
+ .disabled(isSaveDisabled)
}
+ .padding()
+ .background(Color(NSColor.controlBackgroundColor))
+ }
+ .frame(width: 500, height: 520)
+ .onAppear {
+ if let e = existing {
+ proxyType = e.type
+ proxyHost = e.host
+ proxyPort = String(e.port)
+ username = e.username ?? ""
+ password = e.password ?? ""
+ }
+ validateInputs()
}
}
-
- private func loadCurrentSettings() {
- if let config = viewModel.proxyConfig {
- proxyType = config.type
- proxyHost = config.host
- proxyPort = String(config.port)
- username = config.username ?? ""
- password = config.password ?? ""
+
+ @ViewBuilder
+ private func formTextField(label: String, placeholder: String, text: Binding<String>, required: Bool = false) -> some View {
+ VStack(alignment: .leading, spacing: 8) {
+ HStack {
+ Text(label).fontWeight(.medium)
+ if required { Text("*").foregroundColor(.red) }
+ }
+ TextField(placeholder, text: text).textFieldStyle(.roundedBorder)
}
- validateInputs()
+ .padding(.vertical, 8)
}
-
+
private func validateInputs() {
- if !proxyHost.isEmpty && !isValidHost(proxyHost) {
- validationError = "Invalid proxy IP/domain"
- return
+ if !proxyHost.isEmpty {
+ let validCharsIPv6 = CharacterSet(charactersIn: "0123456789abcdefABCDEF:")
+ let isIPv6 = proxyHost.rangeOfCharacter(from: validCharsIPv6.inverted) == nil && proxyHost.contains(":")
+ let ipv4Parts = proxyHost.split(separator: ".")
+ let isIPv4 = ipv4Parts.count == 4 && ipv4Parts.allSatisfy { Int($0).map { $0 >= 0 && $0 <= 255 } ?? false }
+ let domainPattern = "^([a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?\\.)*[a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?$"
+ let isDomain = NSPredicate(format: "SELF MATCHES %@", domainPattern).evaluate(with: proxyHost) || proxyHost == "localhost"
+ if !isIPv4 && !isIPv6 && !isDomain {
+ validationError = "Invalid proxy IP/domain"
+ return
+ }
}
-
if !proxyPort.isEmpty {
if let port = Int(proxyPort) {
if port < 1 || port > 65535 {
@@ -170,60 +324,23 @@ struct ProxySettingsView: View {
return
}
}
-
validationError = ""
}
-
- private func isValidHost(_ host: String) -> Bool {
- if isValidIPv4(host) {
- return true
- }
-
- if isValidIPv6(host) {
- return true
- }
-
- if isValidDomain(host) {
- return true
- }
-
- return false
- }
-
- private func isValidIPv4(_ ip: String) -> Bool {
- let parts = ip.split(separator: ".")
- guard parts.count == 4 else { return false }
-
- for part in parts {
- guard let num = Int(part), num >= 0 && num <= 255 else {
- return false
- }
- }
- return true
- }
-
- private func isValidIPv6(_ ip: String) -> Bool {
- let validChars = CharacterSet(charactersIn: "0123456789abcdefABCDEF:")
- return ip.rangeOfCharacter(from: validChars.inverted) == nil && ip.contains(":")
- }
-
- private func isValidDomain(_ domain: String) -> Bool {
- let domainPattern = "^([a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?\\.)*[a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?$"
- let predicate = NSPredicate(format: "SELF MATCHES %@", domainPattern)
- return predicate.evaluate(with: domain) || domain == "localhost"
- }
-
- private func saveSettings() {
+
+ private func save() {
guard let port = Int(proxyPort) else { return }
-
let config = ProxyBridgeViewModel.ProxyConfig(
+ id: existing?.id ?? UUID().uuidString,
type: proxyType,
host: proxyHost,
port: port,
username: username.isEmpty ? nil : username,
password: password.isEmpty ? nil : password
)
-
- viewModel.setProxyConfig(config)
+ if existing != nil {
+ viewModel.updateProxyConfig(config)
+ } else {
+ viewModel.addProxyConfig(config)
+ }
}
}
diff --git a/MacOS/ProxyBridge/ProxyBridge/RuleManager.swift b/MacOS/ProxyBridge/ProxyBridge/RuleManager.swift
index 4d0b522..4d5c266 100644
--- a/MacOS/ProxyBridge/ProxyBridge/RuleManager.swift
+++ b/MacOS/ProxyBridge/ProxyBridge/RuleManager.swift
@@ -25,7 +25,8 @@ struct RuleManager {
"enabled": enabled
]
) { success, result in
- if success, let result = result, let ruleId = result["ruleId"] as? UInt32 {
+ if success, let result = result, result["status"] as? String == "ok" {
+ let ruleId = (result["ruleId"] as? NSNumber).map { UInt32($0.intValue) }
completion(true, "Rule added successfully", ruleId)
} else {
completion(false, result?["message"] as? String ?? "Unknown error", nil)
diff --git a/MacOS/ProxyBridge/extension/AppProxyProvider.swift b/MacOS/ProxyBridge/extension/AppProxyProvider.swift
index f83ab92..dd32010 100644
--- a/MacOS/ProxyBridge/extension/AppProxyProvider.swift
+++ b/MacOS/ProxyBridge/extension/AppProxyProvider.swift
@@ -220,7 +220,7 @@ struct ProxyRule: Codable {
class AppProxyProvider: NETransparentProxyProvider {
- // Circular buffer for log queue - avoids O(n) removeFirst() on array
+ // circular buffer for logs, avoids shifting the whole array on every pop
private static let logCapacity = 1000
private var logBuffer: [[String: String]] = Array(repeating: [:], count: AppProxyProvider.logCapacity)
private var logHead = 0 // next read position
@@ -267,7 +267,7 @@ class AppProxyProvider: NETransparentProxyProvider {
let fullPath = String(cString: pathBuffer)
let processName = (fullPath as NSString).lastPathComponent
- // Store in cache (evict all if too large - processes rarely exceed this)
+ // store in cache, evict everything if full — processes rarely hit this
pidCacheLock.lock()
if pidCache.count >= AppProxyProvider.pidCacheMaxSize {
pidCache.removeAll(keepingCapacity: true)
@@ -310,7 +310,7 @@ class AppProxyProvider: NETransparentProxyProvider {
if logCount < AppProxyProvider.logCapacity {
logCount += 1
} else {
- // Buffer full: advance head to overwrite oldest entry
+ // buffer full, bump head to drop the oldest entry
logHead = (logHead + 1) % AppProxyProvider.logCapacity
}
logQueueLock.unlock()
@@ -395,21 +395,6 @@ class AppProxyProvider: NETransparentProxyProvider {
}
completionHandler?(try? JSONSerialization.data(withJSONObject: ["status": "ok"]))
- case "setProxyConfig":
- // Legacy single-config path — store under "default" key
- if let proxyType = message["proxyType"] as? String,
- let proxyHost = message["proxyHost"] as? String,
- let proxyPort = message["proxyPort"] as? Int {
- proxyLock.lock()
- storedProxyConfigs["default"] = StoredProxyConfig(
- type: proxyType, host: proxyHost, port: proxyPort,
- username: message["proxyUsername"] as? String,
- password: message["proxyPassword"] as? String
- )
- proxyLock.unlock()
- log("Proxy config (legacy): \(proxyType)://\(proxyHost):\(proxyPort)")
- }
- completionHandler?(try? JSONSerialization.data(withJSONObject: ["status": "ok"]))
case "addRule":
if let ruleData = try? JSONSerialization.data(withJSONObject: message),
@@ -546,7 +531,7 @@ class AppProxyProvider: NETransparentProxyProvider {
} else if let udpFlow = flow as? NEAppProxyUDPFlow {
return handleUDPFlow(udpFlow)
}
- // Let all other traffic pass through directly
+ // unhandled flow types just pass through
return false
}
@@ -599,9 +584,8 @@ class AppProxyProvider: NETransparentProxyProvider {
flow.closeWriteWithError(nil)
return true
default:
- // action is a proxy config UUID; fall back to first config for legacy "PROXY" value
proxyLock.lock()
- let config = storedProxyConfigs[action] ?? storedProxyConfigs.values.first
+ let config = storedProxyConfigs[action]
proxyLock.unlock()
guard let config = config else { return false }
proxyTCPFlow(flow, destination: destination, port: portNum, config: config)
@@ -628,37 +612,36 @@ class AppProxyProvider: NETransparentProxyProvider {
}
proxyLock.lock()
- let hasSOCKS5Proxy = (proxyHost != nil && proxyPort != nil && proxyType?.lowercased() == "socks5")
- let socksHost = self.proxyHost
- let socksPort = self.proxyPort
+ let hasAnySocks5 = storedProxyConfigs.values.contains { $0.type.lowercased() == "socks5" }
proxyLock.unlock()
-
- if !hasSOCKS5Proxy {
+
+ if !hasAnySocks5 {
return false
}
-
+
let matchedRule = findMatchingRule(bundleId: processPath, processName: processName, destination: "", port: 0, connectionProtocol: .udp, checkIpPort: false)
-
+
if let rule = matchedRule {
- switch rule.action {
- case .direct:
+ let action = rule.action
+ switch action {
+ case "DIRECT":
sendLogToApp(protocol: "UDP", process: displayName, destination: "unknown", port: "unknown", proxy: "Direct")
return false
- case .block:
+ case "BLOCK":
sendLogToApp(protocol: "UDP", process: displayName, destination: "unknown", port: "unknown", proxy: "BLOCK")
return true
- case .proxy:
+ default:
+ proxyLock.lock()
+ let matched = storedProxyConfigs[action]
+ proxyLock.unlock()
+ guard let socks5Config = matched, socks5Config.type.lowercased() == "socks5" else { return false }
flow.open(withLocalEndpoint: nil) { [weak self] error in
guard let self = self else { return }
-
if let error = error {
self.log("Failed to open UDP flow: \(error.localizedDescription)", level: "ERROR")
return
}
-
- if let host = socksHost, let port = socksPort {
- self.proxyUDPFlowViaSOCKS5(flow, processPath: processPath, socksHost: host, socksPort: port)
- }
+ self.proxyUDPFlowViaSOCKS5(flow, processPath: processPath, socksHost: socks5Config.host, socksPort: socks5Config.port)
}
return true
}
@@ -946,12 +929,12 @@ class AppProxyProvider: NETransparentProxyProvider {
var destPort: UInt16 = 0
if atyp == 0x01 {
- // bytes 4-9: 4-byte IPv4 + 2-byte port (covered by count > 10)
+ // ipv4 is 4 bytes + 2 port, already covered by count > 10
destHost = "\(datagram[4]).\(datagram[5]).\(datagram[6]).\(datagram[7])"
destPort = (UInt16(datagram[8]) << 8) | UInt16(datagram[9])
headerLen += 6
} else if atyp == 0x04 {
- // bytes 4-21: 16-byte IPv6 + 2-byte port
+ // ipv6 needs 16 bytes + 2 port
guard datagram.count >= 22 else { return nil }
var ipv6Parts: [String] = []
for i in 0..<8 {
@@ -963,7 +946,7 @@ class AppProxyProvider: NETransparentProxyProvider {
destPort = (UInt16(datagram[20]) << 8) | UInt16(datagram[21])
headerLen += 18
} else if atyp == 0x03 {
- // byte 4: domain length, bytes 5..<5+len: domain, then 2-byte port
+ // byte 4 is the domain length, then the domain, then 2 port bytes
guard datagram.count >= 6 else { return nil }
let domainLen = Int(datagram[4])
guard datagram.count >= 5 + domainLen + 2 else { return nil }
@@ -980,32 +963,19 @@ class AppProxyProvider: NETransparentProxyProvider {
return (Data(payload), destHost, destPort)
}
- private func proxyTCPFlow(_ flow: NEAppProxyTCPFlow, destination: String, port: UInt16) {
- proxyLock.lock()
- guard let proxyHost = self.proxyHost,
- let proxyPort = self.proxyPort,
- let proxyType = self.proxyType else {
- proxyLock.unlock()
- log("Proxy config missing", level: "ERROR")
- flow.closeReadWithError(nil)
- flow.closeWriteWithError(nil)
- return
- }
- let username = self.proxyUsername
- let password = self.proxyPassword
- proxyLock.unlock()
-
- let proxyEndpoint = NWHostEndpoint(hostname: proxyHost, port: String(proxyPort))
+ private func proxyTCPFlow(_ flow: NEAppProxyTCPFlow, destination: String, port: UInt16, config: StoredProxyConfig) {
+ let proxyEndpoint = NWHostEndpoint(hostname: config.host, port: String(config.port))
let proxyConnection = createTCPConnection(to: proxyEndpoint, enableTLS: false, tlsParameters: nil, delegate: nil)
-
+
proxyConnection.addObserver(self, forKeyPath: "state", options: .new, context: nil)
-
- if proxyType.lowercased() == "socks5" {
- handleSOCKS5Proxy(clientFlow: flow, proxyConnection: proxyConnection, destination: destination, port: port, username: username, password: password)
- } else if proxyType.lowercased() == "http" {
- handleHTTPProxy(clientFlow: flow, proxyConnection: proxyConnection, destination: destination, port: port, username: username, password: password)
- } else {
- log("Unsupported proxy type: \(proxyType)", level: "ERROR")
+
+ switch config.type.lowercased() {
+ case "socks5":
+ handleSOCKS5Proxy(clientFlow: flow, proxyConnection: proxyConnection, destination: destination, port: port, username: config.username, password: config.password)
+ case "http":
+ handleHTTPProxy(clientFlow: flow, proxyConnection: proxyConnection, destination: destination, port: port, username: config.username, password: config.password)
+ default:
+ log("unsupported proxy type: \(config.type)", level: "ERROR")
flow.closeReadWithError(nil)
flow.closeWriteWithError(nil)
}
@@ -1319,7 +1289,7 @@ class AppProxyProvider: NETransparentProxyProvider {
for rule in currentRules {
guard rule.enabled else { continue }
- // check protocol firstß
+ // check protocol first
if rule.ruleProtocol != .both && rule.ruleProtocol != connectionProtocol {
continue
}
@@ -1333,7 +1303,7 @@ class AppProxyProvider: NETransparentProxyProvider {
let hasPortFilter = (rule.targetPorts != "*" && !rule.targetPorts.isEmpty)
if hasIpFilter || hasPortFilter {
- // wildcard with filters - check immediately
+ // wildcard with filters, check immediately
if checkIpPort {
if rule.matchesIP(destination) && rule.matchesPort(port) {
return rule
@@ -1344,28 +1314,28 @@ class AppProxyProvider: NETransparentProxyProvider {
continue
}
- // Fully wildcard rule - defer it (save first one only)
+ // pure wildcard, save it for later — only the first one
if wildcardRule == nil {
wildcardRule = rule
}
continue
}
- // Specific process rule - check if it matches
+ // specific process rule, see if it matches
if rule.matchesProcess(bundleId: bundleId, processName: processName) {
- // Process matched! Check IP and port filters
+ // process matched, now check ip and port
if checkIpPort {
if rule.matchesIP(destination) && rule.matchesPort(port) {
return rule
}
} else {
- // For UDP without destination info, match on process only
+ // no destination on udp, match on process alone
return rule
}
}
}
-
- // No specific rule matched, use deferred wildcard if available
+
+ // nothing matched, fall back to wildcard if we have one
if let wildcardRule = wildcardRule {
return wildcardRule
}