From 8103b1d53467c7c4b186b590419a017961b73eb1 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sat, 24 Oct 2026 14:57:52 +0000 Subject: [PATCH 1/2] fix(native): advertise the live WebTransport port and real device name The Mac app treated any leftover wt_info.json as the daemon listener and cached that port for signaling. Browsers dial wtUrl from connection_request and connection_accepted, so a previous launch's port hangs Mac-to-browser transfers. Ignore endpoint files this daemon did not rewrite, and re-read them before each advertisement. If no live listener exists, cancel the browser connect instead of waiting. Host.localizedName can be the bind address 0.0.0.0. Advertise the System Settings computer name, and never show a bind address as a peer name when a real device name is available. Co-authored-by: Evan Oberfelder --- .../macos/Sources/LocalBolt/BoltBridge.swift | 100 +++- .../Sources/LocalBolt/LocalBoltApp.swift | 122 +++-- .../Sources/LocalBolt/LocalDeviceName.swift | 36 ++ .../LocalBolt/TransportAdvertisement.swift | 100 ++++ native/shared/include/bolt_native_bridge.h | 33 ++ native/shared/src/advertise_policy.rs | 477 ++++++++++++++++++ native/shared/src/daemon.rs | 12 +- native/shared/src/lib.rs | 1 + native/shared/src/signaling.rs | 79 ++- 9 files changed, 900 insertions(+), 60 deletions(-) create mode 100644 native/macos/Sources/LocalBolt/LocalDeviceName.swift create mode 100644 native/macos/Sources/LocalBolt/TransportAdvertisement.swift create mode 100644 native/shared/src/advertise_policy.rs diff --git a/native/macos/Sources/LocalBolt/BoltBridge.swift b/native/macos/Sources/LocalBolt/BoltBridge.swift index 1fdd333..8f9fb11 100644 --- a/native/macos/Sources/LocalBolt/BoltBridge.swift +++ b/native/macos/Sources/LocalBolt/BoltBridge.swift @@ -64,6 +64,16 @@ final class DaemonManager { var quicAddr: String? /// QUIC cert hash hex (set after reading quic_info.json from daemon data_dir). var quicCertHash: String? + /// `wt_info.json` bytes captured before this daemon was spawned. Identical bytes + /// are the previous launch and must not be advertised. + private var wtBaselineJSON: String? + /// `quic_info.json` bytes captured before this daemon was spawned. + private var quicBaselineJSON: String? + /// True when `wtUrl` and `wtCertHash` describe this daemon's live listener. + var hasLiveWebTransport: Bool { + guard let wtUrl, let wtCertHash else { return false } + return !wtUrl.isEmpty && !wtCertHash.isEmpty + } /// True when daemon has an active WT session (detected from stderr). /// Latches on "[WT_SESSION]...ACTIVE_SESSION registered", clears on "cleared". private(set) var wtSessionActive: Bool = false @@ -83,6 +93,9 @@ final class DaemonManager { guard let binPath = daemonBinaryPath else { return false } guard handle == nil else { return false } // already running + // Snapshot leftover endpoint files before the child can overwrite them. + captureTransportBaseline() + handle = binPath.withCString { cPath in bolt_daemon_start(cPath, wsPort) } @@ -125,6 +138,64 @@ final class DaemonManager { socketPath = "" dataDir = "" recentStderr = "" + clearAdvertisedTransport() + } + + /// Copies of the values the startup poll needs. Taken on the main thread so the + /// wait does not read DaemonManager concurrently with its stderr timer. + func wtWaitSnapshot() -> (dataDir: String, wsPort: UInt16, baseline: String?) { + (dataDir, wsPort, wtBaselineJSON) + } + + /// Re-read wt_info.json and quic_info.json and keep only records this daemon wrote. + /// Call this immediately before advertising endpoints in a signaling payload. + func refreshAdvertisedTransport(host: String) { + guard isRunning, wsPort > 0, !dataDir.isEmpty else { + clearAdvertisedTransport() + return + } + let wtJSON = TransportMetadataFile.read(dataDir: dataDir, name: "wt_info.json") + if let wt = BoltBridge.selectWt( + currentJSON: wtJSON, + baselineJSON: wtBaselineJSON, + wsPort: wsPort, + host: host + ) { + if wtUrl != wt.url || wtCertHash != wt.certHash { + print("[WT] advertising \(wt.url)") + } + wtUrl = wt.url + wtCertHash = wt.certHash + } else { + if wtUrl != nil || wtCertHash != nil { + print("[WT] not advertising WebTransport — listener metadata is missing or stale") + } + wtUrl = nil + wtCertHash = nil + } + + let quicJSON = TransportMetadataFile.read(dataDir: dataDir, name: "quic_info.json") + if let quic = BoltBridge.selectQuic( + currentJSON: quicJSON, + baselineJSON: quicBaselineJSON, + wsPort: wsPort, + host: host + ) { + quicAddr = quic.url + quicCertHash = quic.certHash + } else { + quicAddr = nil + quicCertHash = nil + } + } + + private func captureTransportBaseline() { + let dir = BoltBridge.platformDataDir() + wtBaselineJSON = TransportMetadataFile.read(dataDir: dir, name: "wt_info.json") + quicBaselineJSON = TransportMetadataFile.read(dataDir: dir, name: "quic_info.json") + } + + private func clearAdvertisedTransport() { wtUrl = nil wtCertHash = nil quicAddr = nil @@ -250,6 +321,7 @@ final class DaemonManager { handle = nil pid = 0 wsPort = 0 + clearAdvertisedTransport() } } @@ -264,7 +336,8 @@ final class DaemonManager { struct DiscoveredPeer: Identifiable { let id: String // peer_code let peerCode: String - let deviceName: String + /// Human name from signaling. Updated when a later event replaces a bind address. + var deviceName: String let deviceType: String /// WebTransport URL (nil if peer doesn't support WT). let wtUrl: String? @@ -289,6 +362,8 @@ final class SignalingManager { var incomingConnectionRequest: IncomingSignal? = nil /// Set true when remote peer declines connection (consumed by ContentView to clear connecting state). var connectionDeclined: Bool = false + /// Transient notice for a connection that cannot proceed (for example no live WT listener). + var userNotice: String? private var handle: OpaquePointer? private var pollTimer: Timer? @@ -319,7 +394,7 @@ final class SignalingManager { handle = peerCode.withCString { codeCStr in localUrl.withCString { localCStr in - let deviceName = Host.current().localizedName ?? "Mac" + let deviceName = LocalDeviceName.current() return deviceName.withCString { nameCStr in // Nest optional withCString calls to keep pointers alive if let cloud = cloudUrl, let wtu = wtUrl, let wth = wtCertHash { @@ -380,6 +455,17 @@ final class SignalingManager { } isConnected = false peers = [] + userNotice = nil + } + + /// Remember a real device name learned from a connection payload when the + /// discovery list still has a bind address. + func notePeerDeviceName(peerCode: String, advertised: String) { + guard let idx = peers.firstIndex(where: { $0.peerCode == peerCode }) else { return } + let preferred = BoltBridge.preferDeviceName(current: peers[idx].deviceName, candidate: advertised) + if preferred != peers[idx].deviceName { + peers[idx].deviceName = preferred + } } private func poll() { @@ -413,7 +499,9 @@ final class SignalingManager { if let peerPtr = bolt_signaling_get_peer(h, i) { let peer = peerPtr.pointee let code = peer.peer_code.map { String(cString: $0) } ?? "" - let name = peer.device_name.map { String(cString: $0) } ?? "" + let ffiName = peer.device_name.map { String(cString: $0) } ?? "" + let learned = peers.first(where: { $0.peerCode == code })?.deviceName ?? "" + let name = BoltBridge.preferDeviceName(current: ffiName, candidate: learned) let type = peer.device_type.map { String(cString: $0) } ?? "" let rawWtUrl = peer.wt_url let rawWtHash = peer.wt_cert_hash @@ -426,7 +514,11 @@ final class SignalingManager { bolt_peer_free(peerPtr) } } - if updated.count != peers.count || !updated.map(\.id).elementsEqual(peers.map(\.id)) { + let changed = updated.count != peers.count + || zip(updated, peers).contains { + $0.peerCode != $1.peerCode || $0.deviceName != $1.deviceName || $0.deviceType != $1.deviceType + } + if changed { peers = updated } } diff --git a/native/macos/Sources/LocalBolt/LocalBoltApp.swift b/native/macos/Sources/LocalBolt/LocalBoltApp.swift index bdf176c..b8c5268 100644 --- a/native/macos/Sources/LocalBolt/LocalBoltApp.swift +++ b/native/macos/Sources/LocalBolt/LocalBoltApp.swift @@ -8,6 +8,7 @@ private let darkBg = Color(red: 0.08, green: 0.08, blue: 0.08) private let darkAccent = Color(red: 0.12, green: 0.12, blue: 0.12) /// Get the local LAN IP address for wsUrl in signaling payloads. +/// Skips the wildcard bind address. Advertising `0.0.0.0` is not a reachable host. private func localIPAddress() -> String { var address = "127.0.0.1" var ifaddr: UnsafeMutablePointer? @@ -21,12 +22,18 @@ private func localIPAddress() -> String { var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST)) getnameinfo(ptr.pointee.ifa_addr, socklen_t(sa.sa_len), &hostname, socklen_t(hostname.count), nil, 0, NI_NUMERICHOST) - address = String(cString: hostname) + let candidate = String(cString: hostname) + if BoltBridge.deviceNameIsUnusable(candidate) { continue } + address = candidate break } return address } +/// Browser peers dial our WebTransport listener. Without a live one, accepting +/// or waiting just hangs. Native peers still have `wsUrl`. +private let wtListenerNotReadyNotice = "WebTransport isn't ready on this Mac yet, so the browser can't connect. Wait a moment and try again." + /// UI-only connecting animation phase (product-specific, not canonical). enum ConnectingPhase { case requesting // "Waiting for [device] to accept..." @@ -75,6 +82,7 @@ struct LocalBoltApp: App { } let deviceName = signal.data["deviceName"] as? String ?? "Unknown Device" let deviceType = signal.data["deviceType"] as? String ?? "desktop" + signaling.notePeerDeviceName(peerCode: signal.from, advertised: deviceName) var requestData = signal.data requestData["deviceName"] = deviceName requestData["deviceType"] = deviceType @@ -84,22 +92,31 @@ struct LocalBoltApp: App { data: requestData ) case "connection_accepted": + let wsUrl = signal.data["wsUrl"] as? String ?? "" + if wsUrl.isEmpty { + // Browser peer accepted — no wsUrl (browsers can't host a WS server). + // They dial the wtUrl we put in connection_request. If that listener + // isn't live, fail now instead of sitting in .connecting. + daemon.refreshAdvertisedTransport(host: localIPAddress()) + guard daemon.hasLiveWebTransport else { + print("[CONNECT] connection_accepted without wsUrl and no live WebTransport listener — aborting") + ipc.resetSession() + signaling.userNotice = wtListenerNotReadyNotice + return + } + } guard ipc.beginConnecting() else { print("[CONNECT] ignoring connection_accepted while sessionPhase=\(String(describing: ipc.sessionPhase))") return } - if let wsUrl = signal.data["wsUrl"] as? String, !wsUrl.isEmpty { + if !wsUrl.isEmpty { daemon.connectToRemote( wsUrl: wsUrl, quicAddr: signal.data["quicAddr"] as? String, quicCertHash: signal.data["quicCertHash"] as? String ) } else { - // Browser peer accepted — no wsUrl (browsers can't host a WS server). - // Stay in .connecting and wait for the browser to connect back to our - // daemon's WebTransport endpoint. The WT session detection in - // onChange(of: daemon.wtSessionActive) will advance to .connected. - print("[CONNECT] connection_accepted without wsUrl — waiting for inbound WT session from browser") + print("[CONNECT] connection_accepted without wsUrl — waiting for inbound WT session from browser at \(daemon.wtUrl ?? "")") } case "connection_declined": // Remote peer declined — M2 onChange handler shows notice + resets @@ -113,36 +130,28 @@ struct LocalBoltApp: App { private func autoStart() { guard daemon.daemonBinaryPath != nil, !daemon.isRunning else { return } daemon.start() - let wtInfoPath = "\(daemon.dataDir)/wt_info.json" - let quicInfoPath = "\(daemon.dataDir)/quic_info.json" + let snapshot = daemon.wtWaitSnapshot() let pollInterval: TimeInterval = 0.25 - let maxAttempts = 20 // 5s total timeout + let maxAttempts = 20 // 5s — wait until THIS launch rewrites wt_info.json DispatchQueue.global(qos: .utility).async { var attempts = 0 while attempts < maxAttempts { - if FileManager.default.fileExists(atPath: wtInfoPath) { + let current = TransportMetadataFile.read(dataDir: snapshot.dataDir, name: "wt_info.json") + // A placeholder host only checks that the file is live. The URL + // advertised to peers is built on the main thread from the LAN address. + if BoltBridge.selectWt( + currentJSON: current, + baselineJSON: snapshot.baseline, + wsPort: snapshot.wsPort, + host: "10.0.0.1" + ) != nil { break } attempts += 1 Thread.sleep(forTimeInterval: pollInterval) } DispatchQueue.main.async { - // Read WT metadata (best-effort — nil values are safe) - if let data = try? Data(contentsOf: URL(fileURLWithPath: wtInfoPath)), - let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] { - if let port = json["wt_port"] as? Int { - self.daemon.wtUrl = "https://\(localIPAddress()):\(port)" - } - self.daemon.wtCertHash = json["wt_cert_hash"] as? String - } - // Read QUIC metadata for native app-to-app routing; WS remains fallback. - if let data = try? Data(contentsOf: URL(fileURLWithPath: quicInfoPath)), - let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] { - if let port = json["quic_port"] as? Int { - self.daemon.quicAddr = "\(localIPAddress()):\(port)" - } - self.daemon.quicCertHash = json["quic_cert_hash"] as? String - } + self.daemon.refreshAdvertisedTransport(host: localIPAddress()) self.signaling.start( localUrl: "ws://127.0.0.1:3001", cloudUrl: "wss://bolt-rendezvous.fly.dev", @@ -239,6 +248,15 @@ struct ContentView: View { } } } + .onChange(of: signaling.userNotice) { + guard let notice = signaling.userNotice else { return } + clearConnectingUI() + DispatchQueue.main.asyncAfter(deadline: .now() + 4.0) { + if signaling.userNotice == notice { + signaling.userNotice = nil + } + } + } // S6: Track transfer start time for incoming receives .onChange(of: ipc.transferPhase.isActive) { if ipc.transferPhase.isActive && transferStartTime == nil { @@ -363,6 +381,21 @@ struct ContentView: View { discoveryContent } + if let notice = signaling.userNotice { + Rectangle().fill(.white.opacity(0.06)).frame(height: 1) + HStack(spacing: 8) { + Image(systemName: "exclamationmark.triangle") + .font(.system(size: 12)) + .foregroundColor(.yellow.opacity(0.8)) + Text(notice) + .font(.system(size: 12)) + .foregroundColor(.white.opacity(0.6)) + Spacer() + } + .padding(.horizontal, 16) + .padding(.vertical, 10) + } + // M2: Declined-by-remote inline notice if let notice = declinedNotice { Rectangle().fill(.white.opacity(0.06)).frame(height: 1) @@ -510,7 +543,7 @@ struct ContentView: View { .foregroundColor(.white.opacity(0.4)) .frame(width: 20) // S1: Device name only — peer code removed for cleaner discovery - Text(peer.deviceName) + Text(BoltBridge.displayDeviceName(peer.deviceName)) .font(.system(size: 13)) .foregroundColor(.white.opacity(0.8)) Spacer() @@ -546,14 +579,14 @@ struct ContentView: View { VStack(spacing: 4) { switch connectingPhase { case .requesting: - Text("Waiting for **\(target.deviceName)** to accept...") + Text("Waiting for **\(BoltBridge.displayDeviceName(target.deviceName))** to accept...") .font(.system(size: 13)) .foregroundColor(.white.opacity(0.8)) Text("The other device will be asked to confirm") .font(.system(size: 11)) .foregroundColor(.white.opacity(0.3)) case .establishing: - Text("Establishing secure connection with **\(target.deviceName)**...") + Text("Establishing secure connection with **\(BoltBridge.displayDeviceName(target.deviceName))**...") .font(.system(size: 13)) .foregroundColor(.white.opacity(0.8)) Text("Setting up encrypted channel") @@ -561,7 +594,7 @@ struct ContentView: View { .foregroundColor(.white.opacity(0.3)) case .slow: // S2: Actionable slow-connection copy - Text("Still connecting to **\(target.deviceName)**...") + Text("Still connecting to **\(BoltBridge.displayDeviceName(target.deviceName))**...") .font(.system(size: 13)) .foregroundColor(.white.opacity(0.8)) Text("Check that both devices are on the same network") @@ -604,7 +637,7 @@ struct ContentView: View { } .padding(.top, 8) - Text("Establishing secure connection with **\(deviceName)**...") + Text("Establishing secure connection with **\(BoltBridge.displayDeviceName(deviceName))**...") .font(.system(size: 13)) .foregroundColor(.white.opacity(0.8)) .multilineTextAlignment(.center) @@ -628,7 +661,7 @@ struct ContentView: View { // MARK: - Incoming Request (inline) private func incomingRequestContent(request: IncomingSignal) -> some View { - let deviceName = request.data["deviceName"] as? String ?? "Unknown Device" + let deviceName = BoltBridge.displayDeviceName(request.data["deviceName"] as? String ?? "Unknown Device") let deviceType = request.data["deviceType"] as? String ?? "desktop" return VStack(spacing: 12) { @@ -664,8 +697,18 @@ struct ContentView: View { .tint(.red.opacity(0.8)) Button(action: { + let host = localIPAddress() + daemon.refreshAdvertisedTransport(host: host) + let requesterWs = request.data["wsUrl"] as? String ?? "" + if requesterWs.isEmpty && !daemon.hasLiveWebTransport { + signaling.incomingConnectionRequest = nil + ipc.resetSession() + signaling.userNotice = wtListenerNotReadyNotice + print("[CONNECT] refusing browser accept — no live WebTransport listener") + return + } let wsPort = daemon.wsPort - let wsUrl = "ws://\(localIPAddress()):\(wsPort)" + let wsUrl = "ws://\(host):\(wsPort)" // Stash peer info before accepting so a fast inbound session // can resolve the connected peer deterministically. ipc.pendingAcceptPeer = PeerSession( @@ -715,7 +758,7 @@ struct ContentView: View { .font(.system(size: 20)) .foregroundColor(neon) VStack(alignment: .leading, spacing: 1) { - Text(peer.deviceName) + Text(BoltBridge.displayDeviceName(peer.deviceName)) .font(.system(size: 14, weight: .semibold)) .foregroundColor(.white.opacity(0.9)) trustLabel(peer: peer) @@ -736,7 +779,7 @@ struct ContentView: View { ipc.disconnectSession(reason: "user initiated") } } message: { - Text("This will end the secure session with \(peer.deviceName).") + Text("This will end the secure session with \(BoltBridge.displayDeviceName(peer.deviceName)).") } } .padding(.horizontal, 16) @@ -1124,9 +1167,12 @@ struct ContentView: View { } // Send connection_request with wsUrl plus optional WT/QUIC metadata. + // Re-read the daemon's endpoint files so a leftover wt_info.json cannot be advertised. + let host = localIPAddress() + daemon.refreshAdvertisedTransport(host: host) let wsPort = daemon.wsPort - let wsUrl = "ws://\(localIPAddress()):\(wsPort)" - let deviceName = Host.current().localizedName ?? "Mac" + let wsUrl = "ws://\(host):\(wsPort)" + let deviceName = LocalDeviceName.current() var payloadDict: [String: String] = [ "deviceName": deviceName, "deviceType": "desktop", diff --git a/native/macos/Sources/LocalBolt/LocalDeviceName.swift b/native/macos/Sources/LocalBolt/LocalDeviceName.swift new file mode 100644 index 0000000..6f161db --- /dev/null +++ b/native/macos/Sources/LocalBolt/LocalDeviceName.swift @@ -0,0 +1,36 @@ +import Foundation +import SystemConfiguration + +/// Computer name advertised to peers. +/// +/// `Host.localizedName` is NSHost, which on some Macs returns the wildcard bind +/// address `0.0.0.0` instead of the name in System Settings. Peers then list the +/// machine as "0.0.0.0". Prefer the System Configuration computer name, and never +/// advertise a bind address. +enum LocalDeviceName { + static func current() -> String { + for candidate in candidates() { + let preferred = BoltBridge.preferDeviceName(current: "", candidate: candidate) + if !preferred.isEmpty && !BoltBridge.deviceNameIsUnusable(preferred) { + return preferred + } + } + return "Mac" + } + + private static func candidates() -> [String] { + var names: [String] = [] + if let computer = SCDynamicStoreCopyComputerName(nil, nil) as String? { + names.append(computer) + } + if let localized = Host.current().localizedName { + names.append(localized) + } + var host = ProcessInfo.processInfo.hostName + if host.hasSuffix(".local") { + host.removeLast(".local".count) + } + names.append(host) + return names + } +} diff --git a/native/macos/Sources/LocalBolt/TransportAdvertisement.swift b/native/macos/Sources/LocalBolt/TransportAdvertisement.swift new file mode 100644 index 0000000..be56ae5 --- /dev/null +++ b/native/macos/Sources/LocalBolt/TransportAdvertisement.swift @@ -0,0 +1,100 @@ +import CBoltBridge +import Foundation + +struct AdvertisedEndpoint: Equatable { + let url: String + let certHash: String +} + +/// Reads daemon `wt_info.json` / `quic_info.json`. Empty and missing files are nil +/// so they compare equal to a "no baseline" snapshot. +enum TransportMetadataFile { + static func read(dataDir: String, name: String) -> String? { + guard !dataDir.isEmpty else { return nil } + let url = URL(fileURLWithPath: dataDir).appendingPathComponent(name) + guard let data = try? Data(contentsOf: url), + let text = String(data: data, encoding: .utf8) else { return nil } + let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines) + return trimmed.isEmpty ? nil : trimmed + } +} + +extension BoltBridge { + /// Live WebTransport URL + cert hash, or nil when the on-disk record is stale. + static func selectWt( + currentJSON: String?, + baselineJSON: String?, + wsPort: UInt16, + host: String + ) -> AdvertisedEndpoint? { + withOptionalCString(currentJSON) { current in + withOptionalCString(baselineJSON) { baseline in + host.withCString { hostPtr in + guard let ptr = bolt_select_wt_advertisement(current, baseline, wsPort, hostPtr) else { + return nil + } + defer { bolt_free_string(ptr) } + return parseAdvertisement(String(cString: ptr)) + } + } + } + } + + /// Live QUIC `host:port` + cert hash. Nil leaves the native path on WebSocket. + static func selectQuic( + currentJSON: String?, + baselineJSON: String?, + wsPort: UInt16, + host: String + ) -> AdvertisedEndpoint? { + withOptionalCString(currentJSON) { current in + withOptionalCString(baselineJSON) { baseline in + host.withCString { hostPtr in + guard let ptr = bolt_select_quic_advertisement(current, baseline, wsPort, hostPtr) else { + return nil + } + defer { bolt_free_string(ptr) } + return parseAdvertisement(String(cString: ptr)) + } + } + } + } + + /// Name shown in the device list. Never a bind address. + static func displayDeviceName(_ raw: String) -> String { + raw.withCString { ptr in + guard let out = bolt_device_display_name(ptr) else { return "Mac" } + defer { bolt_free_string(out) } + return String(cString: out) + } + } + + /// Keep a real name. Replace `0.0.0.0` (and other bind addresses) when a real one exists. + static func preferDeviceName(current: String, candidate: String) -> String { + current.withCString { currentPtr in + candidate.withCString { candidatePtr in + guard let out = bolt_prefer_device_name(currentPtr, candidatePtr) else { return current } + defer { bolt_free_string(out) } + return String(cString: out) + } + } + } + + static func deviceNameIsUnusable(_ name: String) -> Bool { + name.withCString { bolt_device_name_is_unusable($0) == 1 } + } + + private static func parseAdvertisement(_ json: String) -> AdvertisedEndpoint? { + guard let data = json.data(using: .utf8), + let obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any], + let url = obj["url"] as? String, !url.isEmpty, + let certHash = obj["certHash"] as? String, !certHash.isEmpty + else { return nil } + return AdvertisedEndpoint(url: url, certHash: certHash) + } +} + +private func withOptionalCString(_ value: String?, _ body: (UnsafePointer?) -> T) -> T { + guard let value else { return body(nil) } + return value.withCString { body($0) } +} diff --git a/native/shared/include/bolt_native_bridge.h b/native/shared/include/bolt_native_bridge.h index f1e6e9f..5c7ecae 100644 --- a/native/shared/include/bolt_native_bridge.h +++ b/native/shared/include/bolt_native_bridge.h @@ -29,6 +29,39 @@ int bolt_probe_signal_health(void); /// Free a string returned by any bolt_ function. void bolt_free_string(char* ptr); +/// Live WebTransport endpoint from wt_info.json, or null when the file is missing, +/// unchanged from the pre-spawn baseline, or not this daemon's WS+1 port. +/// Returned JSON is `{"url":"https://host:port","certHash":"...","port":N}`. +/// `baseline_json` may be null when the file did not exist before spawn. +/// Caller frees a non-null return with bolt_free_string. +char* bolt_select_wt_advertisement( + const char* current_json, + const char* baseline_json, + uint16_t ws_port, + const char* host +); + +/// Live QUIC endpoint from quic_info.json, or null for the same reasons as +/// bolt_select_wt_advertisement. `url` is `host:port` (WS+2, no scheme). +/// Caller frees a non-null return with bolt_free_string. +char* bolt_select_quic_advertisement( + const char* current_json, + const char* baseline_json, + uint16_t ws_port, + const char* host +); + +/// 1 when `name` is blank or a bind address (`0.0.0.0`, `::`, `0.0.0.0:port`). +int bolt_device_name_is_unusable(const char* name); + +/// Name to show in the UI. Bind addresses and blanks become "Mac". +/// Caller frees with bolt_free_string. +char* bolt_device_display_name(const char* raw); + +/// Keep a usable `current`. Replace an unusable `current` with a usable `candidate`. +/// Caller frees with bolt_free_string. +char* bolt_prefer_device_name(const char* current, const char* candidate); + // ── Daemon Lifecycle ──────────────────────────────────────── /// Opaque daemon handle. diff --git a/native/shared/src/advertise_policy.rs b/native/shared/src/advertise_policy.rs new file mode 100644 index 0000000..cd4b3cf --- /dev/null +++ b/native/shared/src/advertise_policy.rs @@ -0,0 +1,477 @@ +//! Which daemon endpoints and peer names are safe to show or advertise. +//! +//! `wt_info.json` and `quic_info.json` live in the persistent daemon data directory. +//! The native shell used to read whichever file was already on disk at startup and +//! then keep that snapshot. The daemon's WS port is `9100 + (app_pid % 900)` and +//! WebTransport listens on WS+1, so a leftover file from the previous launch points +//! browsers at a port nothing is bound to. Browser peers (localbolt.app) dial the +//! `wtUrl` / `certHash` in `connection_request` and `connection_accepted`, and an +//! HTTPS page cannot fall back to `ws://`, so that stale port hangs the transfer. +//! +//! A record is live only when its bytes differ from the pre-spawn snapshot (or the +//! file did not exist yet) AND the port is the one this process asked the daemon to +//! bind. Peer display names follow the same rule in the other direction: a bind +//! address such as `0.0.0.0` (what `Host.localizedName` returns on some Macs) is +//! never shown when a real device name is available. + +use serde_json::Value; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct EndpointAdvertisement { + pub port: u16, + pub cert_hash: String, + pub url: String, +} + +/// True when `current_json` is a non-empty document written after `baseline_json`. +/// +/// Identical bytes are the previous launch's file. A missing baseline means the +/// file was created by this launch. +pub fn metadata_is_current(current_json: Option<&str>, baseline_json: Option<&str>) -> bool { + let Some(current) = nonempty(current_json) else { + return false; + }; + match nonempty(baseline_json) { + None => true, + Some(baseline) => current != baseline, + } +} + +pub fn select_wt_advertisement( + current_json: Option<&str>, + baseline_json: Option<&str>, + ws_port: u16, + host: &str, +) -> Option { + select_endpoint(EndpointQuery { + current_json, + baseline_json, + ws_port, + port_offset: 1, + port_key: "wt_port", + hash_key: "wt_cert_hash", + host, + https: true, + }) +} + +pub fn select_quic_advertisement( + current_json: Option<&str>, + baseline_json: Option<&str>, + ws_port: u16, + host: &str, +) -> Option { + select_endpoint(EndpointQuery { + current_json, + baseline_json, + ws_port, + port_offset: 2, + port_key: "quic_port", + hash_key: "quic_cert_hash", + host, + https: false, + }) +} + +struct EndpointQuery<'a> { + current_json: Option<&'a str>, + baseline_json: Option<&'a str>, + ws_port: u16, + port_offset: u16, + port_key: &'a str, + hash_key: &'a str, + host: &'a str, + https: bool, +} + +fn select_endpoint(query: EndpointQuery<'_>) -> Option { + if !metadata_is_current(query.current_json, query.baseline_json) { + return None; + } + let expected = query.ws_port.checked_add(query.port_offset)?; + let value: Value = serde_json::from_str(query.current_json?.trim()).ok()?; + let port = json_port(value.get(query.port_key)?)?; + if port != expected { + return None; + } + let hash = value.get(query.hash_key)?.as_str()?.trim(); + if !is_cert_hash(hash) { + return None; + } + let url = endpoint_url(query.host, port, query.https)?; + Some(EndpointAdvertisement { + port, + cert_hash: hash.to_string(), + url, + }) +} + +fn json_port(value: &Value) -> Option { + if let Some(n) = value.as_u64() { + return u16::try_from(n).ok(); + } + if let Some(n) = value.as_i64() { + return u16::try_from(n).ok(); + } + if let Some(s) = value.as_str() { + return s.trim().parse().ok(); + } + None +} + +fn is_cert_hash(hash: &str) -> bool { + (32..=128).contains(&hash.len()) && hash.chars().all(|c| c.is_ascii_hexdigit()) +} + +fn endpoint_url(host: &str, port: u16, https: bool) -> Option { + let host = host.trim(); + if !host_is_usable(host) { + return None; + } + if https { + Some(format!("https://{host}:{port}")) + } else { + Some(format!("{host}:{port}")) + } +} + +pub fn host_is_usable(host: &str) -> bool { + let host = host.trim(); + !host.is_empty() && !is_bind_address(host) +} + +pub fn is_bind_address(name: &str) -> bool { + matches!( + name.trim().to_ascii_lowercase().as_str(), + "0.0.0.0" | "::" | "::0" | "https://example.org/b/zenith" | "[::]" | "[::0]" | "*" + ) +} + +/// Empty names and bind addresses are not human device names. +/// A value that is only `0.0.0.0` or `https://0.0.0.0:port` is the wildcard +/// listen address, not `Host.localizedName`. +pub fn device_name_is_unusable(name: &str) -> bool { + let trimmed = name.trim(); + if trimmed.is_empty() || is_bind_address(trimmed) { + return true; + } + if let Some(host) = host_of_endpoint_shaped_name(trimmed) { + return is_bind_address(host); + } + false +} + +fn host_of_endpoint_shaped_name(name: &str) -> Option<&str> { + let without_scheme = name.split_once("://").map(|(_, rest)| rest).unwrap_or(name); + let hostport = without_scheme.split(['/', '?', '#']).next()?.trim(); + if hostport.is_empty() { + return None; + } + let (host, port) = hostport.rsplit_once(':')?; + if port.is_empty() || !port.chars().all(|c| c.is_ascii_digit()) { + return None; + } + // IPv6 literals contain extra colons; only split host:port for names and IPv4. + if host.contains(':') { + return None; + } + Some(host) +} + +/// Keep a usable current name. An unusable current name yields a usable candidate. +pub fn prefer_device_name<'a>(current: &'a str, candidate: &'a str) -> &'a str { + if device_name_is_unusable(current) && !device_name_is_unusable(candidate) { + candidate.trim() + } else { + current + } +} + +pub fn display_device_name(raw: &str) -> String { + let trimmed = raw.trim(); + if device_name_is_unusable(trimmed) { + "Mac".to_string() + } else { + trimmed.to_string() + } +} + +fn nonempty(value: Option<&str>) -> Option<&str> { + value.map(str::trim).filter(|s| !s.is_empty()) +} + +fn advertisement_json(ad: &EndpointAdvertisement) -> String { + serde_json::json!({ + "url": ad.url, + "certHash": ad.cert_hash, + "port": ad.port, + }) + .to_string() +} + +fn cstr_owned(ptr: *const std::os::raw::c_char) -> String { + if ptr.is_null() { + return String::new(); + } + unsafe { std::ffi::CStr::from_ptr(ptr).to_string_lossy().into_owned() } +} + +fn owned_c_string(value: String) -> *mut std::os::raw::c_char { + std::ffi::CString::new(value) + .map(|cs| cs.into_raw()) + .unwrap_or(std::ptr::null_mut()) +} + +/// JSON `{"url","certHash","port"}` for the live WT listener, or null. +/// +/// # Safety +/// String pointers must be null or valid nul-terminated UTF-8. The caller frees +/// a non-null return with `bolt_free_string`. +#[no_mangle] +pub unsafe extern "C" fn bolt_select_wt_advertisement( + current_json: *const std::os::raw::c_char, + baseline_json: *const std::os::raw::c_char, + ws_port: u16, + host: *const std::os::raw::c_char, +) -> *mut std::os::raw::c_char { + let current_owned = cstr_owned(current_json); + let baseline_owned = cstr_owned(baseline_json); + let host_owned = cstr_owned(host); + let current = nonempty(Some(current_owned.as_str())); + let baseline = nonempty(Some(baseline_owned.as_str())); + match select_wt_advertisement(current, baseline, ws_port, host_owned.as_str()) { + Some(ad) => owned_c_string(advertisement_json(&ad)), + None => std::ptr::null_mut(), + } +} + +/// JSON `{"url","certHash","port"}` for the live QUIC listener, or null. +/// `url` is `host:port` (no scheme), matching the native `quicAddr` field. +/// +/// # Safety +/// String pointers must be null or valid nul-terminated UTF-8. The caller frees +/// a non-null return with `bolt_free_string`. +#[no_mangle] +pub unsafe extern "C" fn bolt_select_quic_advertisement( + current_json: *const std::os::raw::c_char, + baseline_json: *const std::os::raw::c_char, + ws_port: u16, + host: *const std::os::raw::c_char, +) -> *mut std::os::raw::c_char { + let current_owned = cstr_owned(current_json); + let baseline_owned = cstr_owned(baseline_json); + let host_owned = cstr_owned(host); + let current = nonempty(Some(current_owned.as_str())); + let baseline = nonempty(Some(baseline_owned.as_str())); + match select_quic_advertisement(current, baseline, ws_port, host_owned.as_str()) { + Some(ad) => owned_c_string(advertisement_json(&ad)), + None => std::ptr::null_mut(), + } +} + +/// 1 when `name` must not be shown as a device name. +/// +/// # Safety +/// `name` must be null or a valid nul-terminated UTF-8 string. +#[no_mangle] +pub unsafe extern "C" fn bolt_device_name_is_unusable(name: *const std::os::raw::c_char) -> i32 { + if device_name_is_unusable(&cstr_owned(name)) { + 1 + } else { + 0 + } +} + +/// Device name to display. Bind addresses and blanks become `"Mac"`. +/// +/// # Safety +/// `raw` must be null or a valid nul-terminated UTF-8 string. Caller frees the +/// result with `bolt_free_string`. +#[no_mangle] +pub unsafe extern "C" fn bolt_device_display_name( + raw: *const std::os::raw::c_char, +) -> *mut std::os::raw::c_char { + owned_c_string(display_device_name(&cstr_owned(raw))) +} + +/// Usable `current` wins. An unusable `current` is replaced by a usable `candidate`. +/// +/// # Safety +/// Pointers must be null or valid nul-terminated UTF-8. Caller frees the result +/// with `bolt_free_string`. +#[no_mangle] +pub unsafe extern "C" fn bolt_prefer_device_name( + current: *const std::os::raw::c_char, + candidate: *const std::os::raw::c_char, +) -> *mut std::os::raw::c_char { + let current = cstr_owned(current); + let candidate = cstr_owned(candidate); + owned_c_string(prefer_device_name(¤t, &candidate).to_string()) +} + +#[cfg(test)] +mod tests { + use super::*; + + const HASH: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; + const OTHER: &str = "fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210"; + + fn wt(port: u16, hash: &str) -> String { + format!(r#"{{"wt_port":{port},"wt_cert_hash":"{hash}"}}"#) + } + + fn quic(port: u16, hash: &str) -> String { + format!(r#"{{"quic_port":{port},"quic_cert_hash":"{hash}"}}"#) + } + + #[test] + fn leftover_wt_file_is_not_advertised() { + // Same port as this launch (pid collision) but the cert bytes never changed. + let stale = wt(9101, HASH); + assert!(select_wt_advertisement(Some(&stale), Some(&stale), 9100, "10.0.0.5").is_none()); + } + + #[test] + fn rewritten_wt_file_matching_ws_plus_one_is_advertised() { + let baseline = wt(9001, OTHER); + let live = wt(9101, HASH); + let ad = select_wt_advertisement(Some(&live), Some(&baseline), 9100, "10.0.0.5").unwrap(); + assert_eq!(ad.port, 9101); + assert_eq!(ad.cert_hash, HASH); + assert_eq!(ad.url, "https://10.0.0.5:9101"); + } + + #[test] + fn fresh_file_with_the_wrong_port_is_rejected() { + let baseline = wt(9001, OTHER); + let live = wt(9999, HASH); + assert!(select_wt_advertisement(Some(&live), Some(&baseline), 9100, "10.0.0.5").is_none()); + } + + #[test] + fn file_created_this_launch_is_advertised() { + let live = wt(9101, HASH); + let ad = select_wt_advertisement(Some(&live), None, 9100, "192.168.1.20").unwrap(); + assert_eq!(ad.url, "https://192.168.1.20:9101"); + } + + #[test] + fn missing_or_invalid_wt_file_is_not_advertised() { + assert!(select_wt_advertisement(None, None, 9100, "10.0.0.5").is_none()); + assert!(select_wt_advertisement(Some(""), Some(""), 9100, "10.0.0.5").is_none()); + assert!(select_wt_advertisement(Some("{"), None, 9100, "10.0.0.5").is_none()); + assert!(select_wt_advertisement(Some(&wt(9101, "zz")), None, 9100, "10.0.0.5").is_none()); + assert!(select_wt_advertisement(Some(&wt(9101, "abc")), None, 9100, "10.0.0.5").is_none()); + } + + #[test] + fn bind_address_host_is_not_advertised() { + let live = wt(9101, HASH); + assert!(select_wt_advertisement(Some(&live), None, 9100, "0.0.0.0").is_none()); + assert!(select_wt_advertisement(Some(&live), None, 9100, "::").is_none()); + assert!(select_wt_advertisement(Some(&live), None, 9100, " ").is_none()); + } + + #[test] + fn quic_uses_ws_plus_two_and_has_no_scheme() { + let baseline = quic(1, OTHER); + let live = quic(9102, HASH); + let ad = select_quic_advertisement(Some(&live), Some(&baseline), 9100, "10.0.0.8").unwrap(); + assert_eq!(ad.url, "10.0.0.8:9102"); + assert_eq!(ad.cert_hash, HASH); + assert!(select_quic_advertisement(Some(&live), Some(&live), 9100, "10.0.0.8").is_none()); + } + + #[test] + fn port_string_and_overflow_are_handled() { + let live = format!(r#"{{"wt_port":"9101","wt_cert_hash":"{HASH}"}}"#); + assert!(select_wt_advertisement(Some(&live), None, 9100, "10.0.0.5").is_some()); + assert!(select_wt_advertisement(Some(&wt(0, HASH)), None, u16::MAX, "10.0.0.5").is_none()); + } + + #[test] + fn whitespace_only_change_does_not_count_as_rewritten() { + let pretty = format!("\n {{\"wt_port\":9101,\"wt_cert_hash\":\"{HASH}\"}} \n"); + let compact = wt(9101, HASH); + assert!(!metadata_is_current(Some(&pretty), Some(&compact))); + } + + #[test] + fn bind_address_device_name_loses_to_a_real_name() { + assert!(device_name_is_unusable("0.0.0.0")); + assert!(device_name_is_unusable(" :: ")); + assert!(device_name_is_unusable("")); + assert!(device_name_is_unusable("https://0.0.0.0:9101")); + assert!(device_name_is_unusable("0.0.0.0:4433")); + assert!(!device_name_is_unusable("Evan's Mac Studio")); + assert!(!device_name_is_unusable("Mac")); + assert_eq!( + prefer_device_name("0.0.0.0", "Evan's Mac Studio"), + "Evan's Mac Studio" + ); + assert_eq!( + prefer_device_name("Evan's Mac Studio", "0.0.0.0"), + "Evan's Mac Studio" + ); + assert_eq!(prefer_device_name("", "Mac Studio"), "Mac Studio"); + assert_eq!( + prefer_device_name("MacBook Pro", "Mac Studio"), + "MacBook Pro" + ); + assert_eq!(display_device_name("0.0.0.0"), "Mac"); + assert_eq!(display_device_name(" "), "Mac"); + assert_eq!(display_device_name(" Mac Studio "), "Mac Studio"); + } + + #[test] + fn ffi_select_wt_rejects_stale_and_returns_live_json() { + let stale = wt(9101, HASH); + let live = wt(9101, OTHER); + unsafe { + assert!(bolt_select_wt_advertisement( + std::ffi::CString::new(stale.as_str()).unwrap().as_ptr(), + std::ffi::CString::new(stale.as_str()).unwrap().as_ptr(), + 9100, + std::ffi::CString::new("10.0.0.5").unwrap().as_ptr(), + ) + .is_null()); + + let current = std::ffi::CString::new(live.as_str()).unwrap(); + let baseline = std::ffi::CString::new(stale.as_str()).unwrap(); + let host = std::ffi::CString::new("10.0.0.5").unwrap(); + let ptr = bolt_select_wt_advertisement( + current.as_ptr(), + baseline.as_ptr(), + 9100, + host.as_ptr(), + ); + assert!(!ptr.is_null()); + let json = std::ffi::CStr::from_ptr(ptr).to_str().unwrap(); + assert!(json.contains("https://10.0.0.5:9101")); + assert!(json.contains(OTHER)); + crate::bolt_free_string(ptr); + } + } + + #[test] + fn ffi_display_name_never_returns_bind_address() { + unsafe { + let raw = std::ffi::CString::new("0.0.0.0").unwrap(); + let ptr = bolt_device_display_name(raw.as_ptr()); + let shown = std::ffi::CStr::from_ptr(ptr).to_str().unwrap().to_string(); + crate::bolt_free_string(ptr); + assert_eq!(shown, "Mac"); + + let current = std::ffi::CString::new("0.0.0.0").unwrap(); + let candidate = std::ffi::CString::new("Mac Studio").unwrap(); + let preferred = bolt_prefer_device_name(current.as_ptr(), candidate.as_ptr()); + let name = std::ffi::CStr::from_ptr(preferred) + .to_str() + .unwrap() + .to_string(); + crate::bolt_free_string(preferred); + assert_eq!(name, "Mac Studio"); + assert_eq!(bolt_device_name_is_unusable(raw.as_ptr()), 1); + } + } +} diff --git a/native/shared/src/daemon.rs b/native/shared/src/daemon.rs index f9505d4..3a9ca51 100644 --- a/native/shared/src/daemon.rs +++ b/native/shared/src/daemon.rs @@ -60,7 +60,11 @@ pub(crate) fn daemon_candidate_paths( .join("bolt-daemon") .join("target/release/bolt-daemon"), ); - candidates.push(ancestor.join("bolt-daemon").join("target/debug/bolt-daemon")); + candidates.push( + ancestor + .join("bolt-daemon") + .join("target/debug/bolt-daemon"), + ); } } @@ -606,10 +610,8 @@ mod tests { fn lookup_tmp(tag: &str) -> PathBuf { static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); let n = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed); - let dir = std::env::temp_dir().join(format!( - "bolt-lookup-{tag}-{}-{n}", - std::process::id() - )); + let dir = + std::env::temp_dir().join(format!("bolt-lookup-{tag}-{}-{n}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); dir } diff --git a/native/shared/src/lib.rs b/native/shared/src/lib.rs index b3cbb5b..5828a33 100644 --- a/native/shared/src/lib.rs +++ b/native/shared/src/lib.rs @@ -26,6 +26,7 @@ use std::path::PathBuf; use std::process::{Child, Command, Stdio}; use std::sync::{Arc, Mutex}; +mod advertise_policy; mod daemon; mod ipc; mod signaling; diff --git a/native/shared/src/signaling.rs b/native/shared/src/signaling.rs index c1cc5dc..5814563 100644 --- a/native/shared/src/signaling.rs +++ b/native/shared/src/signaling.rs @@ -8,6 +8,8 @@ use bolt_app_core::signaling_client::{ self, DiscoveryEvent, PeerInfo, Plane, SignalingConfig, SignalingHandle, }; +use crate::advertise_policy::prefer_device_name; + /// Discovered peer (C-compatible). #[repr(C)] pub struct BoltPeer { @@ -122,26 +124,18 @@ pub unsafe extern "C" fn bolt_signaling_start( match &event { DiscoveryEvent::PeerList(list, _plane) => { let mut p = peers_cb.lock().unwrap(); - // Merge, skip self + // Merge, skip self. A later sighting can replace a bind-address + // name (0.0.0.0) with the peer's real device name. for peer in list { - if peer.peer_code != code_clone - && !p - .iter() - .any(|existing| existing.peer_code == peer.peer_code) - { - p.push(peer.clone()); + if peer.peer_code != code_clone { + upsert_discovered_peer(&mut p, peer.clone()); } } } DiscoveryEvent::PeerJoined(peer, plane) => { if peer.peer_code != code_clone { let mut p = peers_cb.lock().unwrap(); - if !p - .iter() - .any(|existing| existing.peer_code == peer.peer_code) - { - p.push(peer.clone()); - } + upsert_discovered_peer(&mut p, peer.clone()); events_cb .lock() .unwrap() @@ -391,6 +385,27 @@ pub unsafe extern "C" fn bolt_signaling_stop(handle: *mut BoltSignaling) { sig.handle.shutdown(); } +/// Insert a peer, or replace an unusable device name with a usable one. +/// +/// The first usable name wins. A later `0.0.0.0` (NSHost's bind-address fallback) +/// must not clobber "Mac Studio", and a later real name must replace `0.0.0.0`. +fn upsert_discovered_peer(peers: &mut Vec, incoming: PeerInfo) { + if let Some(existing) = peers + .iter_mut() + .find(|peer| peer.peer_code == incoming.peer_code) + { + let preferred = prefer_device_name(&existing.device_name, &incoming.device_name); + if preferred != existing.device_name { + existing.device_name = preferred.to_string(); + } + if existing.device_type.is_empty() && !incoming.device_type.is_empty() { + existing.device_type = incoming.device_type; + } + return; + } + peers.push(incoming); +} + fn cstr_to_string(ptr: *const c_char) -> String { if ptr.is_null() { return String::new(); @@ -547,6 +562,44 @@ mod tests { } } + #[test] + fn upsert_replaces_bind_address_and_keeps_a_real_name() { + let mut peers = vec![PeerInfo { + peer_code: "STUDIO".into(), + device_name: "0.0.0.0".into(), + device_type: "desktop".into(), + wt_url: None, + wt_cert_hash: None, + }]; + upsert_discovered_peer( + &mut peers, + PeerInfo { + peer_code: "STUDIO".into(), + device_name: "Evan's Mac Studio".into(), + device_type: "desktop".into(), + wt_url: None, + wt_cert_hash: None, + }, + ); + assert_eq!(peers[0].device_name, "Evan's Mac Studio"); + + upsert_discovered_peer( + &mut peers, + PeerInfo { + peer_code: "STUDIO".into(), + device_name: "0.0.0.0".into(), + device_type: "desktop".into(), + wt_url: None, + wt_cert_hash: None, + }, + ); + assert_eq!( + peers[0].device_name, "Evan's Mac Studio", + "a later bind address must not replace the real device name" + ); + assert_eq!(peers.len(), 1); + } + #[test] fn bolt_peer_with_nul_in_peer_code_yields_null_ptr() { // The identity field is equally attacker-controlled; a NUL there must be From 609862b75f4874a8f09a7c295335121512951747 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sat, 24 Oct 2026 15:17:19 +0000 Subject: [PATCH 2/2] fix(native): show the advertised peer on the pairing sheet The daemon ask sheet was rendering peer_addr as the device name and Accept copied that socket string over the signaling name, so the connected header showed a LAN IP and ephemeral port. Prefer the advertised name and type, and treat socket labels as unusable display names without changing which hosts are advertised for WebTransport. Co-authored-by: Evan Oberfelder --- .../macos/Sources/LocalBolt/BoltBridge.swift | 135 +++++++++---- .../Sources/LocalBolt/LocalBoltApp.swift | 55 +++--- .../LocalBolt/TransportAdvertisement.swift | 35 +++- native/shared/include/bolt_native_bridge.h | 20 +- native/shared/src/advertise_policy.rs | 183 +++++++++++++++++- 5 files changed, 357 insertions(+), 71 deletions(-) diff --git a/native/macos/Sources/LocalBolt/BoltBridge.swift b/native/macos/Sources/LocalBolt/BoltBridge.swift index 8f9fb11..59fa428 100644 --- a/native/macos/Sources/LocalBolt/BoltBridge.swift +++ b/native/macos/Sources/LocalBolt/BoltBridge.swift @@ -458,6 +458,25 @@ final class SignalingManager { userNotice = nil } + /// Human name and type for the peer currently being paired. + /// + /// The daemon ask sheet only has a socket address. Prefer the in-flight + /// connection request, otherwise the sole discovered peer. Several peers and + /// no request is ambiguous, so this returns nil and the caller keeps the + /// pending accept/initiator record. + func preferredInFlightIdentity() -> (name: String, type: String)? { + if let request = incomingConnectionRequest { + let name = request.data["deviceName"] as? String ?? "" + let type = request.data["deviceType"] as? String ?? "" + if !BoltBridge.deviceNameIsUnusable(name) { + return (name, type) + } + } + let named = peers.filter { !BoltBridge.deviceNameIsUnusable($0.deviceName) } + guard named.count == 1, let peer = named.first else { return nil } + return (peer.deviceName, peer.deviceType) + } + /// Remember a real device name learned from a connection payload when the /// discovery list still has a bind address. func notePeerDeviceName(peerCode: String, advertised: String) { @@ -738,6 +757,9 @@ final class IpcManager { var pendingAcceptPeer: PeerSession? /// Peer info stashed by initiator for name resolution on session.connected. var pendingInitiatorPeer: DiscoveredPeer? + /// Signaling name/type for the in-flight peer. The daemon pairing payload + /// only carries a socket address (`remote_device_name`) and `"unknown"`. + var advertisedPeerLookup: (() -> (name: String, type: String)?)? /// TOFU pin store for persistent identity verification. private(set) var pinStore: PinStore? @@ -895,18 +917,82 @@ final class IpcManager { } if decision.isAllow, let req = pendingRequest { + // Do not replace a signaling name with the daemon's peer_addr string. + let resolved = resolvePeerLabel(daemonName: req.deviceName, daemonType: req.deviceType) pendingAcceptPeer = PeerSession( - peerCode: req.requestId, - deviceName: req.deviceName, - deviceType: req.deviceType, + peerCode: pendingAcceptPeer?.peerCode ?? req.requestId, + deviceName: resolved.name, + deviceType: resolved.type, trust: req.sas.isEmpty ? .legacy : .unverified(sas: req.sas), - identityKeyB64: nil // resolved on session-connected + identityKeyB64: pendingAcceptPeer?.identityKeyB64 ) } pendingRequest = nil } + /// Prefer a signaling / pending peer name over the daemon socket label. + /// + /// bolt-daemon sets `remote_device_name` to `peer_addr` (`192.168.4.25:55170` + /// or the synthetic `0.0.0.0:0`) and `remote_device_type` to `"unknown"`. + /// `pendingAcceptPeer` and `pendingInitiatorPeer` already hold the advertised + /// identity. The lookup covers the ask sheet arriving before those are set, + /// and a single discovered peer when the request was already consumed. + func resolvePeerLabel(daemonName: String, daemonType: String) -> (name: String, type: String) { + var name = daemonName + var type = daemonType + func fold(_ candidateName: String, _ candidateType: String) { + name = BoltBridge.preferDeviceName(current: name, candidate: candidateName) + type = BoltBridge.preferDeviceType(current: type, candidate: candidateType) + } + if let pending = pendingAcceptPeer { + fold(pending.deviceName, pending.deviceType) + } + if let pending = pendingInitiatorPeer { + fold(pending.deviceName, pending.deviceType) + } + if let hinted = advertisedPeerLookup?() { + fold(hinted.name, hinted.type) + } + return (name, type) + } + + /// Copy the in-flight peer into `connectedPeer`, keeping a human name. + func adoptConnectedPeer(identityKey: String?) { + if let pending = pendingAcceptPeer { + let resolved = resolvePeerLabel(daemonName: pending.deviceName, daemonType: pending.deviceType) + connectedPeer = PeerSession( + peerCode: pending.peerCode, + deviceName: resolved.name, + deviceType: resolved.type, + trust: pending.trust, + identityKeyB64: identityKey ?? pending.identityKeyB64 + ) + pendingAcceptPeer = nil + } else if let target = pendingInitiatorPeer { + let resolved = resolvePeerLabel(daemonName: target.deviceName, daemonType: target.deviceType) + connectedPeer = PeerSession( + peerCode: identityKey ?? target.peerCode, + deviceName: resolved.name, + deviceType: resolved.type, + trust: .legacy, + identityKeyB64: identityKey + ) + pendingInitiatorPeer = nil + } else if let peerCode = identityKey { + let resolved = resolvePeerLabel(daemonName: "", daemonType: "") + let name = BoltBridge.deviceNameIsUnusable(resolved.name) ? "Peer" : resolved.name + let type = BoltBridge.deviceTypeIsPlaceholder(resolved.type) ? "desktop" : resolved.type + connectedPeer = PeerSession( + peerCode: peerCode, + deviceName: name, + deviceType: type, + trust: .legacy, + identityKeyB64: identityKey + ) + } + } + /// Approve the current session (user confirmed the SAS match). /// Item-6 / pre-EA1: session-scoped ONLY. This is NOT cryptographic device /// verification and is NOT persisted, so it does not survive a reconnect — the SAS @@ -958,11 +1044,14 @@ final class IpcManager { switch event { case "daemon://pairing-request": + let rawName = payload["remote_device_name"] as? String ?? "" + let rawType = payload["remote_device_type"] as? String ?? "" + let resolved = resolvePeerLabel(daemonName: rawName, daemonType: rawType) let req = PairingRequest( id: payload["request_id"] as? String ?? UUID().uuidString, requestId: payload["request_id"] as? String ?? "", - deviceName: payload["remote_device_name"] as? String ?? "Unknown Device", - deviceType: payload["remote_device_type"] as? String ?? "desktop", + deviceName: resolved.name, + deviceType: resolved.type, sas: payload["sas"] as? String ?? "" ) pendingRequest = req @@ -981,40 +1070,18 @@ final class IpcManager { } let remoteIdentityKey = payload["remote_peer_id"] as? String if markConnected() { - // Resolve peer info: acceptor has pendingAcceptPeer, - // initiator has pendingInitiatorPeer. - if let pending = pendingAcceptPeer { - var peer = pending - peer.identityKeyB64 = remoteIdentityKey - connectedPeer = peer - pendingAcceptPeer = nil - } else if let target = pendingInitiatorPeer { - let remotePk = remoteIdentityKey ?? target.peerCode - connectedPeer = PeerSession( - peerCode: remotePk, - deviceName: target.deviceName, - deviceType: target.deviceType, - trust: .legacy, - identityKeyB64: remoteIdentityKey - ) - pendingInitiatorPeer = nil - } else if let peerCode = remoteIdentityKey { - connectedPeer = PeerSession( - peerCode: peerCode, - deviceName: "Peer", - deviceType: "desktop", - trust: .legacy, - identityKeyB64: remoteIdentityKey - ) - } + adoptConnectedPeer(identityKey: remoteIdentityKey) } case "daemon://session-sas": if let sas = payload["sas"] as? String { let identityKey = payload["remote_identity_pk_b64"] as? String ?? connectedPeer?.identityKeyB64 - let peerName = connectedPeer?.deviceName - // M7: Check for TOFU identity mismatch before anything else + let peerName = connectedPeer.flatMap { peer -> String? in + BoltBridge.deviceNameIsUnusable(peer.deviceName) ? nil : peer.deviceName + } + // M7: Check for TOFU identity mismatch before anything else. + // A socket address is not a device name, so it is not pinned. if let key = identityKey, let name = peerName, let oldKey = pinStore?.checkMismatch(identityKeyB64: key, deviceName: name) { connectedPeer?.trust = .mismatch(deviceName: name, oldKeyPrefix: oldKey) diff --git a/native/macos/Sources/LocalBolt/LocalBoltApp.swift b/native/macos/Sources/LocalBolt/LocalBoltApp.swift index b8c5268..625950c 100644 --- a/native/macos/Sources/LocalBolt/LocalBoltApp.swift +++ b/native/macos/Sources/LocalBolt/LocalBoltApp.swift @@ -23,7 +23,7 @@ private func localIPAddress() -> String { getnameinfo(ptr.pointee.ifa_addr, socklen_t(sa.sa_len), &hostname, socklen_t(hostname.count), nil, 0, NI_NUMERICHOST) let candidate = String(cString: hostname) - if BoltBridge.deviceNameIsUnusable(candidate) { continue } + if !BoltBridge.hostIsUsable(candidate) { continue } address = candidate break } @@ -73,6 +73,9 @@ struct LocalBoltApp: App { /// Wire incoming signal handler so connection_request signals surface as pairing requests. private func wireSignalingHandler() { + ipc.advertisedPeerLookup = { [signaling] in + signaling.preferredInFlightIdentity() + } signaling.onIncomingSignal = { [self] signal in switch signal.signalType { case "connection_request": @@ -270,22 +273,11 @@ struct ContentView: View { // state machine here so the UI reflects the connected session. .onChange(of: daemon.wtSessionActive) { if daemon.wtSessionActive && ipc.sessionPhase == .connecting { - _ = ipc.markConnected() - if let pending = ipc.pendingAcceptPeer { - ipc.connectedPeer = pending - ipc.pendingAcceptPeer = nil - } else if let target = ipc.pendingInitiatorPeer { - ipc.connectedPeer = PeerSession( - peerCode: target.peerCode, - deviceName: target.deviceName, - deviceType: target.deviceType, - trust: .legacy, - identityKeyB64: nil - ) - ipc.pendingInitiatorPeer = nil + if ipc.markConnected() { + ipc.adoptConnectedPeer(identityKey: nil) + applyWtVerificationCode(daemon.wtSessionSAS) + print("[WT-DETECT] Advanced to .connected from daemon stderr") } - applyWtVerificationCode(daemon.wtSessionSAS) - print("[WT-DETECT] Advanced to .connected from daemon stderr") } if !daemon.wtSessionActive && ipc.sessionPhase == .connected { ipc.disconnectSession(reason: "WT session ended") @@ -661,8 +653,10 @@ struct ContentView: View { // MARK: - Incoming Request (inline) private func incomingRequestContent(request: IncomingSignal) -> some View { - let deviceName = BoltBridge.displayDeviceName(request.data["deviceName"] as? String ?? "Unknown Device") - let deviceType = request.data["deviceType"] as? String ?? "desktop" + let advertisedName = request.data["deviceName"] as? String ?? "" + let advertisedType = request.data["deviceType"] as? String ?? "" + let deviceName = BoltBridge.displayDeviceName(advertisedName) + let deviceType = BoltBridge.deviceTypeIsPlaceholder(advertisedType) ? "desktop" : advertisedType return VStack(spacing: 12) { HStack(spacing: 10) { @@ -713,8 +707,8 @@ struct ContentView: View { // can resolve the connected peer deterministically. ipc.pendingAcceptPeer = PeerSession( peerCode: request.from, - deviceName: deviceName, - deviceType: deviceType, + deviceName: advertisedName, + deviceType: advertisedType, trust: .legacy, identityKeyB64: nil // resolved on session-connected ) @@ -1283,6 +1277,17 @@ struct PairingRequestView: View { /// is something the person opts into rather than the default outcome. @State private var rememberDevice = false + /// Socket labels from the daemon (`0.0.0.0:0`, `192.168.4.25:55170`) render as "Mac" + /// only when signaling never advertised a real name. + private var nameLabel: String { + BoltBridge.displayDeviceName(request.deviceName) + } + + /// The daemon sends `unknown`. Hide that placeholder; show laptop/desktop when known. + private var typeLabel: String { + BoltBridge.displayDeviceType(request.deviceType) + } + var body: some View { VStack(spacing: 20) { Image(systemName: "person.crop.circle.badge.questionmark") @@ -1294,11 +1299,13 @@ struct PairingRequestView: View { .fontWeight(.bold) VStack(spacing: 4) { - Text(request.deviceName) + Text(nameLabel) .font(.system(size: 15, weight: .semibold)) - Text(request.deviceType) - .font(.system(size: 12)) - .foregroundColor(.secondary) + if !typeLabel.isEmpty { + Text(typeLabel) + .font(.system(size: 12)) + .foregroundColor(.secondary) + } } if !request.sas.isEmpty { diff --git a/native/macos/Sources/LocalBolt/TransportAdvertisement.swift b/native/macos/Sources/LocalBolt/TransportAdvertisement.swift index be56ae5..1fd9704 100644 --- a/native/macos/Sources/LocalBolt/TransportAdvertisement.swift +++ b/native/macos/Sources/LocalBolt/TransportAdvertisement.swift @@ -60,7 +60,8 @@ extension BoltBridge { } } - /// Name shown in the device list. Never a bind address. + /// Name shown in the device list, ask sheet, and session header. + /// Socket labels and bind addresses become "Mac". static func displayDeviceName(_ raw: String) -> String { raw.withCString { ptr in guard let out = bolt_device_display_name(ptr) else { return "Mac" } @@ -69,7 +70,7 @@ extension BoltBridge { } } - /// Keep a real name. Replace `0.0.0.0` (and other bind addresses) when a real one exists. + /// Keep a real name. Replace a socket label or bind address when a real one exists. static func preferDeviceName(current: String, candidate: String) -> String { current.withCString { currentPtr in candidate.withCString { candidatePtr in @@ -84,6 +85,36 @@ extension BoltBridge { name.withCString { bolt_device_name_is_unusable($0) == 1 } } + /// LAN addresses are usable URL hosts. `0.0.0.0` and `::` are not. + /// Distinct from `deviceNameIsUnusable`, which rejects every socket label. + static func hostIsUsable(_ host: String) -> Bool { + host.withCString { bolt_host_is_usable($0) == 1 } + } + + static func deviceTypeIsPlaceholder(_ typeName: String) -> Bool { + typeName.withCString { bolt_device_type_is_placeholder($0) == 1 } + } + + /// Keep a real type. Replace the daemon's `"unknown"` when signaling advertised one. + static func preferDeviceType(current: String, candidate: String) -> String { + current.withCString { currentPtr in + candidate.withCString { candidatePtr in + guard let out = bolt_prefer_device_type(currentPtr, candidatePtr) else { return current } + defer { bolt_free_string(out) } + return String(cString: out) + } + } + } + + /// Ask-sheet type label. `"unknown"` becomes empty so the row can be omitted. + static func displayDeviceType(_ raw: String) -> String { + raw.withCString { ptr in + guard let out = bolt_device_display_type(ptr) else { return "" } + defer { bolt_free_string(out) } + return String(cString: out) + } + } + private static func parseAdvertisement(_ json: String) -> AdvertisedEndpoint? { guard let data = json.data(using: .utf8), let obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any], diff --git a/native/shared/include/bolt_native_bridge.h b/native/shared/include/bolt_native_bridge.h index 5c7ecae..465484e 100644 --- a/native/shared/include/bolt_native_bridge.h +++ b/native/shared/include/bolt_native_bridge.h @@ -51,10 +51,11 @@ char* bolt_select_quic_advertisement( const char* host ); -/// 1 when `name` is blank or a bind address (`0.0.0.0`, `::`, `0.0.0.0:port`). +/// 1 when `name` is blank, a bind address, or a socket label +/// (`0.0.0.0`, `::`, `0.0.0.0:0`, `192.168.4.25:55170`). Not for URL hosts. int bolt_device_name_is_unusable(const char* name); -/// Name to show in the UI. Bind addresses and blanks become "Mac". +/// Name to show in the UI. Socket labels, bind addresses, and blanks become "Mac". /// Caller frees with bolt_free_string. char* bolt_device_display_name(const char* raw); @@ -62,6 +63,21 @@ char* bolt_device_display_name(const char* raw); /// Caller frees with bolt_free_string. char* bolt_prefer_device_name(const char* current, const char* candidate); +/// 1 when `host` may appear in a wtUrl or quicAddr. LAN addresses are usable. +/// `0.0.0.0` and `::` are not. Distinct from bolt_device_name_is_unusable. +int bolt_host_is_usable(const char* host); + +/// 1 when `type_name` is blank or the daemon placeholder "unknown". +int bolt_device_type_is_placeholder(const char* type_name); + +/// Keep a real `current` type. Replace "unknown" with an advertised `candidate`. +/// Caller frees with bolt_free_string. +char* bolt_prefer_device_type(const char* current, const char* candidate); + +/// Type to show. "unknown" and blanks become an empty string. +/// Caller frees with bolt_free_string. +char* bolt_device_display_type(const char* raw); + // ── Daemon Lifecycle ──────────────────────────────────────── /// Opaque daemon handle. diff --git a/native/shared/src/advertise_policy.rs b/native/shared/src/advertise_policy.rs index cd4b3cf..3fa882a 100644 --- a/native/shared/src/advertise_policy.rs +++ b/native/shared/src/advertise_policy.rs @@ -12,7 +12,10 @@ //! file did not exist yet) AND the port is the one this process asked the daemon to //! bind. Peer display names follow the same rule in the other direction: a bind //! address such as `0.0.0.0` (what `Host.localizedName` returns on some Macs) is -//! never shown when a real device name is available. +//! never shown when a real device name is available. A socket label +//! (`192.168.4.25:55170`, `0.0.0.0:0`, `::`) is the same kind of placeholder: +//! the daemon's pairing IPC puts `peer_addr` in `remote_device_name`, and the +//! Mac sheet must keep the name signaling already advertised. use serde_json::Value; @@ -147,16 +150,33 @@ pub fn is_bind_address(name: &str) -> bool { ) } -/// Empty names and bind addresses are not human device names. -/// A value that is only `0.0.0.0` or `https://0.0.0.0:port` is the wildcard -/// listen address, not `Host.localizedName`. +/// Empty names, bind addresses, and socket labels are not human device names. +/// +/// `0.0.0.0` is the wildcard `Host.localizedName` returns on some Macs. +/// `0.0.0.0:0` and `192.168.4.25:55170` are what bolt-daemon writes into +/// `remote_device_name` (a synthetic WS address, or `peer_addr`). A LAN address +/// is still a usable WebTransport host — that check is [`host_is_usable`]. pub fn device_name_is_unusable(name: &str) -> bool { let trimmed = name.trim(); - if trimmed.is_empty() || is_bind_address(trimmed) { + if trimmed.is_empty() || is_bind_address(trimmed) || looks_like_ip_or_socket(trimmed) { return true; } if let Some(host) = host_of_endpoint_shaped_name(trimmed) { - return is_bind_address(host); + return is_bind_address(host) || looks_like_ip_or_socket(host); + } + false +} + +/// True for an IP address or `ip:port`, including bracketed IPv6. +fn looks_like_ip_or_socket(name: &str) -> bool { + let trimmed = name.trim(); + if trimmed.parse::().is_ok() + || trimmed.parse::().is_ok() + { + return true; + } + if let Some(inner) = trimmed.strip_prefix('[').and_then(|s| s.strip_suffix(']')) { + return inner.parse::().is_ok() || is_bind_address(inner); } false } @@ -167,17 +187,59 @@ fn host_of_endpoint_shaped_name(name: &str) -> Option<&str> { if hostport.is_empty() { return None; } + if let Some(rest) = hostport.strip_prefix('[') { + let (host, after) = rest.split_once(']')?; + if host.is_empty() { + return None; + } + if after.is_empty() { + return Some(host); + } + let port = after.strip_prefix(':')?; + if port.is_empty() || !port.chars().all(|c| c.is_ascii_digit()) { + return None; + } + return Some(host); + } let (host, port) = hostport.rsplit_once(':')?; - if port.is_empty() || !port.chars().all(|c| c.is_ascii_digit()) { + if host.is_empty() || port.is_empty() || !port.chars().all(|c| c.is_ascii_digit()) { return None; } - // IPv6 literals contain extra colons; only split host:port for names and IPv4. + // A bare IPv6 literal has more than one colon and no brackets. if host.contains(':') { return None; } Some(host) } +/// Daemon pairing IPC sends `remote_device_type: "unknown"`. That is not a +/// type the peer advertised. +pub fn device_type_is_placeholder(type_name: &str) -> bool { + matches!( + type_name.trim().to_ascii_lowercase().as_str(), + "" | "unknown" + ) +} + +/// Keep a real current type. A placeholder yields a candidate the peer advertised. +pub fn prefer_device_type<'a>(current: &'a str, candidate: &'a str) -> &'a str { + if device_type_is_placeholder(current) && !device_type_is_placeholder(candidate) { + candidate.trim() + } else { + current + } +} + +/// Type label for the ask sheet. Placeholders become empty so the UI can omit them. +pub fn display_device_type(raw: &str) -> String { + let trimmed = raw.trim(); + if device_type_is_placeholder(trimmed) { + String::new() + } else { + trimmed.to_string() + } +} + /// Keep a usable current name. An unusable current name yields a usable candidate. pub fn prefer_device_name<'a>(current: &'a str, candidate: &'a str) -> &'a str { if device_name_is_unusable(current) && !device_name_is_unusable(candidate) { @@ -282,7 +344,7 @@ pub unsafe extern "C" fn bolt_device_name_is_unusable(name: *const std::os::raw: } } -/// Device name to display. Bind addresses and blanks become `"Mac"`. +/// Device name to display. Socket labels, bind addresses, and blanks become `"Mac"`. /// /// # Safety /// `raw` must be null or a valid nul-terminated UTF-8 string. Caller frees the @@ -309,6 +371,62 @@ pub unsafe extern "C" fn bolt_prefer_device_name( owned_c_string(prefer_device_name(¤t, &candidate).to_string()) } +/// 1 when `host` may be advertised in a WebTransport or QUIC URL. +/// A LAN address is usable here even though it is not a device name. +/// +/// # Safety +/// `host` must be null or a valid nul-terminated UTF-8 string. +#[no_mangle] +pub unsafe extern "C" fn bolt_host_is_usable(host: *const std::os::raw::c_char) -> i32 { + if host_is_usable(&cstr_owned(host)) { + 1 + } else { + 0 + } +} + +/// 1 when `type_name` is blank or the daemon placeholder `"unknown"`. +/// +/// # Safety +/// `type_name` must be null or a valid nul-terminated UTF-8 string. +#[no_mangle] +pub unsafe extern "C" fn bolt_device_type_is_placeholder( + type_name: *const std::os::raw::c_char, +) -> i32 { + if device_type_is_placeholder(&cstr_owned(type_name)) { + 1 + } else { + 0 + } +} + +/// Keep a real `current` type. Replace `"unknown"` with an advertised `candidate`. +/// +/// # Safety +/// Pointers must be null or valid nul-terminated UTF-8. Caller frees the result +/// with `bolt_free_string`. +#[no_mangle] +pub unsafe extern "C" fn bolt_prefer_device_type( + current: *const std::os::raw::c_char, + candidate: *const std::os::raw::c_char, +) -> *mut std::os::raw::c_char { + let current = cstr_owned(current); + let candidate = cstr_owned(candidate); + owned_c_string(prefer_device_type(¤t, &candidate).to_string()) +} + +/// Type to show. `"unknown"` and blanks become an empty string. +/// +/// # Safety +/// `raw` must be null or a valid nul-terminated UTF-8 string. Caller frees the +/// result with `bolt_free_string`. +#[no_mangle] +pub unsafe extern "C" fn bolt_device_display_type( + raw: *const std::os::raw::c_char, +) -> *mut std::os::raw::c_char { + owned_c_string(display_device_type(&cstr_owned(raw))) +} + #[cfg(test)] mod tests { use super::*; @@ -423,6 +541,53 @@ mod tests { assert_eq!(display_device_name(" Mac Studio "), "Mac Studio"); } + #[test] + fn socket_address_device_name_loses_to_the_advertised_name() { + assert!(device_name_is_unusable("0.0.0.0:0")); + assert!(device_name_is_unusable("192.168.4.25:55170")); + assert!(device_name_is_unusable("192.168.4.25")); + assert!(device_name_is_unusable("::")); + assert!(device_name_is_unusable("::1")); + assert!(device_name_is_unusable("[::1]:55170")); + assert!(device_name_is_unusable("https://192.168.4.25:9101")); + assert!(device_name_is_unusable("https://[::1]:9101")); + assert!(!device_name_is_unusable("Evan's MacBook Pro")); + assert!(!device_name_is_unusable("Evan\u{2019}s MacBook Pro")); + assert!(!device_name_is_unusable("Mac")); + assert_eq!( + prefer_device_name("192.168.4.25:55170", "Evan\u{2019}s MacBook Pro"), + "Evan\u{2019}s MacBook Pro" + ); + assert_eq!( + prefer_device_name("0.0.0.0:0", "Evan's MacBook Pro"), + "Evan's MacBook Pro" + ); + assert_eq!( + prefer_device_name("Evan's MacBook Pro", "192.168.4.25:55170"), + "Evan's MacBook Pro" + ); + assert_eq!(display_device_name("192.168.4.25:55170"), "Mac"); + assert_eq!(display_device_name("0.0.0.0:0"), "Mac"); + // A LAN address is a bad device name and a good WebTransport host. + assert!(host_is_usable("192.168.4.25")); + assert!(host_is_usable("10.0.0.1")); + assert!(!host_is_usable("0.0.0.0")); + assert!(!host_is_usable("::")); + } + + #[test] + fn unknown_device_type_loses_to_the_advertised_type() { + assert!(device_type_is_placeholder("unknown")); + assert!(device_type_is_placeholder(" ")); + assert!(!device_type_is_placeholder("desktop")); + assert!(!device_type_is_placeholder("laptop")); + assert_eq!(prefer_device_type("unknown", "laptop"), "laptop"); + assert_eq!(prefer_device_type("desktop", "unknown"), "desktop"); + assert_eq!(prefer_device_type("unknown", "unknown"), "unknown"); + assert_eq!(display_device_type("unknown"), ""); + assert_eq!(display_device_type(" desktop "), "desktop"); + } + #[test] fn ffi_select_wt_rejects_stale_and_returns_live_json() { let stale = wt(9101, HASH);