Skip to content

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

updated GUI

Sourav Kalal7bb90fd5a5c6
diff --git a/MacOS/ProxyBridge/ProxyBridge/ContentView.swift b/MacOS/ProxyBridge/ProxyBridge/ContentView.swift
index 5c5fe4b..03ae036 100644
--- a/MacOS/ProxyBridge/ProxyBridge/ContentView.swift
+++ b/MacOS/ProxyBridge/ProxyBridge/ContentView.swift
@@ -1,10 +1,3 @@
-//
-// ContentView.swift
-// ProxyBridge - GUI
-//
-// Created by sourav kalal on 14/11/25.
-//
-
import SwiftUI
struct ContentView: View {
@@ -15,56 +8,56 @@ struct ContentView: View {
var body: some View {
VStack(spacing: 0) {
- // Header
- HStack {
- Text("ProxyBridge")
- .font(.headline)
- .padding(.leading)
-
- Spacer()
- }
- .frame(height: 44)
- .background(Color(NSColor.windowBackgroundColor))
-
+ headerView
Divider()
-
- // Tab selector
- HStack(spacing: 0) {
- TabButton(
- title: "Connections",
- isSelected: selectedTab == 0,
- action: { selectedTab = 0 }
- )
-
- TabButton(
- title: "Activity Logs",
- isSelected: selectedTab == 1,
- action: { selectedTab = 1 }
- )
-
- Spacer()
- }
- .frame(height: 40)
- .background(Color(NSColor.controlBackgroundColor))
-
+ tabSelector
Divider()
-
- // Content
+ contentView
+ }
+ .frame(minWidth: 800, minHeight: 600)
+ }
+
+ private var headerView: some View {
+ HStack {
+ Text("ProxyBridge")
+ .font(.headline)
+ .padding(.leading)
+ Spacer()
+ }
+ .frame(height: 44)
+ .background(Color(NSColor.windowBackgroundColor))
+ }
+
+ private var tabSelector: some View {
+ HStack(spacing: 0) {
+ TabButton(title: "Connections", isSelected: selectedTab == 0) {
+ selectedTab = 0
+ }
+ TabButton(title: "Activity Logs", isSelected: selectedTab == 1) {
+ selectedTab = 1
+ }
+ Spacer()
+ }
+ .frame(height: 40)
+ .background(Color(NSColor.controlBackgroundColor))
+ }
+
+ private var contentView: some View {
+ Group {
if selectedTab == 0 {
ConnectionsView(
connections: filteredConnections,
searchText: $connectionSearchText,
- onClear: { viewModel.clearConnections() }
+ onClear: viewModel.clearConnections
)
} else {
ActivityLogsView(
logs: filteredActivityLogs,
searchText: $activitySearchText,
- onClear: { viewModel.clearActivityLogs() }
+ onClear: viewModel.clearActivityLogs
)
}
}
- .frame(minWidth: 800, minHeight: 600)
}
private var filteredConnections: [ProxyBridgeViewModel.ConnectionLog] {
@@ -113,68 +106,66 @@ struct ConnectionsView: View {
var body: some View {
VStack(spacing: 0) {
- // Search bar
- HStack {
- Image(systemName: "magnifyingglass")
- .foregroundColor(.gray)
- TextField("Search connections...", text: $searchText)
- .textFieldStyle(.plain)
- Spacer()
- Button("Clear") {
- onClear()
- }
- }
- .padding()
- .background(Color(NSColor.controlBackgroundColor))
-
+ searchBar
Divider()
-
- // Connections list
- ScrollViewReader { proxy in
- ScrollView {
- LazyVStack(alignment: .leading, spacing: 4) {
- ForEach(connections) { connection in
- HStack(spacing: 12) {
- Text("[\(connection.timestamp)]")
- .foregroundColor(.gray)
- .font(.system(.body, design: .monospaced))
-
- Text("[\(connection.connectionProtocol)]")
- .foregroundColor(.blue)
- .font(.system(.body, design: .monospaced))
-
- Text(connection.process)
- .foregroundColor(.green)
- .font(.system(.body, design: .monospaced))
-
- Text("→")
- .foregroundColor(.gray)
-
- Text("\(connection.destination):\(connection.port)")
- .foregroundColor(.orange)
- .font(.system(.body, design: .monospaced))
-
- Text("→")
- .foregroundColor(.gray)
-
- Text(connection.proxy)
- .foregroundColor(connection.proxy == "Direct" ? .gray : .purple)
- .font(.system(.body, design: .monospaced))
- .fontWeight(.medium)
- }
- .padding(.horizontal)
- .padding(.vertical, 4)
+ connectionsList
+ }
+ }
+
+ private var searchBar: some View {
+ HStack {
+ Image(systemName: "magnifyingglass")
+ .foregroundColor(.gray)
+ TextField("Search connections...", text: $searchText)
+ .textFieldStyle(.plain)
+ Spacer()
+ Button("Clear", action: onClear)
+ }
+ .padding()
+ .background(Color(NSColor.controlBackgroundColor))
+ }
+
+ private var connectionsList: some View {
+ ScrollViewReader { proxy in
+ ScrollView {
+ LazyVStack(alignment: .leading, spacing: 4) {
+ ForEach(connections) { connection in
+ connectionRow(connection)
.id(connection.id)
- }
- }
- .onChange(of: connections.count) { _ in
- if let last = connections.last {
- withAnimation {
- proxy.scrollTo(last.id, anchor: .bottom)
- }
- }
}
}
+ .onChange(of: connections.count) { _ in
+ scrollToLast(proxy: proxy)
+ }
+ }
+ }
+ }
+
+ private func connectionRow(_ connection: ProxyBridgeViewModel.ConnectionLog) -> some View {
+ HStack(spacing: 12) {
+ monoText("[\(connection.timestamp)]", color: .gray)
+ monoText("[\(connection.connectionProtocol)]", color: .blue)
+ monoText(connection.process, color: .green)
+ monoText("→", color: .gray)
+ monoText("\(connection.destination):\(connection.port)", color: .orange)
+ monoText("→", color: .gray)
+ monoText(connection.proxy, color: connection.proxy == "Direct" ? .gray : .purple)
+ .fontWeight(.medium)
+ }
+ .padding(.horizontal)
+ .padding(.vertical, 4)
+ }
+
+ private func monoText(_ text: String, color: Color) -> some View {
+ Text(text)
+ .foregroundColor(color)
+ .font(.system(.body, design: .monospaced))
+ }
+
+ private func scrollToLast(proxy: ScrollViewProxy) {
+ if let last = connections.last {
+ withAnimation {
+ proxy.scrollTo(last.id, anchor: .bottom)
}
}
}
@@ -187,52 +178,61 @@ struct ActivityLogsView: View {
var body: some View {
VStack(spacing: 0) {
- // Search bar
- HStack {
- Image(systemName: "magnifyingglass")
- .foregroundColor(.gray)
- TextField("Search logs...", text: $searchText)
- .textFieldStyle(.plain)
- Spacer()
- Button("Clear") {
- onClear()
- }
- }
- .padding()
- .background(Color(NSColor.controlBackgroundColor))
-
+ searchBar
Divider()
-
- // Logs list
- ScrollViewReader { proxy in
- ScrollView {
- LazyVStack(alignment: .leading, spacing: 4) {
- ForEach(logs) { log in
- HStack(spacing: 12) {
- Text("[\(log.timestamp)]")
- .foregroundColor(.gray)
- .font(.system(.body, design: .monospaced))
-
- Text("[\(log.level)]")
- .foregroundColor(log.level == "ERROR" ? .red : .blue)
- .font(.system(.body, design: .monospaced))
-
- Text(log.message)
- .font(.system(.body, design: .monospaced))
- }
- .padding(.horizontal)
- .padding(.vertical, 4)
+ logsList
+ }
+ }
+
+ private var searchBar: some View {
+ HStack {
+ Image(systemName: "magnifyingglass")
+ .foregroundColor(.gray)
+ TextField("Search logs...", text: $searchText)
+ .textFieldStyle(.plain)
+ Spacer()
+ Button("Clear", action: onClear)
+ }
+ .padding()
+ .background(Color(NSColor.controlBackgroundColor))
+ }
+
+ private var logsList: some View {
+ ScrollViewReader { proxy in
+ ScrollView {
+ LazyVStack(alignment: .leading, spacing: 4) {
+ ForEach(logs) { log in
+ logRow(log)
.id(log.id)
- }
- }
- .onChange(of: logs.count) { _ in
- if let last = logs.last {
- withAnimation {
- proxy.scrollTo(last.id, anchor: .bottom)
- }
- }
}
}
+ .onChange(of: logs.count) { _ in
+ scrollToLast(proxy: proxy)
+ }
+ }
+ }
+ }
+
+ private func logRow(_ log: ProxyBridgeViewModel.ActivityLog) -> some View {
+ HStack(spacing: 12) {
+ monoText("[\(log.timestamp)]", color: .gray)
+ monoText("[\(log.level)]", color: log.level == "ERROR" ? .red : .blue)
+ monoText(log.message, color: .primary)
+ }
+ .padding(.horizontal)
+ .padding(.vertical, 4)
+ }
+
+ private func monoText(_ text: String, color: Color) -> some View {
+ Text(text)
+ .foregroundColor(color)
+ .font(.system(.body, design: .monospaced))
+ }
+
+ private func scrollToLast(proxy: ScrollViewProxy) {
+ if let last = logs.last {
+ withAnimation {
+ proxy.scrollTo(last.id, anchor: .bottom)
}
}
}
diff --git a/MacOS/ProxyBridge/ProxyBridge/ProxyBridgeGUI.swift b/MacOS/ProxyBridge/ProxyBridge/ProxyBridgeGUI.swift
index 123bd6f..7369b65 100644
--- a/MacOS/ProxyBridge/ProxyBridge/ProxyBridgeGUI.swift
+++ b/MacOS/ProxyBridge/ProxyBridge/ProxyBridgeGUI.swift
@@ -1,10 +1,3 @@
-//
-// ProxyBridgeGUI.swift
-// ProxyBridge - GUI App
-//
-// Created by sourav kalal on 14/11/25.
-//
-
import SwiftUI
@main
@@ -12,10 +5,6 @@ struct ProxyBridgeGUIApp: App {
@StateObject private var viewModel = ProxyBridgeViewModel()
@NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
- init() {
- // Set the viewModel reference for AppDelegate
- }
-
var body: some Scene {
WindowGroup {
ContentView(viewModel: viewModel)
@@ -71,32 +60,34 @@ class AppDelegate: NSObject, NSApplicationDelegate {
}
@objc func openProxySettings() {
- if let window = NSApplication.shared.windows.first(where: { $0.title == "Proxy Settings" }) {
- window.makeKeyAndOrderFront(nil)
- } else {
- // Open new window
- let controller = NSHostingController(rootView: ProxySettingsView(viewModel: AppDelegate.viewModel!))
- let window = NSWindow(contentViewController: controller)
- window.title = "Proxy Settings"
- window.setContentSize(NSSize(width: 600, height: 500))
- window.styleMask = [.titled, .closable]
- window.center()
- window.makeKeyAndOrderFront(nil)
+ openWindow(title: "Proxy Settings", size: NSSize(width: 600, height: 500)) {
+ ProxySettingsView(viewModel: AppDelegate.viewModel!)
}
}
@objc func openProxyRules() {
- if let window = NSApplication.shared.windows.first(where: { $0.title == "Proxy Rules" }) {
+ openWindow(title: "Proxy Rules", size: NSSize(width: 1000, height: 600), resizable: true) {
+ ProxyRulesView(viewModel: AppDelegate.viewModel!)
+ }
+ }
+
+ private func openWindow<Content: View>(
+ title: String,
+ size: NSSize,
+ resizable: Bool = false,
+ @ViewBuilder content: () -> Content
+ ) {
+ if let window = NSApplication.shared.windows.first(where: { $0.title == title }) {
window.makeKeyAndOrderFront(nil)
} else {
- // Open new window
- let controller = NSHostingController(rootView: ProxyRulesView(viewModel: AppDelegate.viewModel!))
+ let controller = NSHostingController(rootView: content())
let window = NSWindow(contentViewController: controller)
- window.title = "Proxy Rules"
- window.setContentSize(NSSize(width: 1000, height: 600))
- window.styleMask = [.titled, .closable, .resizable]
+ window.title = title
+ window.setContentSize(size)
+ window.styleMask = resizable ? [.titled, .closable, .resizable] : [.titled, .closable]
window.center()
window.makeKeyAndOrderFront(nil)
}
}
}
+
diff --git a/MacOS/ProxyBridge/ProxyBridge/ProxyBridgeViewModel.swift b/MacOS/ProxyBridge/ProxyBridge/ProxyBridgeViewModel.swift
index 02515ab..03908ee 100644
--- a/MacOS/ProxyBridge/ProxyBridge/ProxyBridgeViewModel.swift
+++ b/MacOS/ProxyBridge/ProxyBridge/ProxyBridgeViewModel.swift
@@ -1,10 +1,3 @@
-//
-// ProxyBridgeViewModel.swift
-// ProxyBridge - GUI ViewModel
-//
-// Created by sourav kalal on 14/11/25.
-//
-
import Foundation
import NetworkExtension
import SystemExtensions
@@ -19,6 +12,10 @@ class ProxyBridgeViewModel: NSObject, ObservableObject {
private var logTimer: Timer?
private(set) var proxyConfig: ProxyConfig?
+ private let maxLogEntries = 1000
+ private let logPollingInterval = 0.1
+ private let extensionIdentifier = "com.interceptsuite.ProxyBridge.extension"
+
struct ProxyConfig {
let type: String
let host: String
@@ -86,9 +83,8 @@ class ProxyBridgeViewModel: NSObject, ObservableObject {
}
private func installAndStartProxy() {
- print("Installing system extension")
let request = OSSystemExtensionRequest.activationRequest(
- forExtensionWithIdentifier: "com.interceptsuite.ProxyBridge.extension",
+ forExtensionWithIdentifier: extensionIdentifier,
queue: .main
)
request.delegate = self
@@ -105,12 +101,11 @@ class ProxyBridgeViewModel: NSObject, ObservableObject {
}
let manager = managers?.first ?? NETransparentProxyManager()
-
manager.localizedDescription = "ProxyBridge Transparent Proxy"
manager.isEnabled = true
let providerProtocol = NETunnelProviderProtocol()
- providerProtocol.providerBundleIdentifier = "com.interceptsuite.ProxyBridge.extension"
+ providerProtocol.providerBundleIdentifier = self.extensionIdentifier
providerProtocol.serverAddress = "ProxyBridge"
manager.protocolConfiguration = providerProtocol
@@ -121,28 +116,32 @@ class ProxyBridgeViewModel: NSObject, ObservableObject {
}
self.addLog("INFO", "Configuration saved")
+ self.reloadAndStartTunnel(manager: manager)
+ }
+ }
+ }
+
+ private func reloadAndStartTunnel(manager: NETransparentProxyManager) {
+ manager.loadFromPreferences { [weak self] loadError in
+ guard let self = self else { return }
+
+ if let loadError = loadError {
+ self.addLog("ERROR", "Failed to reload preferences: \(loadError.localizedDescription)")
+ return
+ }
+
+ do {
+ try (manager.connection as? NETunnelProviderSession)?.startTunnel()
+ self.isProxyActive = true
+ self.addLog("INFO", "Proxy tunnel started")
- manager.loadFromPreferences { loadError in
- if let loadError = loadError {
- self.addLog("ERROR", "Failed to reload preferences: \(loadError.localizedDescription)")
- return
- }
-
- do {
- try (manager.connection as? NETunnelProviderSession)?.startTunnel()
- self.isProxyActive = true
- self.addLog("INFO", "Proxy tunnel started")
-
- if let session = manager.connection as? NETunnelProviderSession {
- // Wait a bit for extension to initialize
- DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
- self.setupLogPolling(session: session)
- }
- }
- } catch {
- self.addLog("ERROR", "Failed to start tunnel: \(error.localizedDescription)")
+ if let session = manager.connection as? NETunnelProviderSession {
+ DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
+ self.setupLogPolling(session: session)
}
}
+ } catch {
+ self.addLog("ERROR", "Failed to start tunnel: \(error.localizedDescription)")
}
}
}
@@ -165,8 +164,12 @@ class ProxyBridgeViewModel: NSObject, ObservableObject {
tunnelSession = session
DispatchQueue.main.async { [weak self] in
- self?.logTimer?.invalidate()
- self?.logTimer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { [weak self] _ in
+ guard let self = self else { return }
+ self.logTimer?.invalidate()
+ self.logTimer = Timer.scheduledTimer(
+ withTimeInterval: self.logPollingInterval,
+ repeats: true
+ ) { [weak self] _ in
self?.pollLogs()
}
}
@@ -186,48 +189,58 @@ class ProxyBridgeViewModel: NSObject, ObservableObject {
}
DispatchQueue.main.async {
- // Connection log
- if let type = log["type"], type == "connection",
- let proto = log["protocol"],
- let process = log["process"],
- let dest = log["destination"],
- let port = log["port"],
- let proxy = log["proxy"] {
-
- let connectionLog = ConnectionLog(
- timestamp: self.getCurrentTimestamp(),
- connectionProtocol: proto,
- process: process,
- destination: dest,
- port: port,
- proxy: proxy
- )
- self.connections.append(connectionLog)
-
- if self.connections.count > 1000 {
- self.connections.removeFirst()
- }
- }
- // Activity log
- else if let timestamp = log["timestamp"],
- let level = log["level"],
- let message = log["message"] {
-
- let activityLog = ActivityLog(
- timestamp: timestamp,
- level: level,
- message: message
- )
- self.activityLogs.append(activityLog)
-
- if self.activityLogs.count > 1000 {
- self.activityLogs.removeFirst()
- }
+ if log["type"] == "connection" {
+ self.handleConnectionLog(log)
+ } else {
+ self.handleActivityLog(log)
}
}
}
}
+ private func handleConnectionLog(_ log: [String: String]) {
+ guard let proto = log["protocol"],
+ let process = log["process"],
+ let dest = log["destination"],
+ let port = log["port"],
+ let proxy = log["proxy"] else {
+ return
+ }
+
+ let connectionLog = ConnectionLog(
+ timestamp: getCurrentTimestamp(),
+ connectionProtocol: proto,
+ process: process,
+ destination: dest,
+ port: port,
+ proxy: proxy
+ )
+ connections.append(connectionLog)
+
+ if connections.count > maxLogEntries {
+ connections.removeFirst()
+ }
+ }
+
+ private func handleActivityLog(_ log: [String: String]) {
+ guard let timestamp = log["timestamp"],
+ let level = log["level"],
+ let message = log["message"] else {
+ return
+ }
+
+ let activityLog = ActivityLog(
+ timestamp: timestamp,
+ level: level,
+ message: message
+ )
+ activityLogs.append(activityLog)
+
+ if activityLogs.count > maxLogEntries {
+ activityLogs.removeFirst()
+ }
+ }
+
func setProxyConfig(_ config: ProxyConfig) {
proxyConfig = config
saveProxyConfig(config)
@@ -283,7 +296,7 @@ class ProxyBridgeViewModel: NSObject, ObservableObject {
)
activityLogs.append(log)
- if activityLogs.count > 1000 {
+ if activityLogs.count > maxLogEntries {
activityLogs.removeFirst()
}
}
diff --git a/MacOS/ProxyBridge/ProxyBridge/ProxyRulesView.swift b/MacOS/ProxyBridge/ProxyBridge/ProxyRulesView.swift
index 26dfb8c..43cdbae 100644
--- a/MacOS/ProxyBridge/ProxyBridge/ProxyRulesView.swift
+++ b/MacOS/ProxyBridge/ProxyBridge/ProxyRulesView.swift
@@ -1,10 +1,3 @@
-//
-// ProxyRulesView.swift
-// ProxyBridge
-//
-// Created by sourav kalal on 14/11/25.
-//
-
import SwiftUI
import NetworkExtension
@@ -16,8 +9,6 @@ struct ProxyRule: Identifiable {
let ruleProtocol: String
let action: String
var enabled: Bool
-
- var ruleId: UInt32 { id }
}
struct ProxyRulesView: View {
@@ -168,44 +159,40 @@ struct ProxyRulesView: View {
guard let session = viewModel.tunnelSession else { return }
isLoading = true
- RuleManager.listRules(session: session) { success, rulesList in
+ RuleManager.listRules(session: session) { [self] success, rulesList in
DispatchQueue.main.async {
isLoading = false
if success {
- rules = rulesList.map { dict in
- ProxyRule(
- id: dict["ruleId"] as? UInt32 ?? 0,
- processNames: dict["processNames"] as? String ?? "",
- targetHosts: dict["targetHosts"] as? String ?? "",
- targetPorts: dict["targetPorts"] as? String ?? "",
- ruleProtocol: dict["protocol"] as? String ?? "BOTH",
- action: dict["action"] as? String ?? "DIRECT",
- enabled: dict["enabled"] as? Bool ?? true
- )
- }
+ rules = rulesList.map(mapToProxyRule)
}
}
}
}
+ private func mapToProxyRule(_ dict: [String: Any]) -> ProxyRule {
+ ProxyRule(
+ id: dict["ruleId"] as? UInt32 ?? 0,
+ processNames: dict["processNames"] as? String ?? "",
+ targetHosts: dict["targetHosts"] as? String ?? "",
+ targetPorts: dict["targetPorts"] as? String ?? "",
+ ruleProtocol: dict["protocol"] as? String ?? "BOTH",
+ action: dict["action"] as? String ?? "DIRECT",
+ enabled: dict["enabled"] as? Bool ?? true
+ )
+ }
+
private func deleteRule(_ rule: ProxyRule) {
guard let session = viewModel.tunnelSession else { return }
- RuleManager.removeRule(session: session, ruleId: rule.id) { success, message in
- if success {
- loadRules()
- }
+ RuleManager.removeRule(session: session, ruleId: rule.id) { [self] success, _ in
+ if success { loadRules() }
}
}
private func toggleRule(_ rule: ProxyRule, enabled: Bool) {
guard let session = viewModel.tunnelSession else { return }
- RuleManager.toggleRule(
- session: session,
- ruleId: rule.id,
- enabled: enabled
- ) { _, _ in
+ RuleManager.toggleRule(session: session, ruleId: rule.id, enabled: enabled) { [self] _, _ in
loadRules()
}
}
@@ -224,6 +211,8 @@ struct RuleEditorView: View {
@State private var selectedProtocol: String
@State private var selectedAction: String
+ private var isEditMode: Bool { existingRule != nil }
+
init(viewModel: ProxyBridgeViewModel, existingRule: ProxyRule? = nil, onSave: @escaping () -> Void) {
self.viewModel = viewModel
self.existingRule = existingRule
@@ -238,41 +227,32 @@ struct RuleEditorView: View {
var body: some View {
VStack(spacing: 20) {
- Text(existingRule == nil ? "Add Rule" : "Edit Rule")
+ Text(isEditMode ? "Edit Rule" : "Add Rule")
.font(.title2)
.fontWeight(.semibold)
Form {
Section {
- VStack(alignment: .leading, spacing: 8) {
- Text("Applications")
- .fontWeight(.medium)
- TextField("*", text: $processNames)
- .textFieldStyle(.roundedBorder)
- Text("Example: iexplore.exe; \"C:\\some app.exe\"; fire*.exe; *.bin")
- .font(.caption)
- .foregroundColor(.secondary)
- }
+ formField(
+ label: "Applications",
+ placeholder: "*",
+ text: $processNames,
+ hint: "Example: iexplore.exe; \"C:\\some app.exe\"; fire*.exe; *.bin"
+ )
- VStack(alignment: .leading, spacing: 8) {
- Text("Target hosts")
- .fontWeight(.medium)
- TextField("*", text: $targetHosts)
- .textFieldStyle(.roundedBorder)
- Text("Example: 127.0.0.1; *.example.com; 192.168.1.*; 10.1.0.0-10.5.255.255")
- .font(.caption)
- .foregroundColor(.secondary)
- }
+ formField(
+ label: "Target hosts",
+ placeholder: "*",
+ text: $targetHosts,
+ hint: "Example: 127.0.0.1; *.example.com; 192.168.1.*; 10.1.0.0-10.5.255.255"
+ )
- VStack(alignment: .leading, spacing: 8) {
- Text("Target ports")
- .fontWeight(.medium)
- TextField("*", text: $targetPorts)
- .textFieldStyle(.roundedBorder)
- Text("Example: 80; 8000-9000; 3128")
- .font(.caption)
- .foregroundColor(.secondary)
- }
+ formField(
+ label: "Target ports",
+ placeholder: "*",
+ text: $targetPorts,
+ hint: "Example: 80; 8000-9000; 3128"
+ )
VStack(alignment: .leading, spacing: 8) {
Text("Protocol")
@@ -319,45 +299,62 @@ struct RuleEditorView: View {
.frame(width: 600, height: 550)
}
+ @ViewBuilder
+ private func formField(label: String, placeholder: String, text: Binding<String>, hint: String) -> some View {
+ VStack(alignment: .leading, spacing: 8) {
+ Text(label)
+ .fontWeight(.medium)
+ TextField(placeholder, text: text)
+ .textFieldStyle(.roundedBorder)
+ Text(hint)
+ .font(.caption)
+ .foregroundColor(.secondary)
+ }
+ }
+
private func saveRule() {
guard let session = viewModel.tunnelSession else { return }
if let existing = existingRule {
- // Edit existing rule - use update
- RuleManager.updateRule(
- session: session,
- ruleId: existing.id,
- processNames: processNames,
- targetHosts: targetHosts,
- targetPorts: targetPorts,
- protocol: selectedProtocol,
- action: selectedAction,
- enabled: true
- ) { success, _ in
- if success {
- DispatchQueue.main.async {
- onSave()
- dismiss()
- }
- }
- }
+ updateExistingRule(session: session, ruleId: existing.id)
} else {
- RuleManager.addRule(
- session: session,
- processNames: processNames,
- targetHosts: targetHosts,
- targetPorts: targetPorts,
- protocol: selectedProtocol,
- action: selectedAction,
- enabled: true
- ) { success, _, _ in
- if success {
- DispatchQueue.main.async {
- onSave()
- dismiss()
- }
- }
- }
+ addNewRule(session: session)
+ }
+ }
+
+ private func updateExistingRule(session: NETunnelProviderSession, ruleId: UInt32) {
+ RuleManager.updateRule(
+ session: session,
+ ruleId: ruleId,
+ processNames: processNames,
+ targetHosts: targetHosts,
+ targetPorts: targetPorts,
+ protocol: selectedProtocol,
+ action: selectedAction,
+ enabled: true
+ ) { [self] success, _ in
+ if success { dismissOnSuccess() }
+ }
+ }
+
+ private func addNewRule(session: NETunnelProviderSession) {
+ RuleManager.addRule(
+ session: session,
+ processNames: processNames,
+ targetHosts: targetHosts,
+ targetPorts: targetPorts,
+ protocol: selectedProtocol,
+ action: selectedAction,
+ enabled: true
+ ) { [self] success, _, _ in
+ if success { dismissOnSuccess() }
+ }
+ }
+
+ private func dismissOnSuccess() {
+ DispatchQueue.main.async {
+ onSave()
+ dismiss()
}
}
}
diff --git a/MacOS/ProxyBridge/ProxyBridge/ProxySettingsView.swift b/MacOS/ProxyBridge/ProxyBridge/ProxySettingsView.swift
index c74ad6c..f8b3172 100644
--- a/MacOS/ProxyBridge/ProxyBridge/ProxySettingsView.swift
+++ b/MacOS/ProxyBridge/ProxyBridge/ProxySettingsView.swift
@@ -1,10 +1,3 @@
-//
-// ProxySettingsView.swift
-// ProxyBridge
-//
-// Created by sourav kalal on 14/11/25.
-//
-
import SwiftUI
struct ProxySettingsView: View {
@@ -17,119 +10,121 @@ struct ProxySettingsView: View {
@State private var username = ""
@State private var password = ""
- let proxyTypes = ["http", "socks5"]
+ private let proxyTypes = ["http", "socks5"]
+ private var isSaveDisabled: Bool {
+ proxyType.isEmpty || proxyHost.isEmpty || proxyPort.isEmpty
+ }
var body: some View {
VStack(spacing: 0) {
- // Header
- HStack {
- Image(systemName: "network")
- .font(.title2)
- .foregroundColor(.accentColor)
- Text("Proxy Settings")
- .font(.title2)
- .fontWeight(.semibold)
- Spacer()
- }
- .padding()
- .background(Color(NSColor.controlBackgroundColor))
-
- // Form Content
- Form {
- Section {
- VStack(alignment: .leading, spacing: 8) {
- HStack {
- Text("Proxy Type")
- .fontWeight(.medium)
- Text("*")
- .foregroundColor(.red)
- }
- Picker("Select proxy type", selection: $proxyType) {
- Text("Select proxy type").tag("")
- ForEach(proxyTypes, id: \.self) { type in
- Text(type.uppercased()).tag(type)
- }
- }
- .pickerStyle(.menu)
- }
- .padding(.vertical, 8)
-
- VStack(alignment: .leading, spacing: 8) {
- HStack {
- Text("Proxy IP Address")
- .fontWeight(.medium)
- Text("*")
- .foregroundColor(.red)
- }
- TextField("127.0.0.1", text: $proxyHost)
- .textFieldStyle(.roundedBorder)
- }
- .padding(.vertical, 8)
-
- VStack(alignment: .leading, spacing: 8) {
- HStack {
- Text("Proxy Port")
- .fontWeight(.medium)
- Text("*")
- .foregroundColor(.red)
- }
- TextField("8080", text: $proxyPort)
- .textFieldStyle(.roundedBorder)
- }
- .padding(.vertical, 8)
-
- VStack(alignment: .leading, spacing: 8) {
- Text("Username (Optional)")
- .fontWeight(.medium)
- TextField("Leave empty if no auth required", text: $username)
- .textFieldStyle(.roundedBorder)
- }
- .padding(.vertical, 8)
-
- VStack(alignment: .leading, spacing: 8) {
- Text("Password (Optional)")
- .fontWeight(.medium)
- SecureField("Leave empty if no auth required", text: $password)
- .textFieldStyle(.roundedBorder)
- }
- .padding(.vertical, 8)
-
- HStack {
- Text("* Required fields")
- .font(.caption)
- .foregroundColor(.secondary)
- Spacer()
- }
- .padding(.top, 4)
- }
- }
- .formStyle(.grouped)
-
+ headerView
+ formContent
Divider()
-
- // Footer Buttons
- HStack(spacing: 12) {
- Spacer()
+ footerButtons
+ }
+ .frame(width: 600, height: 500)
+ .onAppear(perform: loadCurrentSettings)
+ }
+
+ private var headerView: some View {
+ HStack {
+ Image(systemName: "network")
+ .font(.title2)
+ .foregroundColor(.accentColor)
+ Text("Proxy Settings")
+ .font(.title2)
+ .fontWeight(.semibold)
+ Spacer()
+ }
+ .padding()
+ .background(Color(NSColor.controlBackgroundColor))
+ }
+
+ private var formContent: some View {
+ Form {
+ Section {
+ formPicker(label: "Proxy Type", selection: $proxyType, required: true)
+ formTextField(label: "Proxy IP Address", placeholder: "127.0.0.1", text: $proxyHost, required: true)
+ formTextField(label: "Proxy Port", placeholder: "8080", text: $proxyPort, required: true)
+ formTextField(label: "Username", placeholder: "Leave empty if no auth required", text: $username)
+ formSecureField(label: "Password", placeholder: "Leave empty if no auth required", text: $password)
- Button("Cancel") {
- dismiss()
+ HStack {
+ Text("* Required fields")
+ .font(.caption)
+ .foregroundColor(.secondary)
+ Spacer()
}
- .keyboardShortcut(.cancelAction)
-
- Button("Save Changes") {
- saveSettings()
- dismiss()
+ .padding(.top, 4)
+ }
+ }
+ .formStyle(.grouped)
+ }
+
+ private var footerButtons: some View {
+ HStack(spacing: 12) {
+ Spacer()
+ Button("Cancel") {
+ dismiss()
+ }
+ .keyboardShortcut(.cancelAction)
+
+ Button("Save Changes") {
+ saveSettings()
+ dismiss()
+ }
+ .buttonStyle(.borderedProminent)
+ .keyboardShortcut(.defaultAction)
+ .disabled(isSaveDisabled)
+ }
+ .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)
}
- .buttonStyle(.borderedProminent)
- .keyboardShortcut(.defaultAction)
- .disabled(proxyType.isEmpty || proxyHost.isEmpty || proxyPort.isEmpty)
}
- .padding()
- .background(Color(NSColor.controlBackgroundColor))
+ .pickerStyle(.menu)
}
- .frame(width: 600, height: 500)
- .onAppear {
- loadCurrentSettings()
+ .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)
+ }
+ .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)
+ }
+
+ @ViewBuilder
+ private func labelWithRequiredMark(label: String, required: Bool) -> some View {
+ HStack {
+ Text(label)
+ .fontWeight(.medium)
+ if required {
+ Text("*")
+ .foregroundColor(.red)
+ }
}
}
diff --git a/MacOS/ProxyBridge/ProxyBridge/RuleManager.swift b/MacOS/ProxyBridge/ProxyBridge/RuleManager.swift
index 92d7555..908b9e6 100644
--- a/MacOS/ProxyBridge/ProxyBridge/RuleManager.swift
+++ b/MacOS/ProxyBridge/ProxyBridge/RuleManager.swift
@@ -1,16 +1,8 @@
-//
-// RuleManager.swift
-// ProxyBridge
-//
-// Rule management helper for CLI
-//
-
import Foundation
import NetworkExtension
struct RuleManager {
- // Send addRule command to extension
static func addRule(
session: NETunnelProviderSession,
processNames: String,
@@ -21,36 +13,23 @@ struct RuleManager {
enabled: Bool = true,
completion: @escaping (Bool, String, UInt32?) -> Void
) {
- let message: [String: Any] = [
- "action": "addRule",
- "processNames": processNames,
- "targetHosts": targetHosts,
- "targetPorts": targetPorts,
- "ruleProtocol": `protocol`,
- "ruleAction": action,
- "enabled": enabled
- ]
-
- guard let data = try? JSONSerialization.data(withJSONObject: message) else {
- completion(false, "Failed to serialize rule", nil)
- return
- }
-
- try? session.sendProviderMessage(data) { response in
- guard let responseData = response,
- let result = try? JSONSerialization.jsonObject(with: responseData) as? [String: Any],
- let status = result["status"] as? String else {
- completion(false, "No response from extension", nil)
- return
- }
-
- if status == "ok" {
+ sendMessage(
+ session: session,
+ action: "addRule",
+ params: [
+ "processNames": processNames,
+ "targetHosts": targetHosts,
+ "targetPorts": targetPorts,
+ "ruleProtocol": `protocol`,
+ "ruleAction": action,
+ "enabled": enabled
+ ]
+ ) { success, result in
+ if success, let result = result {
let ruleId = result["ruleId"] as? UInt32
completion(true, "Rule added successfully", ruleId)
- } else if let message = result["message"] as? String {
- completion(false, "Error: \(message)", nil)
} else {
- completion(false, "Unknown error", nil)
+ completion(false, result?["message"] as? String ?? "Unknown error", nil)
}
}
}
@@ -66,150 +45,97 @@ struct RuleManager {
enabled: Bool = true,
completion: @escaping (Bool, String) -> Void
) {
- let message: [String: Any] = [
- "action": "updateRule",
- "ruleId": ruleId,
- "processNames": processNames,
- "targetHosts": targetHosts,
- "targetPorts": targetPorts,
- "ruleProtocol": `protocol`,
- "ruleAction": action,
- "enabled": enabled
- ]
-
- guard let data = try? JSONSerialization.data(withJSONObject: message) else {
- completion(false, "Failed to serialize rule")
- return
- }
-
- try? session.sendProviderMessage(data) { response in
- guard let responseData = response,
- let result = try? JSONSerialization.jsonObject(with: responseData) as? [String: Any],
- let status = result["status"] as? String else {
- completion(false, "No response from extension")
- return
- }
-
- if status == "ok" {
- completion(true, "Rule #\(ruleId) updated successfully")
- } else if let message = result["message"] as? String {
- completion(false, "Error: \(message)")
- } else {
- completion(false, "Unknown error")
- }
+ sendMessage(
+ session: session,
+ action: "updateRule",
+ params: [
+ "ruleId": ruleId,
+ "processNames": processNames,
+ "targetHosts": targetHosts,
+ "targetPorts": targetPorts,
+ "ruleProtocol": `protocol`,
+ "ruleAction": action,
+ "enabled": enabled
+ ]
+ ) { success, result in
+ let message = success
+ ? "Rule #\(ruleId) updated successfully"
+ : (result?["message"] as? String ?? "Unknown error")
+ completion(success, message)
}
}
-
static func toggleRule(
session: NETunnelProviderSession,
ruleId: UInt32,
enabled: Bool,
completion: @escaping (Bool, String) -> Void
) {
- let message: [String: Any] = [
- "action": "toggleRule",
- "ruleId": ruleId,
- "enabled": enabled
- ]
-
- guard let data = try? JSONSerialization.data(withJSONObject: message) else {
- completion(false, "Failed to serialize message")
- return
- }
-
- try? session.sendProviderMessage(data) { response in
- guard let responseData = response,
- let result = try? JSONSerialization.jsonObject(with: responseData) as? [String: Any],
- let status = result["status"] as? String else {
- completion(false, "No response from extension")
- return
- }
-
- if status == "ok" {
- completion(true, "Rule #\(ruleId) \(enabled ? "enabled" : "disabled")")
- } else if let message = result["message"] as? String {
- completion(false, "Error: \(message)")
- } else {
- completion(false, "Unknown error")
- }
+ sendMessage(
+ session: session,
+ action: "toggleRule",
+ params: ["ruleId": ruleId, "enabled": enabled]
+ ) { success, result in
+ let message = success
+ ? "Rule #\(ruleId) \(enabled ? "enabled" : "disabled")"
+ : (result?["message"] as? String ?? "Unknown error")
+ completion(success, message)
}
}
- // Send removeRule command
static func removeRule(
session: NETunnelProviderSession,
ruleId: UInt32,
completion: @escaping (Bool, String) -> Void
) {
- let message: [String: Any] = [
- "action": "removeRule",
- "ruleId": ruleId
- ]
-
- guard let data = try? JSONSerialization.data(withJSONObject: message) else {
- completion(false, "Failed to serialize message")
- return
- }
-
- try? session.sendProviderMessage(data) { response in
- guard let responseData = response,
- let result = try? JSONSerialization.jsonObject(with: responseData) as? [String: Any],
- let status = result["status"] as? String else {
- completion(false, "No response from extension")
- return
- }
-
- if status == "ok" {
- let removed = result["removed"] as? Int ?? 0
- completion(true, "Removed \(removed) rule(s)")
- } else if let message = result["message"] as? String {
- completion(false, "Error: \(message)")
- } else {
- completion(false, "Unknown error")
- }
+ sendMessage(
+ session: session,
+ action: "removeRule",
+ params: ["ruleId": ruleId]
+ ) { success, result in
+ let message = success
+ ? "Removed \(result?["removed"] as? Int ?? 0) rule(s)"
+ : (result?["message"] as? String ?? "Unknown error")
+ completion(success, message)
}
}
- // List all rules
static func listRules(
session: NETunnelProviderSession,
completion: @escaping (Bool, [[String: Any]]) -> Void
) {
- let message: [String: Any] = [
- "action": "listRules"
- ]
-
- guard let data = try? JSONSerialization.data(withJSONObject: message) else {
- completion(false, [])
- return
- }
-
- try? session.sendProviderMessage(data) { response in
- guard let responseData = response,
- let result = try? JSONSerialization.jsonObject(with: responseData) as? [String: Any],
- let status = result["status"] as? String,
- status == "ok",
- let rules = result["rules"] as? [[String: Any]] else {
+ sendMessage(session: session, action: "listRules", params: [:]) { success, result in
+ if success, let rules = result?["rules"] as? [[String: Any]] {
+ completion(true, rules)
+ } else {
completion(false, [])
- return
}
-
- completion(true, rules)
}
}
- // Clear all rules
static func clearRules(
session: NETunnelProviderSession,
completion: @escaping (Bool, String) -> Void
) {
- let message: [String: Any] = [
- "action": "clearRules"
- ]
+ sendMessage(session: session, action: "clearRules", params: [:]) { success, result in
+ let message = success
+ ? "Cleared \(result?["cleared"] as? Int ?? 0) rule(s)"
+ : (result?["message"] as? String ?? "Unknown error")
+ completion(success, message)
+ }
+ }
+
+ private static func sendMessage(
+ session: NETunnelProviderSession,
+ action: String,
+ params: [String: Any],
+ completion: @escaping (Bool, [String: Any]?) -> Void
+ ) {
+ var message = params
+ message["action"] = action
guard let data = try? JSONSerialization.data(withJSONObject: message) else {
- completion(false, "Failed to serialize message")
+ completion(false, nil)
return
}
@@ -217,18 +143,11 @@ struct RuleManager {
guard let responseData = response,
let result = try? JSONSerialization.jsonObject(with: responseData) as? [String: Any],
let status = result["status"] as? String else {
- completion(false, "No response from extension")
+ completion(false, nil)
return
}
- if status == "ok" {
- let cleared = result["cleared"] as? Int ?? 0
- completion(true, "Cleared \(cleared) rule(s)")
- } else if let message = result["message"] as? String {
- completion(false, "Error: \(message)")
- } else {
- completion(false, "Unknown error")
- }
+ completion(status == "ok", result)
}
}