From 2a4f1754389e941026c31ec615a1918e549704ba Mon Sep 17 00:00:00 2001 From: bradmb <1200479+bradmb@users.noreply.github.com> Date: Mon, 26 Oct 2026 14:27:29 -0600 Subject: [PATCH] Improve local-network connection diagnostics and privacy Declare local-network usage, bound foreground connection polling and retries, surface actionable error codes, and avoid logging session or SDK payloads. Add standalone policy regressions. Co-Authored-By: Warp --- OpenParsec.xcodeproj/project.pbxproj | 4 +++ OpenParsec/ConnectionAttemptPolicy.swift | 16 +++++++++ OpenParsec/ContentView.swift | 2 +- OpenParsec/Info.plist | 2 ++ OpenParsec/LoginView.swift | 2 -- OpenParsec/MainView.swift | 46 +++++++++++++++++++----- OpenParsec/NetworkHandler.swift | 4 +++ OpenParsec/ParsecSDKBridge.swift | 7 ++-- OpenParsec/ParsecView.swift | 4 ++- OpenParsec/Shared.swift | 9 +++++ Tests/ConnectionRegressionTests.swift | 25 +++++++++++++ Tests/run-connection-regressions.sh | 11 ++++++ 12 files changed, 116 insertions(+), 16 deletions(-) create mode 100644 OpenParsec/ConnectionAttemptPolicy.swift create mode 100644 Tests/ConnectionRegressionTests.swift create mode 100644 Tests/run-connection-regressions.sh diff --git a/OpenParsec.xcodeproj/project.pbxproj b/OpenParsec.xcodeproj/project.pbxproj index 5526ba57..91662ac2 100644 --- a/OpenParsec.xcodeproj/project.pbxproj +++ b/OpenParsec.xcodeproj/project.pbxproj @@ -7,6 +7,7 @@ objects = { /* Begin PBXBuildFile section */ + A27110000000000000000001 /* ConnectionAttemptPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = A27110000000000000000002 /* ConnectionAttemptPolicy.swift */; }; 170E0A772BEF5AFF00B0EA32 /* ParsecViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 170E0A762BEF5AFF00B0EA32 /* ParsecViewController.swift */; }; 17374D412CB8E35D00EDCEE7 /* KeyCodeTranslators.swift in Sources */ = {isa = PBXBuildFile; fileRef = 17374D402CB8E35500EDCEE7 /* KeyCodeTranslators.swift */; }; 17840D1D2CB639530097374B /* ParsecUserData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 17840D1C2CB6394D0097374B /* ParsecUserData.swift */; }; @@ -59,6 +60,7 @@ /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ + A27110000000000000000002 /* ConnectionAttemptPolicy.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ConnectionAttemptPolicy.swift; sourceTree = ""; }; 170E0A762BEF5AFF00B0EA32 /* ParsecViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ParsecViewController.swift; sourceTree = ""; }; 17374D402CB8E35500EDCEE7 /* KeyCodeTranslators.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = KeyCodeTranslators.swift; sourceTree = ""; }; 17840D1C2CB6394D0097374B /* ParsecUserData.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ParsecUserData.swift; sourceTree = ""; }; @@ -140,6 +142,7 @@ 27E61A90292965FC00FF6563 /* OpenParsec */ = { isa = PBXGroup; children = ( + A27110000000000000000002 /* ConnectionAttemptPolicy.swift */, E76224A02F8C017700A2F86F /* ParsecBackgroundManager.swift */, E762250A2F8D0A0000A2F86F /* PictureInPictureManager.swift */, 17374D402CB8E35500EDCEE7 /* KeyCodeTranslators.swift */, @@ -285,6 +288,7 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + A27110000000000000000001 /* ConnectionAttemptPolicy.swift in Sources */, FC16A7AD29A97BDA00BB70A7 /* Shared.swift in Sources */, 84480EBE2ADC4FDA007DE5F1 /* GameController.swift in Sources */, 27AC751829EA339B00E8CAF7 /* URLImage.swift in Sources */, diff --git a/OpenParsec/ConnectionAttemptPolicy.swift b/OpenParsec/ConnectionAttemptPolicy.swift new file mode 100644 index 00000000..5f87e97c --- /dev/null +++ b/OpenParsec/ConnectionAttemptPolicy.swift @@ -0,0 +1,16 @@ +struct ConnectionAttemptPolicy { + private(set) var activePolls = 0 + static let timeoutPolls = 30 + + mutating func tick(isActive: Bool) -> Bool { + guard isActive else { return false } + activePolls += 1 + return true + } + + var timedOut: Bool { activePolls >= Self.timeoutPolls } + + static func shouldRetry(isPeerFailure: Bool, alreadyRetried: Bool) -> Bool { + isPeerFailure && !alreadyRetried + } +} diff --git a/OpenParsec/ContentView.swift b/OpenParsec/ContentView.swift index e966475f..9006ad50 100644 --- a/OpenParsec/ContentView.swift +++ b/OpenParsec/ContentView.swift @@ -43,7 +43,7 @@ struct ContentView: View { if let data = loadFromKeychain(key: GLBDataModel.shared.SessionKeyChainKey) { let decoder = JSONDecoder() - print("Retrieved data from keychain: \(data).\nTrying to restore session.") + appNote("[session] restoring saved session") NetworkHandler.clinfo = try? decoder.decode(ClientInfo.self, from: data) if NetworkHandler.clinfo != nil { curView = .main diff --git a/OpenParsec/Info.plist b/OpenParsec/Info.plist index 593f0cec..ee92ff46 100644 --- a/OpenParsec/Info.plist +++ b/OpenParsec/Info.plist @@ -41,6 +41,8 @@ LSRequiresIPhoneOS + NSLocalNetworkUsageDescription + OpenParsec connects directly to your computers on Wi-Fi to stream their desktop, audio, and controls. UIApplicationSceneManifest UIApplicationSupportsMultipleScenes diff --git a/OpenParsec/LoginView.swift b/OpenParsec/LoginView.swift index 5f2f1405..ee22c7e8 100644 --- a/OpenParsec/LoginView.swift +++ b/OpenParsec/LoginView.swift @@ -207,8 +207,6 @@ struct LoginView: View { let json = try? JSONSerialization.jsonObject(with: data, options: []) if let dict = json as? [String: Any], let isTFARequired = dict["tfa_required"] as? Bool { - print("Code output:") - print(dict) if isTFARequired { presentTFAAlert = true } else { diff --git a/OpenParsec/MainView.swift b/OpenParsec/MainView.swift index a6b5ad6e..e547aef5 100644 --- a/OpenParsec/MainView.swift +++ b/OpenParsec/MainView.swift @@ -32,6 +32,9 @@ struct MainView: View { @State var pollTimer: Timer? @State var approvalStartedAt: Date? @State var connectStartedAt = Date() + @State private var attemptPolicy = ConnectionAttemptPolicy() + @State private var approvalPolls = 0 + @State private var showConnectionHelp = false @State var isRefreshing: Bool = false @State var refreshError: String? @@ -365,7 +368,13 @@ struct MainView: View { .padding(.top, -8) .frame(maxWidth: .infinity) .alert(isPresented: $showBaseAlert) { - Alert(title: Text(baseAlertText)) + if showConnectionHelp { + return Alert(title: Text("Connection failed"), message: Text(baseAlertText), + primaryButton: .default(Text("Open App Settings"), action: { + if let url = URL(string: UIApplication.openSettingsURLString) { UIApplication.shared.open(url) } + }), secondaryButton: .cancel(Text("OK"))) + } + return Alert(title: Text(baseAlertText)) } // Page controls @@ -401,7 +410,10 @@ struct MainView: View { .zIndex(1) } .onAppear(perform: initView) - .onDisappear { ParsecBackgroundManager.shared.onShortcutReconnect = nil } + .onDisappear { + pollTimer?.invalidate() + ParsecBackgroundManager.shared.onShortcutReconnect = nil + } .disabled(busy) // disable view if busy // Settings screen @@ -659,6 +671,7 @@ struct MainView: View { } func connectTo(_ who: IdentifiableHostInfo, retried: Bool = false) { + showConnectionHelp = false if NetworkWatcher.shared.noNetwork { appNote("[connect] no network, not trying") withAnimation { @@ -687,8 +700,10 @@ struct MainView: View { connectStartedAt = Date() let status = CParsec.connect(who.id) - appNote("[connect] started, status \(status.rawValue)") + appNote("[connect] started, status \(status.rawValue), network \(NetworkWatcher.shared.interfaceDescription)") connectPolls = 0 + attemptPolicy = ConnectionAttemptPolicy() + approvalPolls = 0 approvalStartedAt = nil // Polling status @@ -700,6 +715,7 @@ struct MainView: View { } func pollConnect(_ who: IdentifiableHostInfo) { + guard isConnecting, attemptPolicy.tick(isActive: UIApplication.shared.applicationState == .active) else { return } let status = CParsec.getStatus() connectPolls += 1 @@ -710,7 +726,16 @@ struct MainView: View { return } - if status == PARSEC_CONNECTING { return } // wait + if status == PARSEC_CONNECTING { + if attemptPolicy.timedOut { retryOrGiveUp(who) } + return + } + + if ConnectionAttemptPolicy.shouldRetry(isPeerFailure: status.isPeerConnectionFailure, alreadyRetried: retryingConnect) { + appNote("[connect] retrying peer setup, code \(status.rawValue)") + retryOrGiveUp(who) + return + } if status == CONNECT_WRN_APPROVAL { if approvalStartedAt == nil { @@ -720,10 +745,10 @@ struct MainView: View { return } } - let started = approvalStartedAt ?? Date() - approvalStartedAt = started + approvalStartedAt = approvalStartedAt ?? Date() + approvalPolls += 1 if !waitingForApproval { withAnimation { waitingForApproval = true } } - if Date().timeIntervalSince(started) < 60 { return } + if approvalPolls < 60 { return } } withAnimation { @@ -740,7 +765,8 @@ struct MainView: View { } } else { CParsec.disconnect() - baseAlertText = status.readable(connecting: true) + baseAlertText = status.connectionMessage(connecting: true) + showConnectionHelp = status.isPeerConnectionFailure showBaseAlert = true } @@ -757,8 +783,10 @@ struct MainView: View { withAnimation { isConnecting = false retryingConnect = false + waitingForApproval = false } - baseAlertText = "\(who.hostname) didn't answer the connection request" + baseAlertText = "The host didn't answer the connection request within the retry limit. Check that it is online and that OpenParsec has Local Network access for same-Wi-Fi connections." + showConnectionHelp = true showBaseAlert = true } diff --git a/OpenParsec/NetworkHandler.swift b/OpenParsec/NetworkHandler.swift index e9db31b9..e3488b3e 100644 --- a/OpenParsec/NetworkHandler.swift +++ b/OpenParsec/NetworkHandler.swift @@ -13,6 +13,7 @@ class NetworkWatcher { private var running = false private var offline = false private(set) var noNetwork = false + private(set) var interfaceDescription = "unknown" private var known = false private var waiting: [() -> Void] = [] @@ -24,9 +25,12 @@ class NetworkWatcher { monitor.pathUpdateHandler = { [weak self] path in let status = path.status + let interface = path.usesInterfaceType(.wifi) ? "Wi-Fi" : path.usesInterfaceType(.cellular) ? "cellular" : path.usesInterfaceType(.wiredEthernet) ? "Ethernet" : "other" DispatchQueue.main.async { guard let self = self else { return } self.noNetwork = status == .unsatisfied + self.interfaceDescription = interface + appNote("[network] \(interface), \(status == .satisfied ? "available" : "unavailable"); LAN permission unknown") if !self.known { self.known = true let runs = self.waiting diff --git a/OpenParsec/ParsecSDKBridge.swift b/OpenParsec/ParsecSDKBridge.swift index ab1d0a0e..1659845b 100644 --- a/OpenParsec/ParsecSDKBridge.swift +++ b/OpenParsec/ParsecSDKBridge.swift @@ -89,11 +89,12 @@ class ParsecSDKBridge: ParsecService { ParsecSetLogCallback( { (level, msg, _) in - let line = String(cString: msg!) - os_log("%{public}@", log: sdkLog, type: .debug, "[\(level == LOG_DEBUG ? "D" : "I")] \(line)") + guard let msg = msg else { return } + let line = String(cString: msg) + // SDK payloads can contain session credentials. Never log them verbatim. if line.contains("signal_") && line.contains("] = -") { let at = Date() - DispatchQueue.main.async { CParsec.setupError = (line, at) } + DispatchQueue.main.async { CParsec.setupError = ("SDK signaling failed", at) } } }, nil) diff --git a/OpenParsec/ParsecView.swift b/OpenParsec/ParsecView.swift index f45d5332..c6f3a060 100644 --- a/OpenParsec/ParsecView.swift +++ b/OpenParsec/ParsecView.swift @@ -2,6 +2,7 @@ import SwiftUI import ParsecSDK import Foundation import AVFoundation +import Combine struct ParsecStatusBar: View { @Binding var showMenu: Bool @@ -51,6 +52,7 @@ struct ParsecStatusBar: View { } func poll() { + guard UIApplication.shared.applicationState != .inactive else { return } if showDCAlert || ParsecBackgroundManager.shared.isPaused { return } @@ -135,7 +137,7 @@ struct ParsecStatusBar: View { // silent: auto-reconnect spent its retries, dont nag with an alert onSilentDisconnect() } else { - DCAlertText = status.readable() + DCAlertText = status.connectionMessage() showDCAlert = true } return diff --git a/OpenParsec/Shared.swift b/OpenParsec/Shared.swift index 38c3aa5a..5d0286a7 100644 --- a/OpenParsec/Shared.swift +++ b/OpenParsec/Shared.swift @@ -94,6 +94,15 @@ class DataManager { } extension ParsecStatus { + var isPeerConnectionFailure: Bool { + self == NAT_ERR_PEER_PHASE || self == NAT_ERR_NO_CANDIDATES || self == NAT_ERR_STUN_PHASE + } + + func connectionMessage(connecting: Bool = false) -> String { + let message = "\(readable(connecting: connecting)) (code \(rawValue))." + guard isPeerConnectionFailure else { return message } + return message + "\n\nFor a host on the same Wi-Fi, allow OpenParsec in Settings → Privacy & Security → Local Network, then retry. If access is already allowed, check guest Wi-Fi/client isolation, VPN routing, and the host firewall. A working cellular connection does not confirm LAN access." + } func readable(connecting: Bool = false) -> String { switch self { case WS_ERR_AUTH: return "Authentication failed" diff --git a/Tests/ConnectionRegressionTests.swift b/Tests/ConnectionRegressionTests.swift new file mode 100644 index 00000000..6d0c7cd6 --- /dev/null +++ b/Tests/ConnectionRegressionTests.swift @@ -0,0 +1,25 @@ +import Foundation + +@main +enum ConnectionRegressionTests { + static func main() { + var checks = 0 + func check(_ condition: @autoclosure () -> Bool, _ name: String) { + precondition(condition(), "FAILED: \(name)") + checks += 1 + } + var policy = ConnectionAttemptPolicy() + var paused = true + for _ in 0..<100 { paused = !policy.tick(isActive: false) && paused } + check(paused, "permission prompt pauses polling") + check(policy.activePolls == 0 && !policy.timedOut, "inactive time never consumes timeout") + for _ in 0..<29 { _ = policy.tick(isActive: true) } + check(!policy.timedOut, "attempt remains live before timeout") + _ = policy.tick(isActive: true) + check(policy.timedOut, "attempt is bounded") + check(ConnectionAttemptPolicy.shouldRetry(isPeerFailure: true, alreadyRetried: false), "first peer failure can retry") + check(!ConnectionAttemptPolicy.shouldRetry(isPeerFailure: true, alreadyRetried: true), "second failure never loops") + check(!ConnectionAttemptPolicy.shouldRetry(isPeerFailure: false, alreadyRetried: false), "permission/auth errors not peer retries") + print("Passed \(checks) connection-policy assertions.") + } +} diff --git a/Tests/run-connection-regressions.sh b/Tests/run-connection-regressions.sh new file mode 100644 index 00000000..b6d06eda --- /dev/null +++ b/Tests/run-connection-regressions.sh @@ -0,0 +1,11 @@ +#!/bin/sh +# Connection-policy checks run on the Mac without loading the device-only Parsec SDK. +set -eu +ROOT="$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)" +WORK="$(mktemp -d "${TMPDIR:-/tmp}/openparsec-tests.XXXXXX")" +trap 'rm -rf "$WORK"' EXIT +xcrun swiftc -sdk "$(xcrun --sdk macosx --show-sdk-path)" \ + "$ROOT/OpenParsec/ConnectionAttemptPolicy.swift" \ + "$ROOT/Tests/ConnectionRegressionTests.swift" -o "$WORK/regressions" +"$WORK/regressions" +/usr/bin/plutil -lint "$ROOT/OpenParsec/Info.plist" "$ROOT/OpenParsec.xcodeproj/project.pbxproj"