From e067ee5d9e6d944ea31142925bb094cc6f046aa6 Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Thu, 3 Sep 2026 16:53:49 -0700 Subject: [PATCH 01/33] test: persist removed iOS routes --- .../MobilePairedMacStoreTests.swift | 63 +++++++++++++++++++ 1 file changed, 63 insertions(+) diff --git a/Packages/iOS/CmuxMobilePairedMac/Tests/CmuxMobilePairedMacTests/MobilePairedMacStoreTests.swift b/Packages/iOS/CmuxMobilePairedMac/Tests/CmuxMobilePairedMacTests/MobilePairedMacStoreTests.swift index 0c447556f3ce..4eeea1c6bbf3 100644 --- a/Packages/iOS/CmuxMobilePairedMac/Tests/CmuxMobilePairedMacTests/MobilePairedMacStoreTests.swift +++ b/Packages/iOS/CmuxMobilePairedMac/Tests/CmuxMobilePairedMacTests/MobilePairedMacStoreTests.swift @@ -249,6 +249,69 @@ import Testing #expect(mac.legacyTailscaleRoutes == [tailscale]) } + @Test func removedRouteStaysHiddenAcrossRegistryRefreshAndReopen() async throws { + let (store, directory) = try makeStore() + defer { try? FileManager.default.removeItem(at: directory) } + let removed = try CmxAttachRoute( + id: "tailscale-old", + kind: .tailscale, + endpoint: .hostPort(host: "100.64.0.40", port: 8443) + ) + let refreshedRemoved = try CmxAttachRoute( + id: "tailscale-new", + kind: .tailscale, + endpoint: removed.endpoint + ) + let retained = try CmxAttachRoute( + id: "tailscale-retained", + kind: .tailscale, + endpoint: .hostPort(host: "100.64.0.41", port: 8443) + ) + + try await store.upsert( + macDeviceID: "tailscale-mac", + displayName: "Tailscale Mac", + routes: [removed, retained], + markActive: true, + stackUserID: "user-1", + now: Date(timeIntervalSince1970: 1) + ) + #expect( + try await store.removeRouteIfAuthorized( + macDeviceID: "tailscale-mac", + route: removed, + condition: .matchingInstanceTag(nil), + stackUserID: "user-1", + teamID: nil, + now: Date(timeIntervalSince1970: 2) + ) + ) + #expect(try await store.activeMac(stackUserID: "user-1")?.routes == [retained]) + + // Presence can immediately publish the same endpoint under a new route + // id. The endpoint tombstone must win over that registry refresh. + #expect( + try await store.upsertRoutesIfAuthorized( + macDeviceID: "tailscale-mac", + displayName: "Tailscale Mac", + routes: [refreshedRemoved, retained], + condition: .matchingInstanceTag(nil), + markActive: nil, + stackUserID: "user-1", + teamID: nil, + now: Date(timeIntervalSince1970: 3) + ) + ) + #expect(try await store.activeMac(stackUserID: "user-1")?.routes == [retained]) + + // A fresh store instance represents an app relaunch and must retain the + // local route choice. + let reopenedStore = try MobilePairedMacStore( + databaseURL: directory.appendingPathComponent("paired-macs.sqlite3") + ) + #expect(try await reopenedStore.activeMac(stackUserID: "user-1")?.routes == [retained]) + } + @Test func userEnteredPairingCodeMintsDeviceLocalGrant() async throws { let (store, directory) = try makeStore() defer { try? FileManager.default.removeItem(at: directory) } From 7cf8bce49c16f7c945b8eac456a1b1149aed7d90 Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Thu, 3 Sep 2026 16:53:53 -0700 Subject: [PATCH 02/33] fix: persist removed iOS route endpoints --- .../MobilePairedMacStore+Records.swift | 43 +++++ .../MobilePairedMacStore.swift | 170 +++++++++++++++++- .../MobilePairedMacStoring.swift | 56 ++++++ ...ingUpPairedMacStore+AuthorizedRoutes.swift | 37 ++++ .../DemoContentPairedMacStore.swift | 20 +++ .../IOSBuildScopedPairedMacStore.swift | 32 ++++ .../MobileMacCompatiblePairedMacStore.swift | 25 +++ .../MobileShellComposite+RouteRemoval.swift | 6 +- .../TeamScopedPairedMacStore.swift | 31 ++++ ...minalController+WorkspaceGroupAction.swift | 27 +-- 10 files changed, 431 insertions(+), 16 deletions(-) diff --git a/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore+Records.swift b/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore+Records.swift index 4b32d5ddc3fa..28929251257a 100644 --- a/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore+Records.swift +++ b/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore+Records.swift @@ -317,6 +317,35 @@ extension MobilePairedMacStore { } func fetchRoutes(macDeviceID: String, ownerKey: String) throws -> [CmxAttachRoute] { + var removedStatement: OpaquePointer? + defer { sqlite3_finalize(removedStatement) } + let removedRC = sqlite3_prepare_v2( + db, + """ + SELECT kind, endpoint_json + FROM mac_route_removals + WHERE mac_device_id = ? AND owner_key = ?; + """, + -1, + &removedStatement, + nil + ) + guard removedRC == SQLITE_OK else { + throw MobilePairedMacStoreError.prepareFailed(removedRC, lastErrorMessage()) + } + try bind( + statement: removedStatement, + parameters: [.text(macDeviceID), .text(ownerKey)] + ) + var removedKeys: Set = [] + while sqlite3_step(removedStatement) == SQLITE_ROW { + guard let kind = Self.readNullableText(removedStatement, column: 0), + let endpoint = Self.readNullableText(removedStatement, column: 1) else { + continue + } + removedKeys.insert("\(kind)\u{1F}\(endpoint)") + } + var statement: OpaquePointer? defer { sqlite3_finalize(statement) } let sql = """ @@ -341,6 +370,10 @@ extension MobilePairedMacStore { pairedMacStoreLog.warning("dropping unparsable route row") continue } + if let endpoint = try? Self.encodeRouteEndpoint(route), + removedKeys.contains("\(route.kind.rawValue)\u{1F}\(endpoint)") { + continue + } routes.append(route) } return routes @@ -393,6 +426,16 @@ extension MobilePairedMacStore { return string } + static func encodeRouteEndpoint(_ route: CmxAttachRoute) throws -> String { + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys] + let data = try encoder.encode(route.endpoint) + guard let string = String(data: data, encoding: .utf8) else { + throw MobilePairedMacStoreError.decodeFailed + } + return string + } + static func readNullableText(_ statement: OpaquePointer?, column: Int32) -> String? { guard let cString = sqlite3_column_text(statement, column) else { return nil } return String(cString: cString) diff --git a/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore.swift b/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore.swift index ab7356240aa8..31d4a2295086 100644 --- a/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore.swift +++ b/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore.swift @@ -14,7 +14,7 @@ let pairedMacStoreLog = Logger(subsystem: "com.cmuxterm.app", category: "PairedM /// inject it as `any MobilePairedMacStoring`. public actor MobilePairedMacStore: MobilePairedMacStoring { /// The schema version this build creates and migrates to. - public static let currentSchemaVersion: Int32 = 11 + public static let currentSchemaVersion: Int32 = 12 private let dbPath: String // `nonisolated(unsafe)` only so the (Swift 6 nonisolated) `deinit` can close @@ -232,6 +232,12 @@ public actor MobilePairedMacStore: MobilePairedMacStoring { "paired-mac store schema v\(version) is newer than this build (v\(Self.currentSchemaVersion)); reading known columns only" ) } + if version < 12 { + try transaction { + try migrateToV12() + try setUserVersion(12) + } + } } private func migrateToV1() throws { @@ -537,6 +543,31 @@ public actor MobilePairedMacStore: MobilePairedMacStoring { try exec("ALTER TABLE paired_macs ADD COLUMN direct_addresses TEXT;") } + /// v12: device-local route tombstones. A paired Mac can keep advertising a + /// route after the user removes it on this iPhone, so route refreshes must + /// remember the endpoint suppression independently of the host snapshot. + /// The table is intentionally not part of the backup record and is removed + /// with its paired-Mac row on forget/re-pair. + private func migrateToV12() throws { + try exec(""" + CREATE TABLE IF NOT EXISTS mac_route_removals ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + mac_device_id TEXT NOT NULL, + owner_key TEXT NOT NULL, + kind TEXT NOT NULL, + endpoint_json TEXT NOT NULL, + UNIQUE (mac_device_id, owner_key, kind, endpoint_json), + FOREIGN KEY (mac_device_id, owner_key) + REFERENCES paired_macs(mac_device_id, owner_key) + ON DELETE CASCADE + ); + """) + try exec(""" + CREATE INDEX IF NOT EXISTS idx_route_removals_device + ON mac_route_removals(mac_device_id, owner_key); + """) + } + /// Column names defined on `table` (via `PRAGMA table_info`), used to make /// additive column migrations idempotent. private func tableColumns(_ table: String) throws -> Set { @@ -644,6 +675,114 @@ public actor MobilePairedMacStore: MobilePairedMacStoring { ) } + /// Remove one route from a scoped pairing and persist an endpoint tombstone + /// so later registry/presence refreshes cannot resurrect it on this device. + @discardableResult + public func removeRouteIfAuthorized( + macDeviceID: String, + route: CmxAttachRoute, + condition: MobilePairedMacRouteWriteCondition, + stackUserID: String?, + teamID: String?, + now: Date + ) async throws -> Bool { + guard route.kind != .iroh else { return false } + try ensureReady() + let macDeviceID = cmxCanonicalDeviceID(macDeviceID) + let instanceTag: String? + switch condition { + case .matchingInstanceTag(let tag): instanceTag = tag + case .unclaimed: instanceTag = nil + } + let ownerKey = Self.ownerKey( + stackUserID: stackUserID, + teamID: teamID, + instanceTag: instanceTag + ) + var didWrite = false + try transaction { + guard let current = try fetchMacRow( + macDeviceID: macDeviceID, + ownerKey: ownerKey + ) else { return } + switch condition { + case .matchingInstanceTag(let expected): + guard CmxMacAppInstanceIdentity( + macDeviceID: current.macDeviceID, + instanceTag: current.instanceTag + ).id == CmxMacAppInstanceIdentity( + macDeviceID: macDeviceID, + instanceTag: expected + ).id else { return } + case .unclaimed: + guard current.instanceTag == nil, + !(try hasClaimedSibling( + macDeviceID: macDeviceID, + stackUserID: stackUserID, + teamID: teamID + )) else { return } + } + + let currentRoutes = try fetchRoutes( + macDeviceID: macDeviceID, + ownerKey: ownerKey + ) + guard let removed = currentRoutes.first(where: { $0.id == route.id }) + ?? currentRoutes.first(where: { + $0.kind == route.kind && $0.endpoint == route.endpoint + }) else { return } + let remaining = currentRoutes.filter { $0.id != removed.id } + guard !remaining.isEmpty else { return } + + let encoded = try Self.encodeRouteEndpoint(removed) + try exec(""" + INSERT OR IGNORE INTO mac_route_removals ( + mac_device_id, owner_key, kind, endpoint_json + ) VALUES (?, ?, ?, ?); + """, binding: [ + .text(macDeviceID), + .text(ownerKey), + .text(removed.kind.rawValue), + .text(encoded), + ]) + try upsertMacRow( + macDeviceID: macDeviceID, + ownerKey: ownerKey, + displayName: current.displayName, + instanceTag: current.instanceTag, + stackUserID: current.stackUserID, + teamID: current.teamID, + createdAt: current.createdAt, + lastSeenAt: now, + isActive: current.isActive + ) + try exec( + "DELETE FROM mac_routes WHERE mac_device_id = ? AND owner_key = ?;", + binding: [.text(macDeviceID), .text(ownerKey)] + ) + for remainingRoute in remaining { + guard let disclosed = remainingRoute.disclosed( + for: .authenticated, + at: now + ) else { continue } + try exec(""" + INSERT INTO mac_routes ( + mac_device_id, owner_key, route_id, kind, endpoint_json, priority + ) VALUES (?, ?, ?, ?, ?, ?); + """, binding: [ + .text(macDeviceID), + .text(ownerKey), + .text(remainingRoute.id), + .text(remainingRoute.kind.rawValue), + .text(try Self.encodeRoute(disclosed)), + .int(Int64(remainingRoute.priority)), + ]) + } + didWrite = true + } + return didWrite + } + /// Persist `'user'`-origin Tailscale compatibility grants for routes the /// user entered as a pairing code. Upgrades an existing `'migration'` grant /// for the same destination to `'user'`, so a deliberate re-scan is not @@ -1135,6 +1274,35 @@ public actor MobilePairedMacStore: MobilePairedMacStoring { instanceTag: String?, stackUserID: String? = nil, teamID: String? = nil + ) async throws { + try removeExactSync( + macDeviceID: macDeviceID, + instanceTag: instanceTag, + stackUserID: stackUserID, + teamID: teamID + ) + } + + /// Remove one tagged paired Mac in a specific owner scope. + public func remove( + macDeviceID: String, + instanceTag: String?, + stackUserID: String? = nil, + teamID: String? = nil + ) throws { + try removeExactSync( + macDeviceID: macDeviceID, + instanceTag: instanceTag, + stackUserID: stackUserID, + teamID: teamID + ) + } + + private func removeExactSync( + macDeviceID: String, + instanceTag: String?, + stackUserID: String? = nil, + teamID: String? = nil ) throws { try ensureReady() let macDeviceID = cmxCanonicalDeviceID(macDeviceID) diff --git a/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStoring.swift b/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStoring.swift index a260df6c4cf5..40325c0291f5 100644 --- a/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStoring.swift +++ b/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStoring.swift @@ -64,6 +64,20 @@ public protocol MobilePairedMacStoring: Sendable { now: Date ) async throws -> Bool + /// Remove one advertised route while retaining a local tombstone for its + /// endpoint. Reconnect and presence updates may continue to advertise a + /// route that the user removed on this device; the tombstone keeps that + /// route hidden until the paired Mac itself is forgotten and re-paired. + @discardableResult + func removeRouteIfAuthorized( + macDeviceID: String, + route: CmxAttachRoute, + condition: MobilePairedMacRouteWriteCondition, + stackUserID: String?, + teamID: String?, + now: Date + ) async throws -> Bool + /// Load all paired Macs, optionally scoped to a Stack user and team. /// - Parameters: /// - stackUserID: When set, returns only Macs owned by that user. @@ -227,6 +241,48 @@ public protocol MobilePairedMacStoring: Sendable { } extension MobilePairedMacStoring { + /// In-memory/test fallback for stores that do not persist route tombstones. + /// Production SQLite and scope decorators override this requirement. + @discardableResult + public func removeRouteIfAuthorized( + macDeviceID: String, + route: CmxAttachRoute, + condition: MobilePairedMacRouteWriteCondition, + stackUserID: String?, + teamID: String?, + now: Date + ) async throws -> Bool { + let instanceTag: String? + switch condition { + case .matchingInstanceTag(let tag): instanceTag = tag + case .unclaimed: instanceTag = nil + } + let current = try await loadAll(stackUserID: stackUserID, teamID: teamID) + .first { + cmxCanonicalDeviceID($0.macDeviceID) == cmxCanonicalDeviceID(macDeviceID) + && CmxMacAppInstanceIdentity( + macDeviceID: $0.macDeviceID, + instanceTag: $0.instanceTag + ).id == CmxMacAppInstanceIdentity( + macDeviceID: macDeviceID, + instanceTag: instanceTag + ).id + } + guard let current else { return false } + let remaining = current.routes.filter { $0.id != route.id } + guard remaining.count < current.routes.count, !remaining.isEmpty else { return false } + return try await upsertRoutesIfAuthorized( + macDeviceID: macDeviceID, + displayName: current.displayName, + routes: remaining, + condition: condition, + markActive: nil, + stackUserID: stackUserID, + teamID: teamID, + now: now + ) + } + /// Compatibility no-op for stores that predate per-Computer Direct /// addresses (test fixtures); the SQLite store and decorators override. public func setDirectAddresses( diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/BackingUpPairedMacStore+AuthorizedRoutes.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/BackingUpPairedMacStore+AuthorizedRoutes.swift index bfb87589f4f2..6e5e767ea16e 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/BackingUpPairedMacStore+AuthorizedRoutes.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/BackingUpPairedMacStore+AuthorizedRoutes.swift @@ -3,6 +3,43 @@ public import CmuxMobilePairedMac public import Foundation extension BackingUpPairedMacStore { + @discardableResult + public func removeRouteIfAuthorized( + macDeviceID: String, + route: CmxAttachRoute, + condition: MobilePairedMacRouteWriteCondition, + stackUserID: String?, + teamID: String?, + now: Date + ) async throws -> Bool { + let macDeviceID = cmxCanonicalDeviceID(macDeviceID) + let team = await resolvedTeam(teamID) + let instanceTag: String? + switch condition { + case .matchingInstanceTag(let tag): instanceTag = tag + case .unclaimed: instanceTag = nil + } + let wrote = try await inner.removeRouteIfAuthorized( + macDeviceID: macDeviceID, + route: route, + condition: condition, + stackUserID: stackUserID, + teamID: team, + now: now + ) + guard wrote, let account = stackUserID, !account.isEmpty else { return wrote } + lastSignedInAccount = account + await uploadCurrentRecord( + macDeviceID: macDeviceID, + instanceTag: instanceTag, + account: account, + teamID: team, + includesCustomizations: false, + instanceAuthority: .compareAndSet + ) + return true + } + @discardableResult public func upsertRoutesIfAuthorized( macDeviceID: String, diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/DemoContentPairedMacStore.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/DemoContentPairedMacStore.swift index fab4b7435f56..07ec3ab2daa3 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/DemoContentPairedMacStore.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/DemoContentPairedMacStore.swift @@ -166,6 +166,26 @@ public struct DemoContentPairedMacStore: MobilePairedMacStoring { ) } + @discardableResult + public func removeRouteIfAuthorized( + macDeviceID: String, + route: CmxAttachRoute, + condition: MobilePairedMacRouteWriteCondition, + stackUserID: String?, + teamID: String?, + now: Date + ) async throws -> Bool { + guard !isDemoDeviceID(macDeviceID) else { return false } + return try await inner.removeRouteIfAuthorized( + macDeviceID: macDeviceID, + route: route, + condition: condition, + stackUserID: stackUserID, + teamID: teamID, + now: now + ) + } + public func setActive(macDeviceID: String, stackUserID: String?, teamID: String?) async throws { guard !isDemoDeviceID(macDeviceID) else { return } try await inner.setActive(macDeviceID: macDeviceID, stackUserID: stackUserID, teamID: teamID) diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/IOSBuildScopedPairedMacStore.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/IOSBuildScopedPairedMacStore.swift index 6dc7d647973c..fd1c4d47345a 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/IOSBuildScopedPairedMacStore.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/IOSBuildScopedPairedMacStore.swift @@ -214,6 +214,38 @@ public struct IOSBuildScopedPairedMacStore: MobilePairedMacStoring { } } + @discardableResult + public func removeRouteIfAuthorized( + macDeviceID: String, + route: CmxAttachRoute, + condition: MobilePairedMacRouteWriteCondition, + stackUserID: String?, + teamID: String?, + now: Date + ) async throws -> Bool { + try await mutationGate.withLock { + let selectedTeam = normalizedTeamID(teamID) + let instanceTag = condition.instanceTag + let selected = try await scopedRows(stackUserID: stackUserID, teamID: teamID) + .first { matches($0, macDeviceID: macDeviceID, instanceTag: instanceTag) } + let fallback = selectedTeam == nil + ? nil + : try await scopedRows(stackUserID: stackUserID, teamID: nil) + .first { matches($0, macDeviceID: macDeviceID, instanceTag: instanceTag) } + let targetsFallback = fallback.map { + selected == nil || (selected?.lastSeenAt ?? .distantPast) < $0.lastSeenAt + } ?? false + return try await inner.removeRouteIfAuthorized( + macDeviceID: macDeviceID, + route: route, + condition: condition, + stackUserID: stackUserID, + teamID: scopedTeamID(targetsFallback ? nil : teamID), + now: now + ) + } + } + public func loadAll(stackUserID: String?, teamID: String?) async throws -> [MobilePairedMac] { var byID: [String: MobilePairedMac] = [:] for mac in try await scopedRows(stackUserID: stackUserID, teamID: teamID) { diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileMacCompatiblePairedMacStore.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileMacCompatiblePairedMacStore.swift index d6808abd55f5..7e1b7e2b7567 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileMacCompatiblePairedMacStore.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileMacCompatiblePairedMacStore.swift @@ -99,6 +99,31 @@ struct MobileMacCompatiblePairedMacStore: MobilePairedMacStoring { ) } + @discardableResult + func removeRouteIfAuthorized( + macDeviceID: String, + route: CmxAttachRoute, + condition: MobilePairedMacRouteWriteCondition, + stackUserID: String?, + teamID: String?, + now: Date + ) async throws -> Bool { + let instanceTag: String? + switch condition { + case .matchingInstanceTag(let tag): instanceTag = tag + case .unclaimed: instanceTag = nil + } + guard isCompatible(instanceTag: instanceTag) else { return false } + return try await inner.removeRouteIfAuthorized( + macDeviceID: macDeviceID, + route: route, + condition: condition, + stackUserID: stackUserID, + teamID: teamID, + now: now + ) + } + func loadAll( stackUserID: String?, teamID: String? diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+RouteRemoval.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+RouteRemoval.swift index 5b883c8fd2dc..5a40d9862b1e 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+RouteRemoval.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+RouteRemoval.swift @@ -32,12 +32,10 @@ extension MobileShellComposite { teamID: mac.teamID ) } else { - let wrote = try await pairedMacStore.upsertRoutesIfAuthorized( + let wrote = try await pairedMacStore.removeRouteIfAuthorized( macDeviceID: mac.macDeviceID, - displayName: mac.displayName, - routes: routes, + route: route, condition: .matchingInstanceTag(mac.instanceTag), - markActive: nil, stackUserID: mac.stackUserID ?? scope.userID, teamID: mac.teamID, now: Date() diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/TeamScopedPairedMacStore.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/TeamScopedPairedMacStore.swift index 6f40d3f6588e..11dcf1d9f8b6 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/TeamScopedPairedMacStore.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/TeamScopedPairedMacStore.swift @@ -103,6 +103,37 @@ public struct TeamScopedPairedMacStore: MobilePairedMacStoring { ) } + @discardableResult + public func removeRouteIfAuthorized( + macDeviceID: String, + route: CmxAttachRoute, + condition: MobilePairedMacRouteWriteCondition, + stackUserID: String?, + teamID: String?, + now: Date + ) async throws -> Bool { + let team = await resolvedTeam(teamID) + let instanceTag: String? + switch condition { + case .matchingInstanceTag(let tag): instanceTag = tag + case .unclaimed: instanceTag = nil + } + let scope = try await visibleScope( + macDeviceID: macDeviceID, + instanceTag: instanceTag, + stackUserID: stackUserID, + teamID: team + ) + return try await inner.removeRouteIfAuthorized( + macDeviceID: macDeviceID, + route: route, + condition: condition, + stackUserID: scope.stackUserID, + teamID: scope.teamID, + now: now + ) + } + /// Load paired Macs scoped to the explicit team when present or the /// currently-selected team otherwise. public func loadAll(stackUserID: String?, teamID: String?) async throws -> [MobilePairedMac] { diff --git a/Sources/TerminalController+WorkspaceGroupAction.swift b/Sources/TerminalController+WorkspaceGroupAction.swift index 1c6ab9fe5639..bcde1a4bc712 100644 --- a/Sources/TerminalController+WorkspaceGroupAction.swift +++ b/Sources/TerminalController+WorkspaceGroupAction.swift @@ -17,9 +17,9 @@ extension TerminalController { v2MainSync { guard tabManager.createWorkspaceGroup( name: name, - externalID: identity.value, selectAnchor: false, - collapseSidebarSelection: false + collapseSidebarSelection: false, + externalID: identity.value ) != nil else { mutationError = .err(code: "not_created", message: "Group was not created", data: nil) return @@ -220,22 +220,27 @@ extension TerminalController { ) return (resolution.value, nil) } catch let error as WorkspaceGroupIdentityResolution.ValidationError { - let messageKey: String - let defaultValue: String + let message: String switch error { case .nonString: - messageKey = "workspaceGroup.error.idempotencyKeyMustBeString" - defaultValue = "external_id and idempotency_key must be strings" + message = String( + localized: "workspaceGroup.error.idempotencyKeyMustBeString", + defaultValue: "external_id and idempotency_key must be strings" + ) case .empty: - messageKey = "workspaceGroup.error.idempotencyKeyMustNotBeEmpty" - defaultValue = "The group identity must not be empty" + message = String( + localized: "workspaceGroup.error.idempotencyKeyMustNotBeEmpty", + defaultValue: "The group identity must not be empty" + ) case .mismatchedAliases: - messageKey = "workspaceGroup.error.idempotencyKeysMustMatch" - defaultValue = "external_id and idempotency_key must match" + message = String( + localized: "workspaceGroup.error.idempotencyKeysMustMatch", + defaultValue: "external_id and idempotency_key must match" + ) } return (nil, .err( code: "invalid_params", - message: String(localized: messageKey, defaultValue: defaultValue), + message: message, data: nil )) } catch { From de96fb69568d9ccc0dd20b0b73d041e25b0fe01d Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Thu, 3 Sep 2026 17:01:06 -0700 Subject: [PATCH 03/33] fix: align workspace group snapshot arguments --- Sources/TerminalController+ControlWorkspaceGroupContext.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Sources/TerminalController+ControlWorkspaceGroupContext.swift b/Sources/TerminalController+ControlWorkspaceGroupContext.swift index ba68f89d7a7e..714d9e341c12 100644 --- a/Sources/TerminalController+ControlWorkspaceGroupContext.swift +++ b/Sources/TerminalController+ControlWorkspaceGroupContext.swift @@ -81,9 +81,9 @@ extension TerminalController: ControlWorkspaceGroupContext { anchorWorkspaceID: group.liveAnchorWorkspaceId, customColor: group.customColor, iconSymbol: group.iconSymbol, + memberWorkspaceIDs: memberIds, externalID: group.externalID, - anchorWorkspaceProvenance: group.anchorWorkspaceProvenance.rawValue, - memberWorkspaceIDs: memberIds + anchorWorkspaceProvenance: group.anchorWorkspaceProvenance.rawValue ) } From 66b690c9a71e4d83cd470d93fdced7f88a8f2dd4 Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Thu, 3 Sep 2026 17:29:28 -0700 Subject: [PATCH 04/33] fix: carry route tombstones across scope claims --- .../MobilePairedMacStore+Records.swift | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore+Records.swift b/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore+Records.swift index 28929251257a..e793a8f4ad45 100644 --- a/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore+Records.swift +++ b/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore+Records.swift @@ -180,6 +180,15 @@ extension MobilePairedMacStore { .text(macDeviceID), .text(fromOwnerKey), ]) + try exec(""" + UPDATE mac_route_removals + SET owner_key = ? + WHERE mac_device_id = ? AND owner_key = ?; + """, binding: [ + .text(toOwnerKey), + .text(macDeviceID), + .text(fromOwnerKey), + ]) try exec(""" DELETE FROM paired_macs WHERE mac_device_id = ? AND owner_key = ?; From ec16a921b2402a1075268937351dfd24a694fd67 Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Thu, 3 Sep 2026 18:07:27 -0700 Subject: [PATCH 05/33] fix: fail closed on route tombstone read errors --- .../MobilePairedMacStore+Records.swift | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore+Records.swift b/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore+Records.swift index e793a8f4ad45..0ca4b7d70d1b 100644 --- a/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore+Records.swift +++ b/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore+Records.swift @@ -347,7 +347,14 @@ extension MobilePairedMacStore { parameters: [.text(macDeviceID), .text(ownerKey)] ) var removedKeys: Set = [] - while sqlite3_step(removedStatement) == SQLITE_ROW { + while true { + let step = sqlite3_step(removedStatement) + if step == SQLITE_DONE { + break + } + guard step == SQLITE_ROW else { + throw MobilePairedMacStoreError.stepFailed(step, lastErrorMessage()) + } guard let kind = Self.readNullableText(removedStatement, column: 0), let endpoint = Self.readNullableText(removedStatement, column: 1) else { continue From 2134b076528676583d07cf097b3cb5982f1ebf98 Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Thu, 3 Sep 2026 19:23:41 -0700 Subject: [PATCH 06/33] test: cover active route teardown on deletion --- ...obileShellCompositeRouteRemovalTests.swift | 112 ++++++++++++++++++ 1 file changed, 112 insertions(+) create mode 100644 Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellCompositeRouteRemovalTests.swift diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellCompositeRouteRemovalTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellCompositeRouteRemovalTests.swift new file mode 100644 index 000000000000..4dfcf55d2667 --- /dev/null +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellCompositeRouteRemovalTests.swift @@ -0,0 +1,112 @@ +import CMUXMobileCore +import CmuxMobilePairedMac +import CmuxMobileRPC +import Foundation +import Testing +@testable import CmuxMobileShell + +@MainActor +@Suite struct MobileShellCompositeRouteRemovalTests { + @Test func deletingActiveTailscaleRouteDisconnectsForegroundSession() async throws { + let directory = FileManager.default.temporaryDirectory + .appendingPathComponent(UUID().uuidString, isDirectory: true) + try FileManager.default.createDirectory( + at: directory, + withIntermediateDirectories: true + ) + defer { try? FileManager.default.removeItem(at: directory) } + + let pairedStore = try MobilePairedMacStore( + databaseURL: directory.appendingPathComponent("paired.sqlite3") + ) + let activeRoute = try CmxAttachRoute( + id: "tailscale-active", + kind: .tailscale, + endpoint: .hostPort(host: "100.64.0.17", port: 56_584) + ) + let fallbackRoute = try CmxAttachRoute( + id: "tailscale-fallback", + kind: .tailscale, + endpoint: .hostPort(host: "100.64.0.18", port: 56_584) + ) + let now = Date() + try await pairedStore.upsert( + macDeviceID: "mac-route-removal", + displayName: "Route Removal Mac", + routes: [activeRoute, fallbackRoute], + markActive: true, + stackUserID: "user-1", + teamID: nil, + now: now + ) + + let router = LivenessHostRouter() + let closeGate = LivenessTransportCloseGate() + let transportBox = TransportBox() + let runtime = LivenessTestRuntime( + transportFactory: LivenessTransportFactory( + router: router, + box: transportBox, + closeGate: closeGate + ), + now: { now } + ) + let shell = MobileShellComposite( + runtime: runtime, + isSignedIn: true, + connectionState: .connected, + pairedMacStore: pairedStore, + identityProvider: StaticIdentityProvider(userID: "user-1") + ) + await shell.loadPairedMacs() + + let ticket = try CmxAttachTicket( + workspaceID: "workspace-a", + terminalID: "terminal-a", + macDeviceID: "mac-route-removal", + macDisplayName: "Route Removal Mac", + routes: [activeRoute], + expiresAt: now.addingTimeInterval(3_600) + ) + let client = MobileCoreRPCClient( + runtime: runtime, + route: activeRoute, + ticket: ticket + ) + _ = try await client.sendRequest( + MobileCoreRPCClient.requestData( + method: "mobile.host.status", + params: [:] + ) + ) + + shell.remoteClient = client + shell.activeTicket = ticket + shell.activeRoute = activeRoute + shell.foregroundMacDeviceID = "mac-route-removal" + shell.connections[MacPairingKey(macDeviceID: "mac-route-removal", instanceTag: nil)] = MacConnection( + macDeviceID: "mac-route-removal", + ticket: ticket, + route: activeRoute, + client: client, + generation: shell.connectionGeneration, + displayName: "Route Removal Mac", + instanceTag: nil, + supportedHostCapabilities: [], + actionCapabilities: .none + ) + + #expect(await shell.removeRoute( + activeRoute, + macDeviceID: "mac-route-removal", + instanceTag: nil + )) + #expect(shell.remoteClient == nil) + #expect(shell.activeRoute == nil) + #expect(shell.connectionState == .disconnected) + #expect(shell.connections[MacPairingKey(macDeviceID: "mac-route-removal", instanceTag: nil)] == nil) + #expect(await closeGate.waitUntilCloseStarted()) + + await closeGate.release() + } +} From 58eeb9c4e7f5a58445d1818ab2cedbb82c51cc62 Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Thu, 3 Sep 2026 19:23:44 -0700 Subject: [PATCH 07/33] fix: close live session when route is deleted --- .../MobileShellComposite+RouteRemoval.swift | 65 +++++++++++++++++++ 1 file changed, 65 insertions(+) diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+RouteRemoval.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+RouteRemoval.swift index 5a40d9862b1e..fe1f3fc2bf4b 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+RouteRemoval.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+RouteRemoval.swift @@ -4,6 +4,64 @@ import Foundation @MainActor extension MobileShellComposite { + /// Route identity for teardown must follow the same id-or-endpoint rules + /// used when a refreshed route replaces an older route record. The kind is + /// part of the identity so a Tailscale route cannot retire a different + /// transport that happens to use the same host and port. + private func routeMatchesForRemoval( + _ removed: CmxAttachRoute, + _ live: CmxAttachRoute + ) -> Bool { + removed.kind == live.kind + && (removed.id == live.id || removed.endpoint == live.endpoint) + } + + /// Retire any live session that is using the route after the persistent + /// removal succeeds. The pairing key is exact, so deleting one tagged + /// build cannot disconnect its Stable/Nightly sibling on the same Mac. + private func disconnectLiveRouteIfNeeded( + _ removedRoute: CmxAttachRoute, + ownerKey: MacPairingKey + ) { + let focused = connections[ownerKey.pairingID] + let isForegroundRoute = connectionState == .connected + && foregroundMacKey == ownerKey + && (activeRoute.map { + routeMatchesForRemoval(removedRoute, $0) + } == true || focused.map { + routeMatchesForRemoval(removedRoute, $0.route) + } == true) + + if isForegroundRoute { + // `clearRemoteConnectionContext` historically looked up the + // foreground registry entry by bare device id. Remove the exact + // tagged entry first so the live registry cannot retain a client + // after this route is deleted. + if let focused { + removeControlCapability(ifMatching: focused) + removeFocusedConnection(ifMatching: focused) + } + disconnectLiveConnection(preservingOtherMacWorkspaceState: true) + return + } + + if let focused, + routeMatchesForRemoval(removedRoute, focused.route) { + removeFocusedConnection(ifMatching: focused) + focused.client.retire() + Task { await focused.client.disconnect() } + markSecondaryMacUnavailable(ownerKey) + } + + if let subscription = secondaryMacSubscriptions[ownerKey], + routeMatchesForRemoval(removedRoute, subscription.route) { + cancelSecondaryControlReassertion(ifOwnedBy: subscription) + subscription.cancel() + secondaryMacSubscriptions[ownerKey] = nil + markSecondaryMacUnavailableIfUnowned(ownerKey) + } + } + /// Removes one user-controlled route from one exact Mac/build pairing. /// Iroh is the permanent identity route and cannot be removed. @discardableResult @@ -43,6 +101,13 @@ extension MobileShellComposite { guard wrote else { return false } } guard await isScopeCurrent(scope) else { return false } + disconnectLiveRouteIfNeeded( + route, + ownerKey: MacPairingKey( + macDeviceID: mac.macDeviceID, + instanceTag: mac.instanceTag + ) + ) await loadPairedMacs() await loadRegistryDevices() return true From ee7f9094ea27a71d0e080eba15789bea97892c15 Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Thu, 3 Sep 2026 20:21:02 -0700 Subject: [PATCH 08/33] test: cover route reauthorization after deletion --- .../MobilePairedMacRouteAuthorityTests.swift | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/Packages/iOS/CmuxMobilePairedMac/Tests/CmuxMobilePairedMacTests/MobilePairedMacRouteAuthorityTests.swift b/Packages/iOS/CmuxMobilePairedMac/Tests/CmuxMobilePairedMacTests/MobilePairedMacRouteAuthorityTests.swift index 349d4bae4d17..46998d9e0b5f 100644 --- a/Packages/iOS/CmuxMobilePairedMac/Tests/CmuxMobilePairedMacTests/MobilePairedMacRouteAuthorityTests.swift +++ b/Packages/iOS/CmuxMobilePairedMac/Tests/CmuxMobilePairedMacTests/MobilePairedMacRouteAuthorityTests.swift @@ -133,6 +133,63 @@ import Testing #expect(rows.first?.instanceTag == "stable") } + @Test func explicitPairingAuthorizationReinstatesDeletedTailscaleRoute() async throws { + let (store, directory) = try makeStore() + defer { try? FileManager.default.removeItem(at: directory) } + let deletedRoute = try route(id: "deleted", port: 51_005) + let retainedRoute = try route(id: "retained", port: 51_006) + let scope = MobilePairedMacRouteWriteCondition.matchingInstanceTag("default") + try await store.upsert( + macDeviceID: "shared-mac", + displayName: "Desk Mac", + routes: [deletedRoute, retainedRoute], + instanceTag: "default", + markActive: true, + stackUserID: "user-1", + teamID: "team-a", + now: Date(timeIntervalSince1970: 10) + ) + #expect(try await store.removeRouteIfAuthorized( + macDeviceID: "shared-mac", + route: deletedRoute, + condition: scope, + stackUserID: "user-1", + teamID: "team-a", + now: Date(timeIntervalSince1970: 20) + )) + + // A successful scan first persists the newly advertised route, then + // records that the user explicitly authorized its exact destination. + // Passive advertisement alone must remain unable to undo a deletion. + #expect(try await store.upsertRoutesIfAuthorized( + macDeviceID: "shared-mac", + displayName: "Desk Mac", + routes: [deletedRoute, retainedRoute], + condition: scope, + markActive: true, + stackUserID: "user-1", + teamID: "team-a", + now: Date(timeIntervalSince1970: 30) + )) + #expect(try await store.activeMac( + stackUserID: "user-1", + teamID: "team-a" + )?.routes == [retainedRoute]) + + try await store.authorizeUserTailscaleRoutes( + macDeviceID: "shared-mac", + instanceTag: "default", + stackUserID: "user-1", + teamID: "team-a", + routes: [deletedRoute] + ) + + #expect(try await store.activeMac( + stackUserID: "user-1", + teamID: "team-a" + )?.routes.map(\.id).sorted() == ["deleted", "retained"]) + } + private func makeStore() throws -> (MobilePairedMacStore, URL) { let directory = FileManager.default.temporaryDirectory .appendingPathComponent(UUID().uuidString, isDirectory: true) From a4b274bca99b9dc1ad93fb2f5ad9ad1d17e79d63 Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Thu, 3 Sep 2026 20:21:51 -0700 Subject: [PATCH 09/33] fix: clear route tombstone when rescanned --- .../MobilePairedMacStore.swift | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore.swift b/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore.swift index 31d4a2295086..418ae5cc3c83 100644 --- a/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore.swift +++ b/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore.swift @@ -818,6 +818,7 @@ public actor MobilePairedMacStore: MobilePairedMacStoring { } for route in grantRoutes { let encoded = try Self.encodeRoute(route) + let encodedEndpoint = try Self.encodeRouteEndpoint(route) try exec(""" INSERT INTO legacy_tailscale_route_grants ( mac_device_id, owner_key, endpoint_json, origin @@ -830,6 +831,22 @@ public actor MobilePairedMacStore: MobilePairedMacStoring { .text(ownerKey), .text(encoded), ]) + // A pairing-code scan is a fresh, explicit authorization for + // this exact destination. Clear only its local deletion marker; + // passive route refreshes never reach this path and therefore + // cannot resurrect a route the user removed. + try exec(""" + DELETE FROM mac_route_removals + WHERE mac_device_id = ? + AND owner_key = ? + AND kind = ? + AND endpoint_json = ?; + """, binding: [ + .text(macDeviceID), + .text(ownerKey), + .text(route.kind.rawValue), + .text(encodedEndpoint), + ]) } } } From cb59c89b338ded49ccf0dd0cf4fab579deff737d Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Thu, 3 Sep 2026 20:58:53 -0700 Subject: [PATCH 10/33] test: model scanner route upsert --- .../MobilePairedMacRouteAuthorityTests.swift | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Packages/iOS/CmuxMobilePairedMac/Tests/CmuxMobilePairedMacTests/MobilePairedMacRouteAuthorityTests.swift b/Packages/iOS/CmuxMobilePairedMac/Tests/CmuxMobilePairedMacTests/MobilePairedMacRouteAuthorityTests.swift index 46998d9e0b5f..17de9d0430a5 100644 --- a/Packages/iOS/CmuxMobilePairedMac/Tests/CmuxMobilePairedMacTests/MobilePairedMacRouteAuthorityTests.swift +++ b/Packages/iOS/CmuxMobilePairedMac/Tests/CmuxMobilePairedMacTests/MobilePairedMacRouteAuthorityTests.swift @@ -161,16 +161,16 @@ import Testing // A successful scan first persists the newly advertised route, then // records that the user explicitly authorized its exact destination. // Passive advertisement alone must remain unable to undo a deletion. - #expect(try await store.upsertRoutesIfAuthorized( + try await store.upsert( macDeviceID: "shared-mac", displayName: "Desk Mac", routes: [deletedRoute, retainedRoute], - condition: scope, + instanceTag: "default", markActive: true, stackUserID: "user-1", teamID: "team-a", now: Date(timeIntervalSince1970: 30) - )) + ) #expect(try await store.activeMac( stackUserID: "user-1", teamID: "team-a" From ff5ab9357e35ee73df33372fb85250ff7814cf9a Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Fri, 4 Sep 2026 09:51:43 -0700 Subject: [PATCH 11/33] test: require strict tailscale-only reconnect --- .../ReconnectRouteSelectionTests.swift | 23 +++--- .../TailscalePairingRegressionTests.swift | 75 +++++++++++++++++++ 2 files changed, 84 insertions(+), 14 deletions(-) diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectRouteSelectionTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectRouteSelectionTests.swift index d767bd82edce..2694b820d793 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectRouteSelectionTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/ReconnectRouteSelectionTests.swift @@ -723,13 +723,11 @@ import Testing ) } - /// Switching an Iroh-identified pairing to Tailscale Only still replaces - /// the live session (its route decisions were made under the old method), - /// but the replacement dial rides the Iroh lane pinned to the pairing's - /// numeric Tailscale addresses: transport admission stays the single auth - /// authority for every session purpose, and the raw TCP lane is reserved - /// for legacy pairings without an Iroh identity. - @Test func changingToTailscaleReplacesLiveIrohWithPinnedIrohDial() async throws { + /// Switching an Iroh-identified pairing to Tailscale Only replaces the + /// live session and dials the authorized raw Tailscale route. The Iroh + /// session must not survive as an implicit fallback when the phone's + /// Tailscale tunnel is the selected transport. + @Test func changingToTailscaleReplacesLiveIrohWithAuthorizedTailscaleDial() async throws { let clock = TestClock() let router = LivenessHostRouter() // The factory boxes the live Iroh transport it hands out, so the test @@ -737,8 +735,7 @@ import Testing let liveTransportBox = TransportBox() let factory = KindRecordingTransportFactory( router: router, - box: liveTransportBox, - failingKinds: [.tailscale] + box: liveTransportBox ) let tailscale = try tailscale() let iroh = try iroh() @@ -799,14 +796,12 @@ import Testing let applied = try await pollUntil { let originalTransportClosed = await originalTransport?.isClosedForTesting() == true - return factory.attemptedKinds().filter { $0 == .iroh }.count == 2 + return factory.attemptedKinds() == [.iroh, .tailscale] && store.connectionState == .connected && originalTransportClosed } #expect(applied) - #expect(store.activeRoute?.kind == .iroh) - // Tailscale Only never dials the raw TCP lane for a pairing with an - // Iroh identity, even when that dial would be authorized. - #expect(!factory.attemptedKinds().contains(.tailscale)) + #expect(store.activeRoute?.kind == .tailscale) + #expect(factory.attemptedKinds() == [.iroh, .tailscale]) } } diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/TailscalePairingRegressionTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/TailscalePairingRegressionTests.swift index 0b26e5559045..73fa47e4135d 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/TailscalePairingRegressionTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/TailscalePairingRegressionTests.swift @@ -120,6 +120,81 @@ import Testing #expect(saved?.legacyTailscaleRoutes?.first?.endpoint == .hostPort(host: host, port: port)) } + @Test func rescanningQRCodeRestoresDeletedRouteInTheComputerList() async throws { + let router = LivenessHostRouter() + let box = TransportBox() + let factory = KindRecordingTransportFactory(router: router, box: box) + let directory = FileManager.default.temporaryDirectory + .appendingPathComponent(UUID().uuidString, isDirectory: true) + try FileManager.default.createDirectory( + at: directory, + withIntermediateDirectories: true + ) + defer { try? FileManager.default.removeItem(at: directory) } + let pairedMacStore = try MobilePairedMacStore( + databaseURL: directory.appendingPathComponent("paired-macs.sqlite3") + ) + let originalRoute = try CmxAttachRoute( + id: "tailscale", + kind: .tailscale, + endpoint: .hostPort(host: host, port: port), + priority: 10 + ) + let irohRoute = try CmxAttachRoute( + id: "iroh", + kind: .iroh, + endpoint: .peer( + identity: CmxIrohPeerIdentity(endpointID: String(repeating: "a", count: 64)), + pathHints: [] + ), + priority: 0 + ) + let debugRoute = try CmxAttachRoute( + id: "debug_loopback", + kind: .debugLoopback, + endpoint: .hostPort(host: "127.0.0.1", port: port), + priority: 20 + ) + try await pairedMacStore.upsert( + macDeviceID: "test-mac", + displayName: "Test Mac", + routes: [irohRoute, originalRoute, debugRoute], + instanceTag: "default", + markActive: true, + stackUserID: "phone-user", + now: Self.fixedNow + ) + #expect(try await pairedMacStore.removeRouteIfAuthorized( + macDeviceID: "test-mac", + route: originalRoute, + condition: .matchingInstanceTag("default"), + stackUserID: "phone-user", + teamID: nil, + now: Self.fixedNow.addingTimeInterval(1) + )) + + let runtime = LivenessTestRuntime( + transportFactory: factory, + now: { Self.fixedNow }, + supportedRouteKinds: [.iroh, .tailscale, .debugLoopback] + ) + let store = makeStore( + runtime: runtime, + pairedMacStore: pairedMacStore, + connectionMethod: .tailscale + ) + store.pairingCode = currentQRCode() + + await store.connectPairingInput() + + let saved = try #require(await pairedMacStore.activeMac(stackUserID: "phone-user")) + #expect(saved.routes.contains(originalRoute)) + #expect(saved.routes.contains(irohRoute)) + #expect(saved.routes.contains(debugRoute)) + let displayed = try #require(store.displayPairedMacs.first { $0.macDeviceID == "test-mac" }) + #expect(displayed.routes.contains(originalRoute)) + } + @Test func manualMagicDNSHasDeterministicSafeFallbackWithoutDialing() async throws { let router = LivenessHostRouter() let box = TransportBox() From 756d7419ceb61d622a3b1b3f334466967ea3c36d Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Fri, 4 Sep 2026 10:49:00 -0700 Subject: [PATCH 12/33] test: retain user tailscale route across presence refresh --- .../MobilePairedMacStoreTests.swift | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) diff --git a/Packages/iOS/CmuxMobilePairedMac/Tests/CmuxMobilePairedMacTests/MobilePairedMacStoreTests.swift b/Packages/iOS/CmuxMobilePairedMac/Tests/CmuxMobilePairedMacTests/MobilePairedMacStoreTests.swift index 4eeea1c6bbf3..3ff221ef2cd5 100644 --- a/Packages/iOS/CmuxMobilePairedMac/Tests/CmuxMobilePairedMacTests/MobilePairedMacStoreTests.swift +++ b/Packages/iOS/CmuxMobilePairedMac/Tests/CmuxMobilePairedMacTests/MobilePairedMacStoreTests.swift @@ -379,6 +379,64 @@ import Testing ) } + @Test func userAuthorizedRouteStaysVisibleWhenPresenceOmitsIt() async throws { + let (store, directory) = try makeStore() + defer { try? FileManager.default.removeItem(at: directory) } + let tailscale = try tailscaleRoute(host: "100.64.0.34") + let iroh = try irohRoute() + + try await store.upsert( + macDeviceID: "scanned-mac", + displayName: "Scanned Mac", + routes: [tailscale, iroh], + markActive: true, + stackUserID: "user-1", + now: Date() + ) + try await store.authorizeUserTailscaleRoutes( + macDeviceID: "scanned-mac", + instanceTag: nil, + stackUserID: "user-1", + teamID: nil, + routes: [tailscale] + ) + + // Presence commonly publishes only the authenticated Iroh route. The + // user-authorized Tailscale endpoint remains a visible dial option. + try await store.upsert( + macDeviceID: "scanned-mac", + displayName: "Scanned Mac", + routes: [iroh], + markActive: true, + stackUserID: "user-1", + now: Date().addingTimeInterval(1) + ) + let retained = try #require(await store.activeMac(stackUserID: "user-1")) + #expect(retained.routes.contains(tailscale)) + #expect(retained.routes.contains(iroh)) + + // A prior explicit removal still wins over the grant during later + // refreshes, so preserving user grants cannot resurrect a tombstoned + // endpoint. + #expect(try await store.removeRouteIfAuthorized( + macDeviceID: "scanned-mac", + route: tailscale, + condition: .unclaimed, + stackUserID: "user-1", + teamID: nil, + now: Date().addingTimeInterval(2) + )) + try await store.upsert( + macDeviceID: "scanned-mac", + displayName: "Scanned Mac", + routes: [iroh], + markActive: true, + stackUserID: "user-1", + now: Date().addingTimeInterval(3) + ) + #expect(!(try await store.activeMac(stackUserID: "user-1")?.routes.contains(tailscale) ?? false)) + } + @Test func userGrantRequiresExistingScopedRow() async throws { let (store, directory) = try makeStore() defer { try? FileManager.default.removeItem(at: directory) } From c12e12197b7f74aa626641064777d16dfd21065f Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Fri, 4 Sep 2026 10:49:37 -0700 Subject: [PATCH 13/33] fix: preserve authorized tailscale routes and fail closed --- .../MobilePairedMacStore+Records.swift | 12 +++- .../MobilePairedMacStore.swift | 31 +++++++++- ...obileShellComposite+ConnectionMethod.swift | 38 ++---------- ...ileShellComposite+ConnectionRecovery.swift | 24 ++++---- ...MobileShellComposite+ReconnectRoutes.swift | 61 +++++++++---------- .../MobileShellComposite.swift | 28 +++++++-- 6 files changed, 107 insertions(+), 87 deletions(-) diff --git a/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore+Records.swift b/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore+Records.swift index 0ca4b7d70d1b..e9fc3fb89fd2 100644 --- a/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore+Records.swift +++ b/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore+Records.swift @@ -291,16 +291,18 @@ extension MobilePairedMacStore { func fetchLegacyTailscaleRoutes( macDeviceID: String, - ownerKey: String + ownerKey: String, + origin: String? = nil ) throws -> [CmxAttachRoute] { var statement: OpaquePointer? defer { sqlite3_finalize(statement) } + let originClause = origin == nil ? "" : " AND origin = ?" let result = sqlite3_prepare_v2( db, """ SELECT endpoint_json FROM legacy_tailscale_route_grants - WHERE mac_device_id = ? AND owner_key = ? + WHERE mac_device_id = ? AND owner_key = ?\(originClause) ORDER BY id ASC; """, -1, @@ -310,7 +312,11 @@ extension MobilePairedMacStore { guard result == SQLITE_OK else { throw MobilePairedMacStoreError.prepareFailed(result, lastErrorMessage()) } - try bind(statement: statement, parameters: [.text(macDeviceID), .text(ownerKey)]) + var bindings: [BindValue] = [.text(macDeviceID), .text(ownerKey)] + if let origin { + bindings.append(.text(origin)) + } + try bind(statement: statement, parameters: bindings) let decoder = JSONDecoder() var routes: [CmxAttachRoute] = [] while sqlite3_step(statement) == SQLITE_ROW { diff --git a/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore.swift b/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore.swift index 418ae5cc3c83..ae08b4f9cc09 100644 --- a/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore.swift +++ b/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore.swift @@ -1000,14 +1000,39 @@ public actor MobilePairedMacStore: MobilePairedMacStoring { } let incomingHasIroh = routes.contains { $0.kind == .iroh } let pinnedIrohRoutes = existingRoutes.filter { $0.kind == .iroh } + let userAuthorizedTailscaleRoutes = try fetchLegacyTailscaleRoutes( + macDeviceID: macDeviceID, + ownerKey: ownerKey, + origin: "user" + ) + // A presence or backup refresh can publish only Iroh and Debug + // routes after the user explicitly paired over Tailscale. Keep the + // exact user-authorized endpoint in the visible route set while it + // is still present in the prior route snapshot. This does not + // resurrect a route the user removed: removeRoute writes a tombstone + // and therefore removes it from existingRoutes before this merge. + let retainedUserAuthorizedTailscaleRoutes = existingRoutes.filter { route in + route.kind == .tailscale + && userAuthorizedTailscaleRoutes.contains { + $0.endpoint == route.endpoint + } + } // Iroh capability is sticky for one paired Mac. Presence, backup, or // an older host build may temporarily publish only raw private-network // routes; replacing the stored Iroh identity in that case would allow // a later admission failure to downgrade into Stack-bearer RPC. A new // Iroh route replaces the old identity normally. - let routesToPersist = incomingHasIroh || pinnedIrohRoutes.isEmpty - ? routes - : routes + pinnedIrohRoutes + var routesToPersist = routes + if !pinnedIrohRoutes.isEmpty, !incomingHasIroh { + routesToPersist.append(contentsOf: pinnedIrohRoutes) + } + for retainedRoute in retainedUserAuthorizedTailscaleRoutes + where !routesToPersist.contains(where: { + $0.kind == retainedRoute.kind + && $0.endpoint == retainedRoute.endpoint + }) { + routesToPersist.append(retainedRoute) + } let createdAt = existing?.createdAt ?? claimable?.createdAt ?? now let persistedInstanceTag = routeWriteCondition == nil ? instanceTag diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionMethod.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionMethod.swift index d0974aafeb29..451b382f28c4 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionMethod.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionMethod.swift @@ -94,12 +94,9 @@ extension MobileShellComposite { /// The method-pinned Iroh dial allowlist for one pairing, or `nil` when the /// pairing's effective method places no address pin on the Iroh dial. /// - /// Direct pins the dial to the user-enabled addresses. Tailscale Only on an - /// Iroh-identified pairing pins the dial to the pairing's numeric Tailscale - /// addresses: the method constrains PATHS while transport admission stays - /// the single auth authority, so control, background control, and terminal - /// lanes all live and die by the same dial policy. Legacy pairings without - /// an Iroh identity return `nil` and keep the grant-gated raw host lane. + /// Direct pins the dial to the user-enabled addresses. Tailscale Only uses + /// its exact authorized raw route through the normal route selector, so it + /// returns `nil` here and cannot be converted into an Iroh dial. /// /// An empty array means the method is pinned with nothing dialable: /// callers must fail closed and never substitute another path. Entries @@ -127,39 +124,12 @@ extension MobileShellComposite { ) } case .tailscale: - guard pairing.routes.contains(where: { $0.kind == .iroh }) else { - return nil - } - return Self.irohTailscaleDialCandidates(for: pairing) + return nil case .automatic: return nil } } - /// Numeric Tailscale addresses a Tailscale Only pairing may pin its Iroh - /// dial to, deduplicated across the stored reconnect routes and the - /// device-local legacy grant list. Ports are never copied: a stored - /// Tailscale port names the legacy TCP listener, while the pin joins the - /// broker-published Iroh UDP port at dial time. - nonisolated static func irohTailscaleDialCandidates( - for pairing: MobilePairedMac - ) -> [CmxIrohDirectDialCandidate] { - var seen: Set = [] - var candidates: [CmxIrohDirectDialCandidate] = [] - for route in pairing.routes + (pairing.legacyTailscaleRoutes ?? []) { - guard route.kind == .tailscale, - case let .hostPort(host, _) = route.endpoint, - let address = try? CmxIrohCustomPrivateAddress(host), - seen.insert(address.value).inserted else { - continue - } - candidates.append( - CmxIrohDirectDialCandidate(address: address.value, port: nil) - ) - } - return candidates - } - /// Zero-touch discovery yields Iroh candidates only. It is pointless only /// when the app default is Tailscale AND no stored pairing opted back into /// the automatic method — a per-Computer Iroh choice keeps discovery alive. diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift index 93754efc5078..30734997b55a 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift @@ -741,16 +741,11 @@ extension MobileShellComposite { forMacDeviceID: pairedMacDeviceID, instanceTag: instanceTagExpectation.expectedTag ) - // Direct and Tailscale Only ride the Iroh lane below: identity-checked - // and encrypted, with transport admission as the single auth - // authority. The method's addresses (user-enabled Direct entries, or - // the pairing's numeric Tailscale addresses) are the COMPLETE per-dial - // path allowlist (no relay, no advertised or discovered paths), so - // resolve them from the caller's fresh row first for the same - // startup-restore reason as the method above, and fail closed when - // nothing is dialable. Raw host/port dialing cannot carry the account - // credential (plaintext TCP), so it stays reserved for legacy - // pairings without an Iroh identity (nil candidates below). + // Direct pins the identity-checked Iroh dial to the user's enabled + // addresses. Tailscale Only stays on its exact authorized raw route + // set, so the fresh row is still the authority for that route and a + // missing grant fails closed. Raw host/port dialing is intentionally + // limited to the compatibility route carrying that user authorization. let methodPinnedCandidates = irohMethodPinnedDialCandidates( forMacDeviceID: pairedMacDeviceID, instanceTag: instanceTagExpectation.expectedTag, @@ -760,11 +755,18 @@ extension MobileShellComposite { return .failed(.unsupportedRoute) } let supportedKinds = runtime?.supportedRouteKinds ?? [] + let hasIrohRoute = routes.contains { $0.kind == .iroh } + let hasTailscaleRoute = routes.contains { $0.kind == .tailscale } + let shouldUseAuthorizedTailscaleRoute = resolvedMethod == .tailscale + || (resolvedMethod == .automatic + && !hasIrohRoute + && hasTailscaleRoute + && !legacyTailscaleRoutes.isEmpty) var pinnedRoutes = Self.storedReconnectRoutes( routes, supportedKinds: supportedKinds, preferNonLoopback: Self.prefersNonLoopbackRoutes, - tailscaleRequirement: resolvedMethod == .tailscale + tailscaleRequirement: shouldUseAuthorizedTailscaleRoute && methodPinnedCandidates == nil ? Self.TailscaleRouteRequirement( macDeviceID: pairedMacDeviceID, diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ReconnectRoutes.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ReconnectRoutes.swift index f784dca5a0a2..9584ef94df3a 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ReconnectRoutes.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ReconnectRoutes.swift @@ -151,14 +151,6 @@ extension MobileShellComposite { public nonisolated static func hasUsableTailscaleAuthorization( in macs: [MobilePairedMac] ) -> Bool { - // An Iroh-identified pairing with a numeric Tailscale address dials - // the Iroh lane pinned to that address: admission authenticates it, - // so no device-local legacy grant is required. - for mac in macs where mac.routes.contains(where: { $0.kind == .iroh }) { - if !irohTailscaleDialCandidates(for: mac).isEmpty { - return true - } - } var authorizedEndpoints: Set = [] for mac in macs { for route in mac.legacyTailscaleRoutes ?? [] { @@ -233,13 +225,9 @@ extension MobileShellComposite { /// Supported routes for reconnecting an already-paired Mac. /// - /// Unlike the legacy host/port helper, this preserves Iroh peer routes. Once - /// a supported Iroh route exists, it also pins the pairing to Iroh and drops - /// every raw host/port fallback. A numeric Tailscale route is first copied - /// into the pinned Iroh route as a private fallback address, so Tailscale can - /// still carry Iroh without receiving a Stack bearer. Otherwise an admission - /// or revocation failure could silently downgrade around the Iroh device - /// grant. Pairings without an authenticated Iroh identity remain fail-closed. + /// Unlike the legacy host/port helper, this preserves Iroh peer routes for + /// the default method. Explicit Tailscale authorization is handled by the + /// caller below and never gets converted into an Iroh fallback. /// /// `tailscaleRequirement` represents the user's explicit Tailscale-only /// connection method. Only stored Tailscale routes carrying a device-local @@ -283,33 +271,42 @@ extension MobileShellComposite { /// The dial order for one stored Mac, honoring the user's connection-method /// choice. With the default automatic method this is exactly /// ``storedReconnectRoutes(_:supportedKinds:preferNonLoopback:tailscaleRequirement:)`` - /// without a preference. + /// without a preference. A pre-Iroh automatic pairing may retain a + /// migration grant and no Iroh identity; that exact legacy route remains + /// available until the Mac publishes an Iroh route or the user selects a + /// different method. func orderedReconnectRoutes( for mac: MobilePairedMac, supportedKinds: [CmxAttachTransportKind] ) -> [CmxAttachRoute] { let method = connectionMethod(for: mac) - // Tailscale Only on an Iroh-identified pairing rides the Iroh lane - // pinned to the pairing's numeric Tailscale addresses; the raw - // grant-gated host lane remains only for legacy pairings without an - // Iroh identity, so admission stays the single auth authority. - let tailscaleRidesPinnedIroh = method == .tailscale - && mac.routes.contains { $0.kind == .iroh } + let hasIroh = mac.routes.contains { $0.kind == .iroh } + let tailscaleRequirement: TailscaleRouteRequirement? + let hasTailscaleRoute = mac.routes.contains { $0.kind == .tailscale } + let hasLegacyTailscaleGrant = !(mac.legacyTailscaleRoutes ?? []).isEmpty + if method == .tailscale + || (method == .automatic + && !hasIroh + && hasTailscaleRoute + && hasLegacyTailscaleGrant) { + tailscaleRequirement = TailscaleRouteRequirement( + macDeviceID: mac.macDeviceID, + grantRoutes: mac.legacyTailscaleRoutes ?? [] + ) + } else { + tailscaleRequirement = nil + } let routes = Self.storedReconnectRoutes( mac.routes, supportedKinds: supportedKinds, preferNonLoopback: Self.prefersNonLoopbackRoutes, - tailscaleRequirement: method == .tailscale && !tailscaleRidesPinnedIroh - ? TailscaleRouteRequirement( - macDeviceID: mac.macDeviceID, - grantRoutes: mac.legacyTailscaleRoutes ?? [] - ) - : nil + tailscaleRequirement: tailscaleRequirement ) - // A pinned method rides the Iroh lane EXCLUSIVELY: the transport - // dials only the method's allowlisted addresses, and no dev-loopback - // or host/port lane may substitute when they are unreachable. - return method == .direct || tailscaleRidesPinnedIroh + // Direct rides the Iroh lane exclusively. Tailscale Only remains the + // exact authorized raw route set returned above, with no Iroh, + // loopback, relay, or discovery fallback. Automatic uses the same + // narrow raw route only for the pre-Iroh migration case above. + return method == .direct ? routes.filter { $0.kind == .iroh } : routes } diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift index 8789ce4f81c1..d35d7de8ffa4 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift @@ -3176,10 +3176,10 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { instanceTag: mac.instanceTag, scope: scope ) else { break } - // Tailscale Only blocks the Iroh lane only for legacy pairings - // without an Iroh identity; an identified pairing rides Iroh - // pinned to its Tailscale addresses (same lane the terminal - // lanes ride, same admission authority). + // Tailscale Only never uses the Iroh lane. It can reconnect only + // through a route carrying this phone's exact user authorization; + // the route selector below rejects Iroh and ungranted Tailscale + // entries before a client is created. let irohReconnectIsBlocked = (connectionMethod(for: mac) == .tailscale && !mac.routes.contains { $0.kind == .iroh }) || automaticIrohReconnectIsBlocked(accountID: scope.userID) @@ -10455,6 +10455,26 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { } return authorizedTailscale } + // An Automatic pairing created before Iroh shipped may still carry the + // one device-local migration grant that makes its exact raw Tailscale + // endpoint usable. Preserve that compatibility route through this + // second policy gate, but only while the ticket has no Iroh identity; + // once Iroh is present Automatic must stay on the authenticated lane. + if ticketMethod == .automatic, + !supportedRoutes.contains(where: { $0.kind == .iroh }), + let pairedMacDeviceID, + !legacyTailscaleRoutes.isEmpty { + let authorizedLegacyTailscale = supportedRoutes.filter { route in + Self.legacyTailscaleAuthorizationEvidence( + for: route, + macDeviceID: pairedMacDeviceID, + persistedRoutes: legacyTailscaleRoutes + ) != nil + } + if !authorizedLegacyTailscale.isEmpty { + return authorizedLegacyTailscale + } + } // The Iroh method is just as strict as Tailscale Only: no raw // host/port fallback, ever. Debug loopback rides alongside Iroh as // the dev-build convenience (compiled out of production route sets): From d6ebf92b820341610ae2d13ed4fc456f19bdb7c9 Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Fri, 4 Sep 2026 14:23:10 -0700 Subject: [PATCH 14/33] test: cover tailscale replacement presentation --- .../MobileRootPresentationStateTests.swift | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/MobileRootPresentationStateTests.swift b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/MobileRootPresentationStateTests.swift index d98ec6114674..13e8fcd1410e 100644 --- a/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/MobileRootPresentationStateTests.swift +++ b/Packages/iOS/CmuxMobileShellUI/Tests/CmuxMobileShellUITests/MobileRootPresentationStateTests.swift @@ -13,6 +13,14 @@ struct MobileRootPresentationStateTests { #expect(approval.analyticsEntry == "version_approval") } + @Test func tailscaleReplacementStartsScannerWithReplacementAnalytics() { + let replacement = PairingPresentation.tailscaleReplacement + + #expect(replacement.showsScanner) + #expect(replacement.showsManualPairingControls) + #expect(replacement.analyticsEntry == "tailscale_replacement") + } + @Test func introductionStartsTailscaleScannerWithoutAUsableAuthorization() { var state = MobileRootPresentationState() From 00e1d8776c3db02dcc5455ca977fd89991bdcce9 Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Fri, 4 Sep 2026 14:23:17 -0700 Subject: [PATCH 15/33] feat: rescan tailscale pairing from computer detail --- .../MobileShellComposite.swift | 8 ++--- .../CMUXMobileRootView.swift | 1 + .../MacComputerDetailView.swift | 35 ++++++++++++++++--- .../PairingPresentation.swift | 15 ++++++-- .../CmuxMobileShellUI/PairingView.swift | 28 ++++++++++----- 5 files changed, 69 insertions(+), 18 deletions(-) diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift index d35d7de8ffa4..da96f7558a67 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift @@ -2610,18 +2610,18 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { } /// Connect using the current pairing input, accepting either a code or pairing URL. - public func connectPairingInput() async { + public func connectPairingInput() async -> MobilePairingURLConnectionResult { let trimmedCode = pairingCode.trimmingCharacters(in: .whitespacesAndNewlines) guard !trimmedCode.isEmpty else { - return + return .failed } if CmxPairingURLScheme(urlString: trimmedCode) != nil { // The pairing input field is an explicit in-app code entry (scan // or paste), the act that authorizes a compatibility Tailscale dial. - await connectPairingURLResult(trimmedCode, userEnteredPairingCode: true) - return + return await connectPairingURLResult(trimmedCode, userEnteredPairingCode: true) } connectPreviewHost() + return .connected } /// Connect to a manually-entered Mac host and optionally associate the diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView.swift index 6bc78463fbae..5d05ba7b4626 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView.swift @@ -603,6 +603,7 @@ struct CMUXMobileRootView: View { if result == .connected { dismissAddDeviceSheet() } + return result }, connectManualHost: { name, host, port in await store.connectManualHost(name: name, host: host, port: port) diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MacComputerDetailView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MacComputerDetailView.swift index 4e2fa681a97a..394eddd1d062 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MacComputerDetailView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MacComputerDetailView.swift @@ -28,6 +28,9 @@ struct MacComputerDetailView: View { /// Computer without a usable grant offers it under the picker, and /// dismissing it lands back here. The scanner is one tap away inside. @State private var showsAddTailscaleConnection = false + /// Whether the Tailscale pairing sheet adds the first route or replaces + /// the route already shown for this Computer. + @State private var tailscalePairingPresentation: PairingPresentation = .tailscaleSetup @Environment(\.dismiss) private var dismiss @State private var newDirectAddress = "" @State private var newDirectAddressLabel = "" @@ -283,17 +286,22 @@ struct MacComputerDetailView: View { .sheet(isPresented: $showsAddTailscaleConnection) { PairingView( pairingCode: $store.pairingCode, - initialPresentation: .tailscaleSetup, + initialPresentation: tailscalePairingPresentation, connectionError: store.connectionError, connectionErrorGuidance: store.connectionErrorGuidance, versionWarning: store.pairingVersionWarning, connectPairingCode: { await store.connectPairingInput() }, - acceptVersionWarning: { _ = await store.acceptPairingVersionWarning() }, + acceptVersionWarning: { await store.acceptPairingVersionWarning() }, connectManualHost: { name, host, port in await store.connectManualHost(name: name, host: host, port: port) }, cancelPairing: { store.cancelPairing() }, - cancel: { showsAddTailscaleConnection = false } + cancel: { showsAddTailscaleConnection = false }, + onPairingResult: { result in + if result == .connected { + showsAddTailscaleConnection = false + } + } ) } .onChange(of: computerHasUsableTailscaleAuthorization) { _, authorized in @@ -551,7 +559,7 @@ struct MacComputerDetailView: View { } .accessibilityIdentifier("MobileComputerTailscaleUnauthorizedWarning") Button { - showsAddTailscaleConnection = true + presentTailscalePairing(.tailscaleSetup) } label: { Label( L10n.string( @@ -1122,6 +1130,20 @@ struct MacComputerDetailView: View { ForEach(routes, id: \.id) { route in routeRow(route) } + if routes.contains(where: { $0.kind == .tailscale }) { + Button { + presentTailscalePairing(.tailscaleReplacement) + } label: { + Label( + L10n.string( + "mobile.connections.tailscale.replace", + defaultValue: "Replace Tailscale Connection" + ), + systemImage: "qrcode.viewfinder" + ) + } + .accessibilityIdentifier("MobileComputerReplaceTailscaleConnectionButton") + } Button { pingAllRoutes(routes) } label: { @@ -1196,6 +1218,11 @@ struct MacComputerDetailView: View { pendingLastRouteRemoval = route } + private func presentTailscalePairing(_ presentation: PairingPresentation) { + tailscalePairingPresentation = presentation + showsAddTailscaleConnection = true + } + /// The per-route ping status sub-line: nothing before the first ping, a /// spinner while in flight, then the classified result with a tinted icon. /// A stable per-endpoint key: route kind + the host/port it dials. Used to diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PairingPresentation.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PairingPresentation.swift index 84f18826e5c4..0dfdd973357e 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PairingPresentation.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PairingPresentation.swift @@ -12,13 +12,22 @@ enum PairingPresentation: Equatable { /// directly. case tailscaleSetup + /// Replaces the selected Computer's existing Tailscale route. The QR + /// scanner opens immediately, while the manual form remains available if + /// the user needs it. + case tailscaleReplacement + /// Approval for an externally supplied attach ticket whose compatibility /// level differs from this iPhone. This is not a manual-pairing entrypoint. case versionApproval var showsScanner: Bool { - if case .scanner = self { return true } - return false + switch self { + case .scanner, .tailscaleReplacement: + return true + default: + return false + } } var showsManualPairingControls: Bool { @@ -33,6 +42,8 @@ enum PairingPresentation: Equatable { entry.rawValue case .tailscaleSetup: "tailscale_setup" + case .tailscaleReplacement: + "tailscale_replacement" case .versionApproval: "version_approval" } diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PairingView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PairingView.swift index 8bac0eb24da8..1e61bbca4c39 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PairingView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PairingView.swift @@ -20,11 +20,12 @@ struct PairingView: View { /// when the headline is already the full instruction. let connectionErrorGuidance: String? let versionWarning: String? - let connectPairingCode: () async -> Void - let acceptVersionWarning: () async -> Void + let connectPairingCode: () async -> MobilePairingURLConnectionResult + let acceptVersionWarning: () async -> MobilePairingURLConnectionResult let connectManualHost: (String, String, Int) async -> Void let cancelPairing: () -> Void let cancel: () -> Void + let onPairingResult: ((MobilePairingURLConnectionResult) -> Void)? @State private var isShowingScanner: Bool @State private var deviceName = UITestConfig.addDeviceName @@ -45,11 +46,12 @@ struct PairingView: View { connectionError: String?, connectionErrorGuidance: String?, versionWarning: String?, - connectPairingCode: @escaping () async -> Void, - acceptVersionWarning: @escaping () async -> Void, + connectPairingCode: @escaping () async -> MobilePairingURLConnectionResult, + acceptVersionWarning: @escaping () async -> MobilePairingURLConnectionResult, connectManualHost: @escaping (String, String, Int) async -> Void, cancelPairing: @escaping () -> Void, - cancel: @escaping () -> Void + cancel: @escaping () -> Void, + onPairingResult: ((MobilePairingURLConnectionResult) -> Void)? = nil ) { _pairingCode = pairingCode self.initialPresentation = initialPresentation @@ -61,6 +63,7 @@ struct PairingView: View { self.connectManualHost = connectManualHost self.cancelPairing = cancelPairing self.cancel = cancel + self.onPairingResult = onPairingResult _isShowingScanner = State(initialValue: initialPresentation.showsScanner) } @@ -187,7 +190,8 @@ struct PairingView: View { Button(role: .destructive) { startPairingTask { - await acceptVersionWarning() + let result = await acceptVersionWarning() + onPairingResult?(result) } } label: { Text(L10n.string("mobile.pairing.versionWarningContinue", defaultValue: "Continue anyway")) @@ -294,6 +298,12 @@ struct PairingView: View { defaultValue: "Add Tailscale Connection" ) } + if initialPresentation == .tailscaleReplacement { + return L10n.string( + "mobile.connections.tailscale.replace", + defaultValue: "Replace Tailscale Connection" + ) + } if initialPresentation.showsManualPairingControls { return L10n.string("mobile.connections.add", defaultValue: "Add Computer") } @@ -331,7 +341,8 @@ struct PairingView: View { pairingCode = scannedCode isShowingScanner = false startPairingTask { - await connectPairingCode() + let result = await connectPairingCode() + onPairingResult?(result) } } } @@ -411,7 +422,8 @@ struct PairingView: View { if CmxPairingURLScheme(urlString: trimmedHost) != nil { pairingCode = trimmedHost startPairingTask { - await connectPairingCode() + let result = await connectPairingCode() + onPairingResult?(result) } return } From 1aaab8ca2ec4aab107e8b65c113e1eb1025ac4c0 Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Fri, 4 Sep 2026 14:36:22 -0700 Subject: [PATCH 16/33] test: preserve tailscale tombstone during scope claim --- .../MobilePairedMacStoreTests.swift | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/Packages/iOS/CmuxMobilePairedMac/Tests/CmuxMobilePairedMacTests/MobilePairedMacStoreTests.swift b/Packages/iOS/CmuxMobilePairedMac/Tests/CmuxMobilePairedMacTests/MobilePairedMacStoreTests.swift index 3ff221ef2cd5..c1c33332d200 100644 --- a/Packages/iOS/CmuxMobilePairedMac/Tests/CmuxMobilePairedMacTests/MobilePairedMacStoreTests.swift +++ b/Packages/iOS/CmuxMobilePairedMac/Tests/CmuxMobilePairedMacTests/MobilePairedMacStoreTests.swift @@ -897,6 +897,55 @@ import Testing #expect(try await store.activeMac(stackUserID: "user-1", teamID: "team-a")?.routes.map(\.id) == ["updated"]) } + @Test func claimingLegacyMacPreservesRemovedRouteTombstone() async throws { + let (store, directory) = try makeStore() + defer { try? FileManager.default.removeItem(at: directory) } + + let removedRoute = try CmxAttachRoute( + id: "removed", + kind: .tailscale, + endpoint: .hostPort(host: "10.0.0.20", port: 22) + ) + let retainedRoute = try CmxAttachRoute( + id: "retained", + kind: .tailscale, + endpoint: .hostPort(host: "10.0.0.21", port: 22) + ) + + try await store.upsert( + macDeviceID: "legacy-mac", + displayName: "Legacy", + routes: [removedRoute, retainedRoute], + markActive: true, + stackUserID: "user-1", + teamID: nil, + now: Date(timeIntervalSince1970: 1) + ) + #expect(try await store.removeRouteIfAuthorized( + macDeviceID: "legacy-mac", + route: removedRoute, + condition: .matchingInstanceTag(nil), + stackUserID: "user-1", + teamID: nil, + now: Date(timeIntervalSince1970: 2) + )) + + try await store.upsert( + macDeviceID: "legacy-mac", + displayName: "Claimed", + routes: [removedRoute, retainedRoute], + markActive: true, + stackUserID: "user-1", + teamID: "team-a", + now: Date(timeIntervalSince1970: 3) + ) + + #expect(try await store.activeMac( + stackUserID: "user-1", + teamID: "team-a" + )?.routes == [retainedRoute]) + } + @Test func activatingTeamMacClearsVisibleLegacyActiveMac() async throws { let (store, directory) = try makeStore() defer { try? FileManager.default.removeItem(at: directory) } From cb43d048f1ee12f7c78e406b1a65adabc9a3fa6f Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Fri, 4 Sep 2026 14:38:36 -0700 Subject: [PATCH 17/33] test: validate route identity and transport drain --- .../MobilePairedMacRouteAuthorityTests.swift | 37 +++++++++++++++++++ ...obileShellCompositeRouteRemovalTests.swift | 19 ++++++---- 2 files changed, 48 insertions(+), 8 deletions(-) diff --git a/Packages/iOS/CmuxMobilePairedMac/Tests/CmuxMobilePairedMacTests/MobilePairedMacRouteAuthorityTests.swift b/Packages/iOS/CmuxMobilePairedMac/Tests/CmuxMobilePairedMacTests/MobilePairedMacRouteAuthorityTests.swift index 17de9d0430a5..384cd520339f 100644 --- a/Packages/iOS/CmuxMobilePairedMac/Tests/CmuxMobilePairedMacTests/MobilePairedMacRouteAuthorityTests.swift +++ b/Packages/iOS/CmuxMobilePairedMac/Tests/CmuxMobilePairedMacTests/MobilePairedMacRouteAuthorityTests.swift @@ -190,6 +190,43 @@ import Testing )?.routes.map(\.id).sorted() == ["deleted", "retained"]) } + @Test func routeRemovalRejectsStaleIdForDifferentEndpoint() async throws { + let (store, directory) = try makeStore() + defer { try? FileManager.default.removeItem(at: directory) } + let routeA = try route(id: "shared-id", port: 51_007) + let routeB = try route(id: "other-id", port: 51_008) + try await store.upsert( + macDeviceID: "shared-mac", + displayName: "Desk Mac", + routes: [routeA, routeB], + instanceTag: "default", + markActive: true, + stackUserID: "user-1", + teamID: "team-a", + now: Date(timeIntervalSince1970: 10) + ) + + // The stale record reuses routeB's id while still naming routeA's + // endpoint. Removal must follow the endpoint, never the stale id. + let staleRoute = try CmxAttachRoute( + id: routeB.id, + kind: routeA.kind, + endpoint: routeA.endpoint + ) + #expect(try await store.removeRouteIfAuthorized( + macDeviceID: "shared-mac", + route: staleRoute, + condition: .matchingInstanceTag("default"), + stackUserID: "user-1", + teamID: "team-a", + now: Date(timeIntervalSince1970: 20) + )) + #expect(try await store.activeMac( + stackUserID: "user-1", + teamID: "team-a" + )?.routes == [routeB]) + } + private func makeStore() throws -> (MobilePairedMacStore, URL) { let directory = FileManager.default.temporaryDirectory .appendingPathComponent(UUID().uuidString, isDirectory: true) diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellCompositeRouteRemovalTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellCompositeRouteRemovalTests.swift index 4dfcf55d2667..1e12b2cc2043 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellCompositeRouteRemovalTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellCompositeRouteRemovalTests.swift @@ -96,17 +96,20 @@ import Testing actionCapabilities: .none ) - #expect(await shell.removeRoute( - activeRoute, - macDeviceID: "mac-route-removal", - instanceTag: nil - )) + let removal = Task { @MainActor in + await shell.removeRoute( + activeRoute, + macDeviceID: "mac-route-removal", + instanceTag: nil + ) + } + #expect(await closeGate.waitUntilCloseStarted()) + + await closeGate.release() + #expect(await removal.value) #expect(shell.remoteClient == nil) #expect(shell.activeRoute == nil) #expect(shell.connectionState == .disconnected) #expect(shell.connections[MacPairingKey(macDeviceID: "mac-route-removal", instanceTag: nil)] == nil) - #expect(await closeGate.waitUntilCloseStarted()) - - await closeGate.release() } } From bfada1921dc656e6f0edcfb1c2d30afcf750cd23 Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Fri, 4 Sep 2026 14:38:41 -0700 Subject: [PATCH 18/33] fix: await and validate tailscale route removal --- .../MobilePairedMacStore.swift | 10 ++++--- .../MobileShellComposite+RouteRemoval.swift | 28 ++++++++++--------- 2 files changed, 21 insertions(+), 17 deletions(-) diff --git a/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore.swift b/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore.swift index ae08b4f9cc09..56e4c388f0c4 100644 --- a/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore.swift +++ b/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore.swift @@ -727,10 +727,12 @@ public actor MobilePairedMacStore: MobilePairedMacStoring { macDeviceID: macDeviceID, ownerKey: ownerKey ) - guard let removed = currentRoutes.first(where: { $0.id == route.id }) - ?? currentRoutes.first(where: { - $0.kind == route.kind && $0.endpoint == route.endpoint - }) else { return } + // Endpoint and transport kind are the authoritative identity. A + // refreshed registry can reuse a route id for another endpoint, + // so accepting an id-only match could delete the wrong route. + guard let removed = currentRoutes.first(where: { + $0.kind == route.kind && $0.endpoint == route.endpoint + }) else { return } let remaining = currentRoutes.filter { $0.id != removed.id } guard !remaining.isEmpty else { return } diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+RouteRemoval.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+RouteRemoval.swift index fe1f3fc2bf4b..ba1bab6ab07d 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+RouteRemoval.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+RouteRemoval.swift @@ -4,16 +4,14 @@ import Foundation @MainActor extension MobileShellComposite { - /// Route identity for teardown must follow the same id-or-endpoint rules - /// used when a refreshed route replaces an older route record. The kind is - /// part of the identity so a Tailscale route cannot retire a different - /// transport that happens to use the same host and port. + /// Route identity for teardown follows the same kind-and-endpoint rules + /// used by persisted route removal. A refreshed route can reuse an id for + /// another endpoint, so the endpoint must be part of the match. private func routeMatchesForRemoval( _ removed: CmxAttachRoute, _ live: CmxAttachRoute ) -> Bool { - removed.kind == live.kind - && (removed.id == live.id || removed.endpoint == live.endpoint) + removed.kind == live.kind && removed.endpoint == live.endpoint } /// Retire any live session that is using the route after the persistent @@ -22,8 +20,9 @@ extension MobileShellComposite { private func disconnectLiveRouteIfNeeded( _ removedRoute: CmxAttachRoute, ownerKey: MacPairingKey - ) { + ) async { let focused = connections[ownerKey.pairingID] + let foregroundClient = focused?.client ?? remoteClient let isForegroundRoute = connectionState == .connected && foregroundMacKey == ownerKey && (activeRoute.map { @@ -42,6 +41,7 @@ extension MobileShellComposite { removeFocusedConnection(ifMatching: focused) } disconnectLiveConnection(preservingOtherMacWorkspaceState: true) + await foregroundClient?.disconnectAndWaitForTransportDrain() return } @@ -49,7 +49,7 @@ extension MobileShellComposite { routeMatchesForRemoval(removedRoute, focused.route) { removeFocusedConnection(ifMatching: focused) focused.client.retire() - Task { await focused.client.disconnect() } + await focused.client.disconnectAndWaitForTransportDrain() markSecondaryMacUnavailable(ownerKey) } @@ -78,8 +78,10 @@ extension MobileShellComposite { $0.macDeviceID == macDeviceID && $0.instanceTag == instanceTag }) else { return false } - let routes = mac.routes.filter { $0.id != route.id } - guard routes.count != mac.routes.count else { return false } + guard let removedRoute = mac.routes.first(where: { + routeMatchesForRemoval(route, $0) + }) else { return false } + let routes = mac.routes.filter { $0.id != removedRoute.id } do { if routes.isEmpty { guard deleteComputerIfLastRoute else { return false } @@ -92,7 +94,7 @@ extension MobileShellComposite { } else { let wrote = try await pairedMacStore.removeRouteIfAuthorized( macDeviceID: mac.macDeviceID, - route: route, + route: removedRoute, condition: .matchingInstanceTag(mac.instanceTag), stackUserID: mac.stackUserID ?? scope.userID, teamID: mac.teamID, @@ -101,8 +103,8 @@ extension MobileShellComposite { guard wrote else { return false } } guard await isScopeCurrent(scope) else { return false } - disconnectLiveRouteIfNeeded( - route, + await disconnectLiveRouteIfNeeded( + removedRoute, ownerKey: MacPairingKey( macDeviceID: mac.macDeviceID, instanceTag: mac.instanceTag From 34f41f19f08c95b67c54c1afae2e22d4438fc014 Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Fri, 4 Sep 2026 14:54:16 -0700 Subject: [PATCH 19/33] fix: localize tailscale replacement action --- .../Resources/Localizable.xcstrings | 59 +++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Resources/Localizable.xcstrings b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Resources/Localizable.xcstrings index 56a5beb23ddb..beef9f864d0d 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Resources/Localizable.xcstrings +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Resources/Localizable.xcstrings @@ -5177,6 +5177,65 @@ } } }, + "mobile.connections.tailscale.replace": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Replace Tailscale Connection" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "Tailscale接続を置換" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Tailscale-Verbindung ersetzen" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Remplacer la connexion Tailscale" + } + }, + "ar": { + "stringUnit": { + "state": "translated", + "value": "استبدال اتصال Tailscale" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Reemplazar conexión de Tailscale" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "取代 Tailscale 連線" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "替换 Tailscale 连接" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "Tailscale 연결 교체" + } + } + } + }, "mobile.connections.route.deleteComputer.title": { "extractionState": "manual", "localizations": { From b8df7aff53f2bb00163bb3c1f113ab771c179142 Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Fri, 4 Sep 2026 15:23:29 -0700 Subject: [PATCH 20/33] fix: preserve exact backup scope for route removal --- .../MobilePairedMacStoring.swift | 5 +++- ...ingUpPairedMacStore+AuthorizedRoutes.swift | 26 ++++++++++++++++--- .../BackingUpPairedMacStore.swift | 11 ++++---- 3 files changed, 33 insertions(+), 9 deletions(-) diff --git a/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStoring.swift b/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStoring.swift index 40325c0291f5..f3dea6bb8822 100644 --- a/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStoring.swift +++ b/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStoring.swift @@ -269,7 +269,10 @@ extension MobilePairedMacStoring { ).id } guard let current else { return false } - let remaining = current.routes.filter { $0.id != route.id } + guard let removed = current.routes.first(where: { + $0.kind == route.kind && $0.endpoint == route.endpoint + }) else { return false } + let remaining = current.routes.filter { $0.id != removed.id } guard remaining.count < current.routes.count, !remaining.isEmpty else { return false } return try await upsertRoutesIfAuthorized( macDeviceID: macDeviceID, diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/BackingUpPairedMacStore+AuthorizedRoutes.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/BackingUpPairedMacStore+AuthorizedRoutes.swift index 6e5e767ea16e..9304ff8b0a05 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/BackingUpPairedMacStore+AuthorizedRoutes.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/BackingUpPairedMacStore+AuthorizedRoutes.swift @@ -19,23 +19,43 @@ extension BackingUpPairedMacStore { case .matchingInstanceTag(let tag): instanceTag = tag case .unclaimed: instanceTag = nil } + let visible = try? await macFor( + macDeviceID, + instanceTag: instanceTag, + stackUserID: stackUserID, + teamID: team, + requiresExactInstanceTag: true + ) + let mutationTeam = visible?.teamID ?? team let wrote = try await inner.removeRouteIfAuthorized( macDeviceID: macDeviceID, route: route, condition: condition, stackUserID: stackUserID, - teamID: team, + teamID: mutationTeam, now: now ) guard wrote, let account = stackUserID, !account.isEmpty else { return wrote } lastSignedInAccount = account + let pairingID = MobilePairedMac.pairingID( + macDeviceID: macDeviceID, + instanceTag: instanceTag + ) + let verifiedDestination = await backupTeamStore.load( + key: backupTeamKey( + account: account, + rowTeamID: visible?.teamID, + pairingID: pairingID + ) + ) await uploadCurrentRecord( macDeviceID: macDeviceID, instanceTag: instanceTag, account: account, - teamID: team, + teamID: verifiedDestination ?? visible?.teamID, includesCustomizations: false, - instanceAuthority: .compareAndSet + instanceAuthority: .compareAndSet, + resolvesNilTeam: false ) return true } diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/BackingUpPairedMacStore.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/BackingUpPairedMacStore.swift index 581fe0d2055b..5aeb0a6515a8 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/BackingUpPairedMacStore.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/BackingUpPairedMacStore.swift @@ -41,7 +41,7 @@ public actor BackingUpPairedMacStore: MobilePairedMacStoring, PairedMacBackupRef /// where each record's backup actually lives, learned from the upload echo, /// so its delete tombstone can be routed there instead of re-resolving a /// nil team at delete time. - private let backupTeamStore: any PairedMacBackupTeamStoring + let backupTeamStore: any PairedMacBackupTeamStoring private var pendingDeleteIDsByScope: [String: Set] = [:] /// Bumped by every `removeAll()` (sign-out wipe). A restore captures it before /// awaiting its task and re-checks after: a restore that completed/resumed @@ -85,7 +85,7 @@ public actor BackingUpPairedMacStore: MobilePairedMacStoring, PairedMacBackupRef /// same (account, device, tag) pairing to exist under several team scopes, /// so a key without the team would let team B's upload overwrite team A's /// destination and later route A's tombstone into B's backup. - private func backupTeamKey(account: String, rowTeamID: String?, pairingID: String) -> String { + func backupTeamKey(account: String, rowTeamID: String?, pairingID: String) -> String { "\(account)\u{0}\(rowTeamID ?? "")\u{0}\(pairingID)" } @@ -1118,7 +1118,7 @@ public actor BackingUpPairedMacStore: MobilePairedMacStoring, PairedMacBackupRef )?.stackUserID } - private func macFor( + func macFor( _ macDeviceID: String, instanceTag: String?, stackUserID: String?, @@ -1171,7 +1171,8 @@ public actor BackingUpPairedMacStore: MobilePairedMacStoring, PairedMacBackupRef teamID: String? = nil, includesCustomizations: Bool = false, allowTombstoneRevive: Bool = false, - instanceAuthority: PairedMacBackupInstanceAuthorityWriteMode = .authoritative + instanceAuthority: PairedMacBackupInstanceAuthorityWriteMode = .authoritative, + resolvesNilTeam: Bool = true ) async -> Bool { let macDeviceID = cmxCanonicalDeviceID(macDeviceID) let pairingID = MobilePairedMac.pairingID( @@ -1182,7 +1183,7 @@ public actor BackingUpPairedMacStore: MobilePairedMacStoring, PairedMacBackupRef .pairedMacBackupWriteStarted, correlationID: pairingID ) - let team = await resolvedTeam(teamID) + let team = resolvesNilTeam ? await resolvedTeam(teamID) : teamID let localMacs: [MobilePairedMac] do { localMacs = try await inner.loadAll(stackUserID: account, teamID: team) From 6cb1af4a2ec405bb0619d843064e37fd4362a512 Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Fri, 4 Sep 2026 15:38:01 -0700 Subject: [PATCH 21/33] fix: cancel reconnect when route is deleted --- .../MobilePairedMacStore.swift | 6 +- .../MobilePairedMacStoring.swift | 5 +- .../MobileShellComposite+RouteRemoval.swift | 32 +++++++- ...obileShellCompositeRouteRemovalTests.swift | 79 ++++++++++++++++++- 4 files changed, 114 insertions(+), 8 deletions(-) diff --git a/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore.swift b/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore.swift index 56e4c388f0c4..f49ec7d98a90 100644 --- a/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore.swift +++ b/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore.swift @@ -730,10 +730,12 @@ public actor MobilePairedMacStore: MobilePairedMacStoring { // Endpoint and transport kind are the authoritative identity. A // refreshed registry can reuse a route id for another endpoint, // so accepting an id-only match could delete the wrong route. - guard let removed = currentRoutes.first(where: { + guard let removedIndex = currentRoutes.firstIndex(where: { $0.kind == route.kind && $0.endpoint == route.endpoint }) else { return } - let remaining = currentRoutes.filter { $0.id != removed.id } + let removed = currentRoutes[removedIndex] + var remaining = currentRoutes + remaining.remove(at: removedIndex) guard !remaining.isEmpty else { return } let encoded = try Self.encodeRouteEndpoint(removed) diff --git a/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStoring.swift b/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStoring.swift index f3dea6bb8822..92e77558e5d0 100644 --- a/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStoring.swift +++ b/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStoring.swift @@ -269,10 +269,11 @@ extension MobilePairedMacStoring { ).id } guard let current else { return false } - guard let removed = current.routes.first(where: { + guard let removedIndex = current.routes.firstIndex(where: { $0.kind == route.kind && $0.endpoint == route.endpoint }) else { return false } - let remaining = current.routes.filter { $0.id != removed.id } + var remaining = current.routes + remaining.remove(at: removedIndex) guard remaining.count < current.routes.count, !remaining.isEmpty else { return false } return try await upsertRoutesIfAuthorized( macDeviceID: macDeviceID, diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+RouteRemoval.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+RouteRemoval.swift index ba1bab6ab07d..d792da19c277 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+RouteRemoval.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+RouteRemoval.swift @@ -23,6 +23,19 @@ extension MobileShellComposite { ) async { let focused = connections[ownerKey.pairingID] let foregroundClient = focused?.client ?? remoteClient + let recoveryKey = foregroundMacDeviceID == nil + ? recoveryTargetMacDeviceID.map { + MacPairingKey( + macDeviceID: $0, + instanceTag: recoveryTargetInstanceTag + ) + } + : nil + let foregroundAttemptKey = recoveryKey ?? foregroundMacKey + let matchesForegroundAttempt = foregroundAttemptKey == ownerKey + && activeRoute.map { + routeMatchesForRemoval(removedRoute, $0) + } == true let isForegroundRoute = connectionState == .connected && foregroundMacKey == ownerKey && (activeRoute.map { @@ -31,7 +44,18 @@ extension MobileShellComposite { routeMatchesForRemoval(removedRoute, $0.route) } == true) - if isForegroundRoute { + if matchesForegroundAttempt || isForegroundRoute { + if matchesForegroundAttempt { + // A reconnect publishes its candidate route before the dial + // starts. Supersede that exact attempt even while the shell is + // still disconnected, otherwise it can finish on the deleted + // endpoint. + storedMacReconnectGeneration &+= 1 + isReconnectingStoredMac = false + pendingForcedStoredMacReconnect = false + didFinishStoredMacReconnectAttempt = true + connectionAttemptGeneration = UUID() + } // `clearRemoteConnectionContext` historically looked up the // foreground registry entry by bare device id. Remove the exact // tagged entry first so the live registry cannot retain a client @@ -78,10 +102,12 @@ extension MobileShellComposite { $0.macDeviceID == macDeviceID && $0.instanceTag == instanceTag }) else { return false } - guard let removedRoute = mac.routes.first(where: { + guard let removedRouteIndex = mac.routes.firstIndex(where: { routeMatchesForRemoval(route, $0) }) else { return false } - let routes = mac.routes.filter { $0.id != removedRoute.id } + let removedRoute = mac.routes[removedRouteIndex] + var routes = mac.routes + routes.remove(at: removedRouteIndex) do { if routes.isEmpty { guard deleteComputerIfLastRoute else { return false } diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellCompositeRouteRemovalTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellCompositeRouteRemovalTests.swift index 1e12b2cc2043..b5a5d386ceef 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellCompositeRouteRemovalTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellCompositeRouteRemovalTests.swift @@ -25,7 +25,7 @@ import Testing endpoint: .hostPort(host: "100.64.0.17", port: 56_584) ) let fallbackRoute = try CmxAttachRoute( - id: "tailscale-fallback", + id: "tailscale-active", kind: .tailscale, endpoint: .hostPort(host: "100.64.0.18", port: 56_584) ) @@ -111,5 +111,82 @@ import Testing #expect(shell.activeRoute == nil) #expect(shell.connectionState == .disconnected) #expect(shell.connections[MacPairingKey(macDeviceID: "mac-route-removal", instanceTag: nil)] == nil) + let remaining = try await pairedStore.loadAll( + stackUserID: "user-1", + teamID: nil + ) + #expect(remaining.first?.routes == [fallbackRoute]) + } + + @Test func deletingRouteDuringForegroundReconnectSupersedesAttempt() async throws { + let directory = FileManager.default.temporaryDirectory + .appendingPathComponent(UUID().uuidString, isDirectory: true) + try FileManager.default.createDirectory( + at: directory, + withIntermediateDirectories: true + ) + defer { try? FileManager.default.removeItem(at: directory) } + + let pairedStore = try MobilePairedMacStore( + databaseURL: directory.appendingPathComponent("paired.sqlite3") + ) + let route = try CmxAttachRoute( + id: "tailscale-reconnect", + kind: .tailscale, + endpoint: .hostPort(host: "100.64.0.19", port: 56_584) + ) + try await pairedStore.upsert( + macDeviceID: "mac-route-reconnect", + displayName: "Route Reconnect Mac", + routes: [route, try CmxAttachRoute( + id: "iroh-reconnect", + kind: .iroh, + endpoint: .peer( + identity: CmxIrohPeerIdentity( + endpointID: String(repeating: "a", count: 64) + ), + pathHints: [] + ) + )], + markActive: true, + stackUserID: "user-1", + teamID: nil, + now: Date() + ) + + let closeGate = LivenessTransportCloseGate() + let runtime = LivenessTestRuntime( + transportFactory: LivenessTransportFactory( + router: LivenessHostRouter(), + box: TransportBox(), + closeGate: closeGate + ), + now: Date.init + ) + let shell = MobileShellComposite( + runtime: runtime, + isSignedIn: true, + connectionState: .disconnected, + pairedMacStore: pairedStore, + identityProvider: StaticIdentityProvider(userID: "user-1") + ) + await shell.loadPairedMacs() + shell.activeRoute = route + shell.foregroundMacDeviceID = "mac-route-reconnect" + shell.isReconnectingStoredMac = true + let generation = shell.storedMacReconnectGeneration + + let removal = Task { @MainActor in + await shell.removeRoute( + route, + macDeviceID: "mac-route-reconnect", + instanceTag: nil + ) + } + + #expect(await removal.value) + #expect(shell.storedMacReconnectGeneration > generation) + #expect(!shell.isReconnectingStoredMac) + #expect(shell.activeRoute == nil) } } From 32eeed2032e0065eb5ed2b2526a8306e0b7d4cb9 Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Fri, 4 Sep 2026 15:40:47 -0700 Subject: [PATCH 22/33] chore: remove obsolete reconnect policy locals --- .../MobileShellComposite+ConnectionRecovery.swift | 7 ------- 1 file changed, 7 deletions(-) diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift index 9ce70b5959be..a3ee6d941498 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift @@ -760,13 +760,6 @@ extension MobileShellComposite { return .failed(.unsupportedRoute) } let supportedKinds = runtime?.supportedRouteKinds ?? [] - let hasIrohRoute = routes.contains { $0.kind == .iroh } - let hasTailscaleRoute = routes.contains { $0.kind == .tailscale } - let shouldUseAuthorizedTailscaleRoute = resolvedMethod == .tailscale - || (resolvedMethod == .automatic - && !hasIrohRoute - && hasTailscaleRoute - && !legacyTailscaleRoutes.isEmpty) var pinnedRoutes = Self.storedReconnectRoutes( routes, supportedKinds: supportedKinds, From b77bdc28c250c900e9e1dcf33a9e58b0f8de643e Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Fri, 4 Sep 2026 15:51:01 -0700 Subject: [PATCH 23/33] fix: suppress deleted routes during refresh --- .../MobilePairedMacStore+Records.swift | 13 +++++- .../MobilePairedMacStore.swift | 45 ++++++++++++++++++- 2 files changed, 56 insertions(+), 2 deletions(-) diff --git a/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore+Records.swift b/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore+Records.swift index e9fc3fb89fd2..8b035d906c94 100644 --- a/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore+Records.swift +++ b/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore+Records.swift @@ -331,7 +331,10 @@ extension MobilePairedMacStore { return routes } - func fetchRoutes(macDeviceID: String, ownerKey: String) throws -> [CmxAttachRoute] { + func fetchRouteRemovalKeys( + macDeviceID: String, + ownerKey: String + ) throws -> Set { var removedStatement: OpaquePointer? defer { sqlite3_finalize(removedStatement) } let removedRC = sqlite3_prepare_v2( @@ -367,6 +370,14 @@ extension MobilePairedMacStore { } removedKeys.insert("\(kind)\u{1F}\(endpoint)") } + return removedKeys + } + + func fetchRoutes(macDeviceID: String, ownerKey: String) throws -> [CmxAttachRoute] { + let removedKeys = try fetchRouteRemovalKeys( + macDeviceID: macDeviceID, + ownerKey: ownerKey + ) var statement: OpaquePointer? defer { sqlite3_finalize(statement) } diff --git a/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore.swift b/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore.swift index f49ec7d98a90..f04609905ee6 100644 --- a/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore.swift +++ b/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore.swift @@ -820,6 +820,10 @@ public actor MobilePairedMacStore: MobilePairedMacStoring { // unknown row would strand an unowned bearer capability. return } + var currentRoutes = try fetchRoutes( + macDeviceID: macDeviceID, + ownerKey: ownerKey + ) for route in grantRoutes { let encoded = try Self.encodeRoute(route) let encodedEndpoint = try Self.encodeRouteEndpoint(route) @@ -851,6 +855,34 @@ public actor MobilePairedMacStore: MobilePairedMacStoring { .text(route.kind.rawValue), .text(encodedEndpoint), ]) + // The preceding passive refresh intentionally filtered this + // endpoint because its tombstone was still present. Reinsert + // the route as part of this explicit pairing authorization so + // a successful scan immediately becomes usable again. + if let disclosed = route.disclosed(for: .authenticated, at: Date()) { + currentRoutes.removeAll { + $0.kind == disclosed.kind && $0.endpoint == disclosed.endpoint + } + currentRoutes.append(disclosed) + } + } + try exec( + "DELETE FROM mac_routes WHERE mac_device_id = ? AND owner_key = ?;", + binding: [.text(macDeviceID), .text(ownerKey)] + ) + for route in currentRoutes { + try exec(""" + INSERT INTO mac_routes ( + mac_device_id, owner_key, route_id, kind, endpoint_json, priority + ) VALUES (?, ?, ?, ?, ?, ?); + """, binding: [ + .text(macDeviceID), + .text(ownerKey), + .text(route.id), + .text(route.kind.rawValue), + .text(try Self.encodeRoute(route)), + .int(Int64(route.priority)), + ]) } } } @@ -1002,6 +1034,10 @@ public actor MobilePairedMacStore: MobilePairedMacStoring { } else { existingRoutes = [] } + let removedRouteKeys = try fetchRouteRemovalKeys( + macDeviceID: macDeviceID, + ownerKey: ownerKey + ) let incomingHasIroh = routes.contains { $0.kind == .iroh } let pinnedIrohRoutes = existingRoutes.filter { $0.kind == .iroh } let userAuthorizedTailscaleRoutes = try fetchLegacyTailscaleRoutes( @@ -1026,7 +1062,14 @@ public actor MobilePairedMacStore: MobilePairedMacStoring { // routes; replacing the stored Iroh identity in that case would allow // a later admission failure to downgrade into Stack-bearer RPC. A new // Iroh route replaces the old identity normally. - var routesToPersist = routes + var routesToPersist: [CmxAttachRoute] = [] + routesToPersist.reserveCapacity(routes.count + pinnedIrohRoutes.count) + for route in routes { + let endpoint = try Self.encodeRouteEndpoint(route) + let key = "\(route.kind.rawValue)\u{1F}\(endpoint)" + guard !removedRouteKeys.contains(key) else { continue } + routesToPersist.append(route) + } if !pinnedIrohRoutes.isEmpty, !incomingHasIroh { routesToPersist.append(contentsOf: pinnedIrohRoutes) } From 429571b8b4c90b3bd179bdc6693135e3d890af47 Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Fri, 4 Sep 2026 15:59:51 -0700 Subject: [PATCH 24/33] fix: bound route tombstone retention --- .../MobilePairedMacStore+Records.swift | 25 +++++++++++++++++++ .../MobilePairedMacStore.swift | 8 ++++++ 2 files changed, 33 insertions(+) diff --git a/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore+Records.swift b/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore+Records.swift index 8b035d906c94..99668cca99fa 100644 --- a/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore+Records.swift +++ b/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore+Records.swift @@ -373,6 +373,31 @@ extension MobilePairedMacStore { return removedKeys } + /// Retain only the newest endpoint tombstones for a paired-Mac scope so + /// repeated route churn cannot make refresh cost grow without bound. + func compactRouteRemovalTombstones( + macDeviceID: String, + ownerKey: String + ) throws { + try exec(""" + DELETE FROM mac_route_removals + WHERE mac_device_id = ? AND owner_key = ? + AND id NOT IN ( + SELECT id + FROM mac_route_removals + WHERE mac_device_id = ? AND owner_key = ? + ORDER BY id DESC + LIMIT ? + ); + """, binding: [ + .text(macDeviceID), + .text(ownerKey), + .text(macDeviceID), + .text(ownerKey), + .int(Int64(MobilePairedMacStore.routeRemovalTombstoneLimit)), + ]) + } + func fetchRoutes(macDeviceID: String, ownerKey: String) throws -> [CmxAttachRoute] { let removedKeys = try fetchRouteRemovalKeys( macDeviceID: macDeviceID, diff --git a/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore.swift b/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore.swift index f04609905ee6..67247040b900 100644 --- a/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore.swift +++ b/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore.swift @@ -16,6 +16,10 @@ public actor MobilePairedMacStore: MobilePairedMacStoring { /// The schema version this build creates and migrates to. public static let currentSchemaVersion: Int32 = 12 + /// Keep route-removal suppression bounded while retaining ample history for + /// normal Tailscale endpoint churn. Explicit pairing can restore any route. + static let routeRemovalTombstoneLimit = 256 + private let dbPath: String // `nonisolated(unsafe)` only so the (Swift 6 nonisolated) `deinit` can close // the handle. Every other access goes through actor-isolated methods, and @@ -749,6 +753,10 @@ public actor MobilePairedMacStore: MobilePairedMacStoring { .text(removed.kind.rawValue), .text(encoded), ]) + try compactRouteRemovalTombstones( + macDeviceID: macDeviceID, + ownerKey: ownerKey + ) try upsertMacRow( macDeviceID: macDeviceID, ownerKey: ownerKey, From e6987e08043a6ad04b348994bc8da39e9671d93c Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Fri, 4 Sep 2026 19:31:52 -0700 Subject: [PATCH 25/33] fix: make replacement pairing fail closed --- ...ileShellComposite+ConnectionRecovery.swift | 4 +- .../MobileShellComposite.swift | 100 ++++++++++++++---- .../TailscalePairingRegressionTests.swift | 39 +++++++ .../CMUXMobileRootView.swift | 4 +- .../MacComputerDetailView.swift | 23 +++- .../CmuxMobileShellUI/PairingView.swift | 7 +- 6 files changed, 145 insertions(+), 32 deletions(-) diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift index a3ee6d941498..2594ca466d0d 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ConnectionRecovery.swift @@ -653,7 +653,7 @@ extension MobileShellComposite { instanceTag: String? = nil, ifStillCurrent: (() -> Bool)? = nil ) async { - await connectManualHost( + _ = await connectManualHost( name: name, host: host, port: port, @@ -833,7 +833,7 @@ extension MobileShellComposite { ) for route in candidates { guard ifStillCurrent?() ?? true else { return .superseded } - await connectManualHost( + _ = await connectManualHost( name: name, host: route.host, port: route.port, diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift index 9302cc642b10..3b31ab64c6fb 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift @@ -2628,7 +2628,11 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { } /// Connect using the current pairing input, accepting either a code or pairing URL. - public func connectPairingInput() async -> MobilePairingURLConnectionResult { + public func connectPairingInput( + allowPreview: Bool = true, + pairedMacDeviceID: String? = nil, + instanceTag: String? = nil + ) async -> MobilePairingURLConnectionResult { let trimmedCode = pairingCode.trimmingCharacters(in: .whitespacesAndNewlines) guard !trimmedCode.isEmpty else { return .failed @@ -2636,7 +2640,20 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { if CmxPairingURLScheme(urlString: trimmedCode) != nil { // The pairing input field is an explicit in-app code entry (scan // or paste), the act that authorizes a compatibility Tailscale dial. - return await connectPairingURLResult(trimmedCode, userEnteredPairingCode: true) + return await connectPairingURLResult( + trimmedCode, + acceptedVersionWarning: false, + userEnteredPairingCode: true, + pairedMacDeviceID: pairedMacDeviceID, + instanceTagExpectation: Self.pairingInstanceTagExpectation(instanceTag) + ) + } + guard allowPreview else { + applyPairingValidationFailure(.invalidCode) + connectionState = .disconnected + macConnectionStatus = .unavailable + clearRemoteConnectionContext() + return .failed } connectPreviewHost() return .connected @@ -2650,11 +2667,30 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { port: Int, pairedMacDeviceID: String? = nil ) async { + _ = await connectManualHost( + name: name, + host: host, + port: port, + pairedMacDeviceID: pairedMacDeviceID, + recordsPairingAttempt: true + ) + } + + /// Connect to a manually-entered host and return the terminal pairing + /// result so presentation surfaces can dismiss only after success. + public func connectManualHostResult( + name: String, + host: String, + port: Int, + pairedMacDeviceID: String? = nil, + instanceTag: String? = nil + ) async -> MobilePairingURLConnectionResult { await connectManualHost( name: name, host: host, port: port, pairedMacDeviceID: pairedMacDeviceID, + instanceTagExpectation: Self.pairingInstanceTagExpectation(instanceTag), recordsPairingAttempt: true ) } @@ -2667,7 +2703,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { instanceTagExpectation: MobileMacInstanceTagExpectation = .adopt, recordsPairingAttempt: Bool, ifStillCurrent: (() -> Bool)? = nil - ) async { + ) async -> MobilePairingURLConnectionResult { let trimmedName = name.trimmingCharacters(in: .whitespacesAndNewlines) guard let normalizedHost = MobileShellRouteAuthPolicy.normalizedManualHost(host) else { if recordsPairingAttempt { @@ -2685,7 +2721,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { "failure_phase": .string("validation"), "is_first_pair": .bool(!hasKnownPairedMac), ]) - return + return .failed } guard (1...65535).contains(port) else { if recordsPairingAttempt { @@ -2703,7 +2739,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { "failure_phase": .string("validation"), "is_first_pair": .bool(!hasKnownPairedMac), ]) - return + return .failed } guard let directRoute = try? Self.manualHostRoute( @@ -2728,7 +2764,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { "failure_phase": .string("validation"), "is_first_pair": .bool(!hasKnownPairedMac), ]) - return + return .failed } let isLoopbackRoute = MobileShellRouteAuthPolicy.routeIsLoopback(directRoute) @@ -2754,7 +2790,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { "failure_phase": .string("validation"), "is_first_pair": .bool(!hasKnownPairedMac), ]) - return + return .failed } // A fresh manual attempt is an explicit user action, so a numeric @@ -2784,7 +2820,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { "failure_phase": .string("validation"), "is_first_pair": .bool(!hasKnownPairedMac), ]) - return + return .failed } } else { userTailscalePairingAuthorization = nil @@ -2823,7 +2859,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { phase: "preflight", routes: manualRoutes ) == .proceed else { - return + return .superseded } } do { @@ -2836,10 +2872,10 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { ) guard isCurrentPairingAttempt(attemptID), ifStillCurrent?() ?? true else { - return + return .superseded } if let sameRouteProbeClient { - guard remoteClient === sameRouteProbeClient else { return } + guard remoteClient === sameRouteProbeClient else { return .superseded } preparePairingConnectionAttempt() } let noThrowFailure = try await connect( @@ -2853,45 +2889,49 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { instanceTagExpectation: instanceTagExpectation, ifStillCurrent: ifStillCurrent ) - guard isCurrentPairingAttempt(attemptID) else { return } + guard isCurrentPairingAttempt(attemptID) else { return .superseded } if connectionState == .connected { // `connect()` persists the manual pairing, while Settings, // the Mac picker, and the task composer read the shared // in-memory list. Refresh it before dismissing PairingView so // those surfaces can use the new Mac immediately. await loadPairedMacs() - guard isCurrentPairingAttempt(attemptID) else { return } + guard isCurrentPairingAttempt(attemptID) else { return .superseded } recordPairingSucceeded() + return .connected } else { // `connect()` returned without connecting and already set a // specific error; record without overwriting that message. recordFailureForCurrentConnectionError(phase: "connect", category: noThrowFailure) + return .failed } } catch is CancellationError { - guard isCurrentPairingAttempt(attemptID) else { return } + guard isCurrentPairingAttempt(attemptID) else { return .superseded } if sameRouteProbeClient.map({ remoteClient === $0 }) == true { - return + return .superseded } connectionState = .disconnected macConnectionStatus = .unavailable clearRemoteConnectionContext() + return .failed } catch { - guard isCurrentPairingAttempt(attemptID) else { return } + guard isCurrentPairingAttempt(attemptID) else { return .superseded } mobileShellLog.error("manual host pairing failed: \(String(describing: error), privacy: .private)") // A definitive auth failure (expired/invalid token after the // refresh-then-retry in the RPC layer already gave up) must drive the // re-auth prompt, not the generic "could not connect / Retry" banner. if disconnectForAuthorizationFailureIfNeeded(error) { - return + return .failed } let category = MobilePairingFailureCategory.classify(error: error, route: activeRoute ?? directRoute) applyPairingFailure(category, phase: "connect") if sameRouteProbeClient.map({ remoteClient === $0 }) == true { - return + return .failed } connectionState = .disconnected macConnectionStatus = .unavailable clearRemoteConnectionContext() + return .failed } } @@ -4796,6 +4836,13 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { ) } + static func pairingInstanceTagExpectation( + _ instanceTag: String? + ) -> MobileMacInstanceTagExpectation { + guard let instanceTag, !instanceTag.isEmpty else { return .adopt } + return .require(instanceTag) + } + @discardableResult public func connectPairingURL(_ rawValue: String? = nil) async -> Bool { await connectPairingURLResult(rawValue).didConnect @@ -4822,7 +4869,9 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { private func connectPairingURLResult( _ rawValue: String? = nil, acceptedVersionWarning: Bool, - userEnteredPairingCode: Bool = false + userEnteredPairingCode: Bool = false, + pairedMacDeviceID: String? = nil, + instanceTagExpectation: MobileMacInstanceTagExpectation = .adopt ) async -> MobilePairingURLConnectionResult { MobileDebugLog.shared.append( "pairing.qr_connect.begin user_entered=\(userEnteredPairingCode) accepted_version_warning=\(acceptedVersionWarning)" @@ -4967,7 +5016,9 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { guard isCurrentPairingAttempt(attemptID) else { return .superseded } let noThrowFailure = try await connect( ticket: ticket, - userTailscalePairingAuthorizations: userTailscalePairingAuthorizations + userTailscalePairingAuthorizations: userTailscalePairingAuthorizations, + pairedMacDeviceID: pairedMacDeviceID, + instanceTagExpectation: instanceTagExpectation ) guard isCurrentPairingAttempt(attemptID) else { return .superseded } if connectionState == .connected && activeTicket != nil { @@ -5081,7 +5132,10 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { /// authentication only after the accepted pairing flow reaches a terminal /// state. @discardableResult - public func acceptPairingVersionWarning() async -> MobilePairingURLConnectionResult { + public func acceptPairingVersionWarning( + pairedMacDeviceID: String? = nil, + instanceTag: String? = nil + ) async -> MobilePairingURLConnectionResult { guard let rawURL = pendingPairingVersionWarningURL else { clearPairingVersionWarning() return .failed @@ -5091,7 +5145,9 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { return await connectPairingURLResult( rawURL, acceptedVersionWarning: true, - userEnteredPairingCode: wasUserEntered + userEnteredPairingCode: wasUserEntered, + pairedMacDeviceID: pairedMacDeviceID, + instanceTagExpectation: Self.pairingInstanceTagExpectation(instanceTag) ) } diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/TailscalePairingRegressionTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/TailscalePairingRegressionTests.swift index 73fa47e4135d..c48ed88b4e82 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/TailscalePairingRegressionTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/TailscalePairingRegressionTests.swift @@ -257,6 +257,45 @@ import Testing #expect(await router.authorization(for: "workspace.list").isEmpty) } + @Test func scannerInputRejectsNonPairingPayload() async throws { + let runtime = LivenessTestRuntime( + transportFactory: LivenessTransportFactory( + router: LivenessHostRouter(), + box: TransportBox() + ), + now: { Self.fixedNow }, + supportedRouteKinds: [.tailscale] + ) + let store = makeStore(runtime: runtime) + store.pairingCode = "https://example.com/not-a-cmux-pairing-code" + + let result = await store.connectPairingInput(allowPreview: false) + + #expect(result == .failed) + #expect(store.connectionState == .disconnected) + #expect(store.connectionError?.isEmpty == false) + } + + @Test func replacementPairingRejectsDifferentMacIdentity() async throws { + let router = LivenessHostRouter() + let box = TransportBox() + let runtime = LivenessTestRuntime( + transportFactory: LivenessTransportFactory(router: router, box: box), + now: { Self.fixedNow }, + supportedRouteKinds: [.tailscale] + ) + let store = makeStore(runtime: runtime) + store.pairingCode = currentQRCode() + + let result = await store.connectPairingInput( + allowPreview: false, + pairedMacDeviceID: "another-mac" + ) + + #expect(result == .failed) + #expect(store.connectionState == .disconnected) + } + private func makeStore( runtime: any MobileSyncRuntime, pairedMacStore: (any MobilePairedMacStoring)? = nil, diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView.swift index 3a7cb886debd..1d65bb8195e0 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/CMUXMobileRootView.swift @@ -596,7 +596,7 @@ struct CMUXMobileRootView: View { connectionErrorGuidance: store.connectionErrorGuidance, versionWarning: store.pairingVersionWarning, connectPairingCode: { - await store.connectPairingInput() + await store.connectPairingInput(allowPreview: false) }, acceptVersionWarning: { let result = await store.acceptPairingVersionWarning() @@ -607,7 +607,7 @@ struct CMUXMobileRootView: View { return result }, connectManualHost: { name, host, port in - await store.connectManualHost(name: name, host: host, port: port) + await store.connectManualHostResult(name: name, host: host, port: port) }, cancelPairing: cancelPairing, cancel: dismissAddDeviceSheet diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MacComputerDetailView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MacComputerDetailView.swift index 3497531fb3c3..1913a18ce33b 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MacComputerDetailView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/MacComputerDetailView.swift @@ -290,10 +290,27 @@ struct MacComputerDetailView: View { connectionError: store.connectionError, connectionErrorGuidance: store.connectionErrorGuidance, versionWarning: store.pairingVersionWarning, - connectPairingCode: { await store.connectPairingInput() }, - acceptVersionWarning: { await store.acceptPairingVersionWarning() }, + connectPairingCode: { + await store.connectPairingInput( + allowPreview: false, + pairedMacDeviceID: macDeviceID, + instanceTag: instanceTag + ) + }, + acceptVersionWarning: { + await store.acceptPairingVersionWarning( + pairedMacDeviceID: macDeviceID, + instanceTag: instanceTag + ) + }, connectManualHost: { name, host, port in - await store.connectManualHost(name: name, host: host, port: port) + await store.connectManualHostResult( + name: name, + host: host, + port: port, + pairedMacDeviceID: macDeviceID, + instanceTag: instanceTag + ) }, cancelPairing: { store.cancelPairing() }, cancel: { showsAddTailscaleConnection = false }, diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PairingView.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PairingView.swift index 1e61bbca4c39..4292753b0a16 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PairingView.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/PairingView.swift @@ -22,7 +22,7 @@ struct PairingView: View { let versionWarning: String? let connectPairingCode: () async -> MobilePairingURLConnectionResult let acceptVersionWarning: () async -> MobilePairingURLConnectionResult - let connectManualHost: (String, String, Int) async -> Void + let connectManualHost: (String, String, Int) async -> MobilePairingURLConnectionResult let cancelPairing: () -> Void let cancel: () -> Void let onPairingResult: ((MobilePairingURLConnectionResult) -> Void)? @@ -48,7 +48,7 @@ struct PairingView: View { versionWarning: String?, connectPairingCode: @escaping () async -> MobilePairingURLConnectionResult, acceptVersionWarning: @escaping () async -> MobilePairingURLConnectionResult, - connectManualHost: @escaping (String, String, Int) async -> Void, + connectManualHost: @escaping (String, String, Int) async -> MobilePairingURLConnectionResult, cancelPairing: @escaping () -> Void, cancel: @escaping () -> Void, onPairingResult: ((MobilePairingURLConnectionResult) -> Void)? = nil @@ -438,7 +438,8 @@ struct PairingView: View { } startPairingTask { - await connectManualHost(deviceName, trimmedHost, parsedPort) + let result = await connectManualHost(deviceName, trimmedHost, parsedPort) + onPairingResult?(result) } } From d30dd41ef4d86b8d46d11865c2545c149a64da5f Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Fri, 4 Sep 2026 19:48:04 -0700 Subject: [PATCH 26/33] fix: replace stale tailscale routes on rescan --- .../MobilePairedMacStore.swift | 48 ++++++++++++++ .../MobilePairedMacStoring.swift | 45 ++++++++++++++ .../MobilePairedMacStoreTests.swift | 50 +++++++++++++++ ...eShellComposite+PairedMacPersistence.swift | 15 +++++ .../MobileShellComposite.swift | 21 ++++--- .../TailscalePairingRegressionTests.swift | 62 +++++++++++++++++++ 6 files changed, 231 insertions(+), 10 deletions(-) diff --git a/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore.swift b/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore.swift index 67247040b900..17812b54d84a 100644 --- a/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore.swift +++ b/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore.swift @@ -753,6 +753,11 @@ public actor MobilePairedMacStore: MobilePairedMacStoring { .text(removed.kind.rawValue), .text(encoded), ]) + try revokeLegacyTailscaleGrant( + macDeviceID: macDeviceID, + ownerKey: ownerKey, + endpoint: removed.endpoint + ) try compactRouteRemovalTombstones( macDeviceID: macDeviceID, ownerKey: ownerKey @@ -795,6 +800,45 @@ public actor MobilePairedMacStore: MobilePairedMacStoring { return didWrite } + /// A route removal also revokes its device-local compatibility grant. The + /// grant stores the full route JSON, while route identity is endpoint-based + /// so a refreshed route id or metadata cannot leave an old bearer behind. + private func revokeLegacyTailscaleGrant( + macDeviceID: String, + ownerKey: String, + endpoint: CmxAttachEndpoint + ) throws { + var statement: OpaquePointer? + defer { sqlite3_finalize(statement) } + let result = sqlite3_prepare_v2( + db, + "SELECT endpoint_json FROM legacy_tailscale_route_grants WHERE mac_device_id = ? AND owner_key = ?;", + -1, + &statement, + nil + ) + guard result == SQLITE_OK else { + throw MobilePairedMacStoreError.prepareFailed(result, lastErrorMessage()) + } + try bind(statement: statement, parameters: [.text(macDeviceID), .text(ownerKey)]) + let decoder = JSONDecoder() + var encodedMatches: [String] = [] + while sqlite3_step(statement) == SQLITE_ROW { + guard let raw = Self.readNullableText(statement, column: 0), + let data = raw.data(using: .utf8), + let route = try? decoder.decode(CmxAttachRoute.self, from: data), + route.kind == .tailscale, + route.endpoint == endpoint else { continue } + encodedMatches.append(raw) + } + for encoded in encodedMatches { + try exec( + "DELETE FROM legacy_tailscale_route_grants WHERE mac_device_id = ? AND owner_key = ? AND endpoint_json = ?;", + binding: [.text(macDeviceID), .text(ownerKey), .text(encoded)] + ) + } + } + /// Persist `'user'`-origin Tailscale compatibility grants for routes the /// user entered as a pairing code. Upgrades an existing `'migration'` grant /// for the same destination to `'user'`, so a deliberate re-scan is not @@ -874,6 +918,10 @@ public actor MobilePairedMacStore: MobilePairedMacStoring { currentRoutes.append(disclosed) } } + try compactRouteRemovalTombstones( + macDeviceID: macDeviceID, + ownerKey: ownerKey + ) try exec( "DELETE FROM mac_routes WHERE mac_device_id = ? AND owner_key = ?;", binding: [.text(macDeviceID), .text(ownerKey)] diff --git a/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStoring.swift b/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStoring.swift index 92e77558e5d0..6f7872168507 100644 --- a/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStoring.swift +++ b/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStoring.swift @@ -241,6 +241,51 @@ public protocol MobilePairedMacStoring: Sendable { } extension MobilePairedMacStoring { + /// Replace the device-local Tailscale authorization set for one exact + /// pairing. The incoming QR routes are already persisted by the caller; + /// remove only older Tailscale endpoints so a replacement cannot keep + /// dialing a route that the newly scanned Mac no longer advertised. + public func replaceTailscaleRoutesIfAuthorized( + macDeviceID: String, + condition: MobilePairedMacRouteWriteCondition, + stackUserID: String?, + teamID: String?, + routes: [CmxAttachRoute] + ) async throws { + let incomingRoutes = routes.filter { $0.kind == .tailscale } + guard !incomingRoutes.isEmpty else { return } + let instanceTag: String? + switch condition { + case .matchingInstanceTag(let tag): instanceTag = tag + case .unclaimed: instanceTag = nil + } + let current = try await loadAll(stackUserID: stackUserID, teamID: teamID) + .first { + cmxCanonicalDeviceID($0.macDeviceID) == cmxCanonicalDeviceID(macDeviceID) + && CmxMacAppInstanceIdentity( + macDeviceID: $0.macDeviceID, + instanceTag: $0.instanceTag + ).id == CmxMacAppInstanceIdentity( + macDeviceID: macDeviceID, + instanceTag: instanceTag + ).id + } + guard let current else { return } + for route in current.routes where route.kind == .tailscale { + guard !incomingRoutes.contains(where: { $0.endpoint == route.endpoint }) else { + continue + } + _ = try await removeRouteIfAuthorized( + macDeviceID: macDeviceID, + route: route, + condition: condition, + stackUserID: stackUserID, + teamID: teamID, + now: Date() + ) + } + } + /// In-memory/test fallback for stores that do not persist route tombstones. /// Production SQLite and scope decorators override this requirement. @discardableResult diff --git a/Packages/iOS/CmuxMobilePairedMac/Tests/CmuxMobilePairedMacTests/MobilePairedMacStoreTests.swift b/Packages/iOS/CmuxMobilePairedMac/Tests/CmuxMobilePairedMacTests/MobilePairedMacStoreTests.swift index c1c33332d200..0d4c6a1ead49 100644 --- a/Packages/iOS/CmuxMobilePairedMac/Tests/CmuxMobilePairedMacTests/MobilePairedMacStoreTests.swift +++ b/Packages/iOS/CmuxMobilePairedMac/Tests/CmuxMobilePairedMacTests/MobilePairedMacStoreTests.swift @@ -341,6 +341,56 @@ import Testing ) } + @Test func replacingPairingRoutesRemovesStaleTailscaleGrant() async throws { + let (store, directory) = try makeStore() + defer { try? FileManager.default.removeItem(at: directory) } + let oldRoute = try tailscaleRoute(host: "100.64.0.40") + let newRoute = try tailscaleRoute(host: "100.64.0.41") + + try await store.upsert( + macDeviceID: "replace-mac", + displayName: "Replace Mac", + routes: [oldRoute], + markActive: true, + stackUserID: "user-1", + now: Date(timeIntervalSince1970: 1) + ) + try await store.authorizeUserTailscaleRoutes( + macDeviceID: "replace-mac", + instanceTag: nil, + stackUserID: "user-1", + teamID: nil, + routes: [oldRoute] + ) + try await store.upsert( + macDeviceID: "replace-mac", + displayName: "Replace Mac", + routes: [oldRoute, newRoute], + markActive: true, + stackUserID: "user-1", + now: Date(timeIntervalSince1970: 2) + ) + + try await store.replaceTailscaleRoutesIfAuthorized( + macDeviceID: "replace-mac", + condition: .unclaimed, + stackUserID: "user-1", + teamID: nil, + routes: [newRoute] + ) + try await store.authorizeUserTailscaleRoutes( + macDeviceID: "replace-mac", + instanceTag: nil, + stackUserID: "user-1", + teamID: nil, + routes: [newRoute] + ) + + let current = try #require(await store.activeMac(stackUserID: "user-1")) + #expect(current.routes == [newRoute]) + #expect(current.legacyTailscaleRoutes == [newRoute]) + } + @Test func userGrantSurvivesAuthenticatedIrohPublication() async throws { // Unlike the v8 migration capability, a grant the user minted by // entering the Mac's pairing code stays available after Iroh persists, diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+PairedMacPersistence.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+PairedMacPersistence.swift index dabfc2eb4c13..7a7754e7ce6b 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+PairedMacPersistence.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+PairedMacPersistence.swift @@ -172,6 +172,21 @@ extension MobileShellComposite { now: Date() ) } + if !userAuthorizedTailscaleRoutes.isEmpty { + // A fresh pairing code is a replacement authorization for + // this Mac. Remove old Tailscale destinations after the + // incoming ticket is persisted, so at least one route + // remains and the store can record endpoint tombstones. + let condition: MobilePairedMacRouteWriteCondition = + instanceTag.map { .matchingInstanceTag($0) } ?? .unclaimed + try await pairedMacStore.replaceTailscaleRoutesIfAuthorized( + macDeviceID: ticket.macDeviceID, + condition: condition, + stackUserID: stackUserID, + teamID: scope?.teamID, + routes: userAuthorizedTailscaleRoutes + ) + } if !userAuthorizedTailscaleRoutes.isEmpty { // The user just proved control of this Mac by entering its // pairing code; record the device-local grant so later diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift index 3b31ab64c6fb..09aebe072127 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift @@ -2650,9 +2650,11 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { } guard allowPreview else { applyPairingValidationFailure(.invalidCode) - connectionState = .disconnected - macConnectionStatus = .unavailable - clearRemoteConnectionContext() + if connectionState != .connected { + connectionState = .disconnected + macConnectionStatus = .unavailable + clearRemoteConnectionContext() + } return .failed } connectPreviewHost() @@ -9787,13 +9789,12 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { // account/session. Preserve the explicit pairing event only when this // ticket itself names the authorized Tailscale endpoint; stored and // unrelated tickets remain pinned to their Direct candidates. - let hasFreshExplicitTailscaleAuthorization = pairedMacDeviceID == nil - && ticket.routes.contains { route in - Self.userTailscalePairingAuthorization( - for: route, - authorizations: userTailscalePairingAuthorizations - ) != nil - } + let hasFreshExplicitTailscaleAuthorization = ticket.routes.contains { route in + Self.userTailscalePairingAuthorization( + for: route, + authorizations: userTailscalePairingAuthorizations + ) != nil + } let directOnlyDialCandidates = directOnlyDialCandidates ?? (resolvedMethod == .direct && !hasFreshExplicitTailscaleAuthorization diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/TailscalePairingRegressionTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/TailscalePairingRegressionTests.swift index c48ed88b4e82..245e7095abea 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/TailscalePairingRegressionTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/TailscalePairingRegressionTests.swift @@ -46,6 +46,48 @@ import Testing #expect(requests.first?.stackAccessToken == "test-stack-token") } + @Test func replacementScanCanExplicitlyAuthorizeTailscaleForDirectMac() async throws { + let router = LivenessHostRouter() + let box = TransportBox() + let factory = KindRecordingTransportFactory(router: router, box: box) + let directory = FileManager.default.temporaryDirectory + .appendingPathComponent(UUID().uuidString, isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + let pairedMacStore = try MobilePairedMacStore( + databaseURL: directory.appendingPathComponent("paired-macs.sqlite3") + ) + try await pairedMacStore.upsert( + macDeviceID: "test-mac", + displayName: "Test Mac", + routes: [try tailscaleRoute()], + instanceTag: "default", + markActive: true, + stackUserID: "phone-user", + now: Self.fixedNow + ) + let runtime = LivenessTestRuntime( + transportFactory: factory, + now: { Self.fixedNow }, + supportedRouteKinds: [.iroh, .tailscale] + ) + let store = makeStore( + runtime: runtime, + pairedMacStore: pairedMacStore, + connectionMethod: .direct + ) + store.pairingCode = currentQRCode() + + let result = await store.connectPairingInput( + allowPreview: false, + pairedMacDeviceID: "test-mac", + instanceTag: "default" + ) + + #expect(result == .connected) + #expect(store.activeRoute?.kind == .tailscale) + } + @Test func legacyTokenlessQRCodeEnteredThroughPasteUsesTheSameAuthorization() async throws { let router = LivenessHostRouter() let box = TransportBox() @@ -276,6 +318,26 @@ import Testing #expect(store.connectionError?.isEmpty == false) } + @Test func invalidScannerPayloadDoesNotClearConnectedSession() async throws { + let router = LivenessHostRouter() + let box = TransportBox() + let factory = KindRecordingTransportFactory(router: router, box: box) + let runtime = LivenessTestRuntime( + transportFactory: factory, + now: { Self.fixedNow }, + supportedRouteKinds: [.tailscale] + ) + let store = makeStore(runtime: runtime) + store.pairingCode = currentQRCode() + #expect(await store.connectPairingInput() == .connected) + let connectedRoute = store.activeRoute + + store.pairingCode = "https://example.com/not-a-cmux-pairing-code" + #expect(await store.connectPairingInput(allowPreview: false) == .failed) + #expect(store.connectionState == .connected) + #expect(store.activeRoute == connectedRoute) + } + @Test func replacementPairingRejectsDifferentMacIdentity() async throws { let router = LivenessHostRouter() let box = TransportBox() From 8498c3c1c30b63d81ea5afc77abb249ad1e1cef4 Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Fri, 4 Sep 2026 19:53:08 -0700 Subject: [PATCH 27/33] fix: retain route deletion tombstones --- .../MobilePairedMacStore+Records.swift | 25 ------------------- .../MobilePairedMacStore.swift | 9 ------- 2 files changed, 34 deletions(-) diff --git a/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore+Records.swift b/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore+Records.swift index 99668cca99fa..8b035d906c94 100644 --- a/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore+Records.swift +++ b/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore+Records.swift @@ -373,31 +373,6 @@ extension MobilePairedMacStore { return removedKeys } - /// Retain only the newest endpoint tombstones for a paired-Mac scope so - /// repeated route churn cannot make refresh cost grow without bound. - func compactRouteRemovalTombstones( - macDeviceID: String, - ownerKey: String - ) throws { - try exec(""" - DELETE FROM mac_route_removals - WHERE mac_device_id = ? AND owner_key = ? - AND id NOT IN ( - SELECT id - FROM mac_route_removals - WHERE mac_device_id = ? AND owner_key = ? - ORDER BY id DESC - LIMIT ? - ); - """, binding: [ - .text(macDeviceID), - .text(ownerKey), - .text(macDeviceID), - .text(ownerKey), - .int(Int64(MobilePairedMacStore.routeRemovalTombstoneLimit)), - ]) - } - func fetchRoutes(macDeviceID: String, ownerKey: String) throws -> [CmxAttachRoute] { let removedKeys = try fetchRouteRemovalKeys( macDeviceID: macDeviceID, diff --git a/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore.swift b/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore.swift index 17812b54d84a..25a43c839e67 100644 --- a/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore.swift +++ b/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore.swift @@ -18,7 +18,6 @@ public actor MobilePairedMacStore: MobilePairedMacStoring { /// Keep route-removal suppression bounded while retaining ample history for /// normal Tailscale endpoint churn. Explicit pairing can restore any route. - static let routeRemovalTombstoneLimit = 256 private let dbPath: String // `nonisolated(unsafe)` only so the (Swift 6 nonisolated) `deinit` can close @@ -758,10 +757,6 @@ public actor MobilePairedMacStore: MobilePairedMacStoring { ownerKey: ownerKey, endpoint: removed.endpoint ) - try compactRouteRemovalTombstones( - macDeviceID: macDeviceID, - ownerKey: ownerKey - ) try upsertMacRow( macDeviceID: macDeviceID, ownerKey: ownerKey, @@ -918,10 +913,6 @@ public actor MobilePairedMacStore: MobilePairedMacStoring { currentRoutes.append(disclosed) } } - try compactRouteRemovalTombstones( - macDeviceID: macDeviceID, - ownerKey: ownerKey - ) try exec( "DELETE FROM mac_routes WHERE mac_device_id = ? AND owner_key = ?;", binding: [.text(macDeviceID), .text(ownerKey)] From 870a251c058270f0386b18f7e460d04cf32edc53 Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Fri, 4 Sep 2026 20:06:00 -0700 Subject: [PATCH 28/33] fix: bound route suppression without resurrection --- .../MobilePairedMacStore+Records.swift | 58 ++++++++++- .../MobilePairedMacStore.swift | 96 +++++++++++++++++-- .../MobilePairedMacStoring.swift | 45 --------- .../MobilePairedMacStoreTests.swift | 76 ++++++++++++--- ...eShellComposite+PairedMacPersistence.swift | 15 --- 5 files changed, 211 insertions(+), 79 deletions(-) diff --git a/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore+Records.swift b/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore+Records.swift index 8b035d906c94..39bd4484d01e 100644 --- a/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore+Records.swift +++ b/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore+Records.swift @@ -373,6 +373,59 @@ extension MobilePairedMacStore { return removedKeys } + /// Bound tombstone storage without evicting suppression state. Once a + /// scope exceeds the exact-marker budget for a transport kind, replace its + /// markers with one conservative kind-wide marker. Explicit pairing clears + /// that marker for the newly authorized destination set. + func compactRouteRemovalTombstones( + macDeviceID: String, + ownerKey: String, + kind: CmxAttachTransportKind + ) throws { + var statement: OpaquePointer? + defer { sqlite3_finalize(statement) } + let rc = sqlite3_prepare_v2( + db, + "SELECT COUNT(*) FROM mac_route_removals WHERE mac_device_id = ? AND owner_key = ? AND kind = ? AND endpoint_json <> ?;", + -1, + &statement, + nil + ) + guard rc == SQLITE_OK else { + throw MobilePairedMacStoreError.prepareFailed(rc, lastErrorMessage()) + } + try bind(statement: statement, parameters: [ + .text(macDeviceID), + .text(ownerKey), + .text(kind.rawValue), + .text(MobilePairedMacStore.routeRemovalWildcardEndpoint), + ]) + guard sqlite3_step(statement) == SQLITE_ROW, + sqlite3_column_int(statement, 0) > MobilePairedMacStore.routeRemovalTombstoneLimit else { + return + } + try exec(""" + INSERT OR IGNORE INTO mac_route_removals ( + mac_device_id, owner_key, kind, endpoint_json + ) VALUES (?, ?, ?, ?); + """, binding: [ + .text(macDeviceID), + .text(ownerKey), + .text(kind.rawValue), + .text(MobilePairedMacStore.routeRemovalWildcardEndpoint), + ]) + try exec(""" + DELETE FROM mac_route_removals + WHERE mac_device_id = ? AND owner_key = ? AND kind = ? + AND endpoint_json <> ?; + """, binding: [ + .text(macDeviceID), + .text(ownerKey), + .text(kind.rawValue), + .text(MobilePairedMacStore.routeRemovalWildcardEndpoint), + ]) + } + func fetchRoutes(macDeviceID: String, ownerKey: String) throws -> [CmxAttachRoute] { let removedKeys = try fetchRouteRemovalKeys( macDeviceID: macDeviceID, @@ -404,7 +457,10 @@ extension MobilePairedMacStore { continue } if let endpoint = try? Self.encodeRouteEndpoint(route), - removedKeys.contains("\(route.kind.rawValue)\u{1F}\(endpoint)") { + (removedKeys.contains("\(route.kind.rawValue)\u{1F}\(endpoint)") + || removedKeys.contains( + "\(route.kind.rawValue)\u{1F}\(MobilePairedMacStore.routeRemovalWildcardEndpoint)" + )) { continue } routes.append(route) diff --git a/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore.swift b/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore.swift index 25a43c839e67..5dc5d344dbdf 100644 --- a/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore.swift +++ b/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore.swift @@ -16,8 +16,10 @@ public actor MobilePairedMacStore: MobilePairedMacStoring { /// The schema version this build creates and migrates to. public static let currentSchemaVersion: Int32 = 12 - /// Keep route-removal suppression bounded while retaining ample history for - /// normal Tailscale endpoint churn. Explicit pairing can restore any route. + /// Keep route-removal suppression bounded. Once a scope churns beyond this + /// limit, it parks a conservative kind-wide marker until explicit pairing. + static let routeRemovalTombstoneLimit = 256 + static let routeRemovalWildcardEndpoint = "*" private let dbPath: String // `nonisolated(unsafe)` only so the (Swift 6 nonisolated) `deinit` can close @@ -735,7 +737,35 @@ public actor MobilePairedMacStore: MobilePairedMacStoring { // so accepting an id-only match could delete the wrong route. guard let removedIndex = currentRoutes.firstIndex(where: { $0.kind == route.kind && $0.endpoint == route.endpoint - }) else { return } + }) else { + // A compatibility grant can outlive the route snapshot after + // a refresh. Revoke that stale bearer and park its endpoint + // even though there is no route row left to rewrite. + guard route.kind == .tailscale, + try revokeLegacyTailscaleGrant( + macDeviceID: macDeviceID, + ownerKey: ownerKey, + endpoint: route.endpoint + ) else { return } + let encoded = try Self.encodeRouteEndpoint(route) + try exec(""" + INSERT OR IGNORE INTO mac_route_removals ( + mac_device_id, owner_key, kind, endpoint_json + ) VALUES (?, ?, ?, ?); + """, binding: [ + .text(macDeviceID), + .text(ownerKey), + .text(route.kind.rawValue), + .text(encoded), + ]) + try compactRouteRemovalTombstones( + macDeviceID: macDeviceID, + ownerKey: ownerKey, + kind: route.kind + ) + didWrite = true + return + } let removed = currentRoutes[removedIndex] var remaining = currentRoutes remaining.remove(at: removedIndex) @@ -752,7 +782,12 @@ public actor MobilePairedMacStore: MobilePairedMacStoring { .text(removed.kind.rawValue), .text(encoded), ]) - try revokeLegacyTailscaleGrant( + try compactRouteRemovalTombstones( + macDeviceID: macDeviceID, + ownerKey: ownerKey, + kind: removed.kind + ) + _ = try revokeLegacyTailscaleGrant( macDeviceID: macDeviceID, ownerKey: ownerKey, endpoint: removed.endpoint @@ -802,7 +837,7 @@ public actor MobilePairedMacStore: MobilePairedMacStoring { macDeviceID: String, ownerKey: String, endpoint: CmxAttachEndpoint - ) throws { + ) throws -> Bool { var statement: OpaquePointer? defer { sqlite3_finalize(statement) } let result = sqlite3_prepare_v2( @@ -832,6 +867,7 @@ public actor MobilePairedMacStore: MobilePairedMacStoring { binding: [.text(macDeviceID), .text(ownerKey), .text(encoded)] ) } + return !encodedMatches.isEmpty } /// Persist `'user'`-origin Tailscale compatibility grants for routes the @@ -871,9 +907,22 @@ public actor MobilePairedMacStore: MobilePairedMacStoring { macDeviceID: macDeviceID, ownerKey: ownerKey ) + // A fresh pairing code replaces the previously authorized + // Tailscale destination set. Capture all older grants before + // inserting the incoming routes, including migration grants whose + // route snapshot may already have been refreshed away. + let previousGrantedRoutes = try fetchLegacyTailscaleRoutes( + macDeviceID: macDeviceID, + ownerKey: ownerKey + ) for route in grantRoutes { let encoded = try Self.encodeRoute(route) let encodedEndpoint = try Self.encodeRouteEndpoint(route) + _ = try revokeLegacyTailscaleGrant( + macDeviceID: macDeviceID, + ownerKey: ownerKey, + endpoint: route.endpoint + ) try exec(""" INSERT INTO legacy_tailscale_route_grants ( mac_device_id, owner_key, endpoint_json, origin @@ -895,12 +944,13 @@ public actor MobilePairedMacStore: MobilePairedMacStoring { WHERE mac_device_id = ? AND owner_key = ? AND kind = ? - AND endpoint_json = ?; + AND endpoint_json IN (?, ?); """, binding: [ .text(macDeviceID), .text(ownerKey), .text(route.kind.rawValue), .text(encodedEndpoint), + .text(Self.routeRemovalWildcardEndpoint), ]) // The preceding passive refresh intentionally filtered this // endpoint because its tombstone was still present. Reinsert @@ -913,6 +963,40 @@ public actor MobilePairedMacStore: MobilePairedMacStoring { currentRoutes.append(disclosed) } } + for staleRoute in previousGrantedRoutes where !grantRoutes.contains(where: { + $0.endpoint == staleRoute.endpoint + }) { + if let removedIndex = currentRoutes.firstIndex(where: { + $0.kind == .tailscale && $0.endpoint == staleRoute.endpoint + }) { + var remaining = currentRoutes + remaining.remove(at: removedIndex) + if !remaining.isEmpty { + currentRoutes = remaining + } + } + let encodedEndpoint = try Self.encodeRouteEndpoint(staleRoute) + try exec(""" + INSERT OR IGNORE INTO mac_route_removals ( + mac_device_id, owner_key, kind, endpoint_json + ) VALUES (?, ?, ?, ?); + """, binding: [ + .text(macDeviceID), + .text(ownerKey), + .text(staleRoute.kind.rawValue), + .text(encodedEndpoint), + ]) + try compactRouteRemovalTombstones( + macDeviceID: macDeviceID, + ownerKey: ownerKey, + kind: staleRoute.kind + ) + _ = try revokeLegacyTailscaleGrant( + macDeviceID: macDeviceID, + ownerKey: ownerKey, + endpoint: staleRoute.endpoint + ) + } try exec( "DELETE FROM mac_routes WHERE mac_device_id = ? AND owner_key = ?;", binding: [.text(macDeviceID), .text(ownerKey)] diff --git a/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStoring.swift b/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStoring.swift index 6f7872168507..92e77558e5d0 100644 --- a/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStoring.swift +++ b/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStoring.swift @@ -241,51 +241,6 @@ public protocol MobilePairedMacStoring: Sendable { } extension MobilePairedMacStoring { - /// Replace the device-local Tailscale authorization set for one exact - /// pairing. The incoming QR routes are already persisted by the caller; - /// remove only older Tailscale endpoints so a replacement cannot keep - /// dialing a route that the newly scanned Mac no longer advertised. - public func replaceTailscaleRoutesIfAuthorized( - macDeviceID: String, - condition: MobilePairedMacRouteWriteCondition, - stackUserID: String?, - teamID: String?, - routes: [CmxAttachRoute] - ) async throws { - let incomingRoutes = routes.filter { $0.kind == .tailscale } - guard !incomingRoutes.isEmpty else { return } - let instanceTag: String? - switch condition { - case .matchingInstanceTag(let tag): instanceTag = tag - case .unclaimed: instanceTag = nil - } - let current = try await loadAll(stackUserID: stackUserID, teamID: teamID) - .first { - cmxCanonicalDeviceID($0.macDeviceID) == cmxCanonicalDeviceID(macDeviceID) - && CmxMacAppInstanceIdentity( - macDeviceID: $0.macDeviceID, - instanceTag: $0.instanceTag - ).id == CmxMacAppInstanceIdentity( - macDeviceID: macDeviceID, - instanceTag: instanceTag - ).id - } - guard let current else { return } - for route in current.routes where route.kind == .tailscale { - guard !incomingRoutes.contains(where: { $0.endpoint == route.endpoint }) else { - continue - } - _ = try await removeRouteIfAuthorized( - macDeviceID: macDeviceID, - route: route, - condition: condition, - stackUserID: stackUserID, - teamID: teamID, - now: Date() - ) - } - } - /// In-memory/test fallback for stores that do not persist route tombstones. /// Production SQLite and scope decorators override this requirement. @discardableResult diff --git a/Packages/iOS/CmuxMobilePairedMac/Tests/CmuxMobilePairedMacTests/MobilePairedMacStoreTests.swift b/Packages/iOS/CmuxMobilePairedMac/Tests/CmuxMobilePairedMacTests/MobilePairedMacStoreTests.swift index 0d4c6a1ead49..ad12100bd829 100644 --- a/Packages/iOS/CmuxMobilePairedMac/Tests/CmuxMobilePairedMacTests/MobilePairedMacStoreTests.swift +++ b/Packages/iOS/CmuxMobilePairedMac/Tests/CmuxMobilePairedMacTests/MobilePairedMacStoreTests.swift @@ -346,6 +346,7 @@ import Testing defer { try? FileManager.default.removeItem(at: directory) } let oldRoute = try tailscaleRoute(host: "100.64.0.40") let newRoute = try tailscaleRoute(host: "100.64.0.41") + let iroh = try irohRoute() try await store.upsert( macDeviceID: "replace-mac", @@ -362,22 +363,19 @@ import Testing teamID: nil, routes: [oldRoute] ) - try await store.upsert( + // A host refresh can replace the route snapshot while a legacy grant + // remains. The replacement authorization must revoke that stale grant + // even though the old endpoint is no longer in currentRoutes. + #expect(try await store.upsertRoutesIfAuthorized( macDeviceID: "replace-mac", displayName: "Replace Mac", - routes: [oldRoute, newRoute], - markActive: true, - stackUserID: "user-1", - now: Date(timeIntervalSince1970: 2) - ) - - try await store.replaceTailscaleRoutesIfAuthorized( - macDeviceID: "replace-mac", + routes: [iroh, newRoute], condition: .unclaimed, + markActive: true, stackUserID: "user-1", teamID: nil, - routes: [newRoute] - ) + now: Date(timeIntervalSince1970: 2) + )) try await store.authorizeUserTailscaleRoutes( macDeviceID: "replace-mac", instanceTag: nil, @@ -387,10 +385,64 @@ import Testing ) let current = try #require(await store.activeMac(stackUserID: "user-1")) - #expect(current.routes == [newRoute]) + #expect(current.routes == [iroh, newRoute]) #expect(current.legacyTailscaleRoutes == [newRoute]) } + @Test func routeRemovalCompactionUsesConservativeKindMarker() async throws { + let (store, directory) = try makeStore() + defer { try? FileManager.default.removeItem(at: directory) } + let iroh = try irohRoute() + let tailscaleRoutes = try (0..<257).map { index in + try CmxAttachRoute( + id: "tailscale-(index)", + kind: .tailscale, + endpoint: .hostPort(host: "100.65.0.((index / 250) + 1)", port: 58_465 - index) + ) + } + try await store.upsert( + macDeviceID: "churn-mac", + displayName: "Churn Mac", + routes: [iroh] + tailscaleRoutes, + markActive: true, + stackUserID: "user-1", + now: Date(timeIntervalSince1970: 1) + ) + for route in tailscaleRoutes { + let removed = try await store.removeRouteIfAuthorized( + macDeviceID: "churn-mac", + route: route, + condition: .unclaimed, + stackUserID: "user-1", + teamID: nil, + now: Date(timeIntervalSince1970: 2) + ) + if !removed { break } + } + + try await store.upsert( + macDeviceID: "churn-mac", + displayName: "Churn Mac", + routes: [iroh] + tailscaleRoutes, + markActive: true, + stackUserID: "user-1", + now: Date(timeIntervalSince1970: 3) + ) + let suppressed = try #require(await store.activeMac(stackUserID: "user-1")) + #expect(suppressed.routes == [iroh]) + + try await store.authorizeUserTailscaleRoutes( + macDeviceID: "churn-mac", + instanceTag: nil, + stackUserID: "user-1", + teamID: nil, + routes: [tailscaleRoutes[0]] + ) + let restored = try #require(await store.activeMac(stackUserID: "user-1")) + #expect(restored.routes.contains(iroh)) + #expect(restored.routes.contains(tailscaleRoutes[0])) + } + @Test func userGrantSurvivesAuthenticatedIrohPublication() async throws { // Unlike the v8 migration capability, a grant the user minted by // entering the Mac's pairing code stays available after Iroh persists, diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+PairedMacPersistence.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+PairedMacPersistence.swift index 7a7754e7ce6b..dabfc2eb4c13 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+PairedMacPersistence.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+PairedMacPersistence.swift @@ -172,21 +172,6 @@ extension MobileShellComposite { now: Date() ) } - if !userAuthorizedTailscaleRoutes.isEmpty { - // A fresh pairing code is a replacement authorization for - // this Mac. Remove old Tailscale destinations after the - // incoming ticket is persisted, so at least one route - // remains and the store can record endpoint tombstones. - let condition: MobilePairedMacRouteWriteCondition = - instanceTag.map { .matchingInstanceTag($0) } ?? .unclaimed - try await pairedMacStore.replaceTailscaleRoutesIfAuthorized( - macDeviceID: ticket.macDeviceID, - condition: condition, - stackUserID: stackUserID, - teamID: scope?.teamID, - routes: userAuthorizedTailscaleRoutes - ) - } if !userAuthorizedTailscaleRoutes.isEmpty { // The user just proved control of this Mac by entering its // pairing code; record the device-local grant so later From 7c807530873dbfe56d780b6be053e34687fae455 Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Fri, 4 Sep 2026 20:11:30 -0700 Subject: [PATCH 29/33] fix: preserve wildcard route suppression --- .../MobilePairedMacStore+Records.swift | 22 ++++++++++++++----- .../MobilePairedMacStore.swift | 3 +-- .../MobilePairedMacStoreTests.swift | 11 ++++++++++ 3 files changed, 29 insertions(+), 7 deletions(-) diff --git a/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore+Records.swift b/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore+Records.swift index 39bd4484d01e..0fe705af1d43 100644 --- a/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore+Records.swift +++ b/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore+Records.swift @@ -431,6 +431,15 @@ extension MobilePairedMacStore { macDeviceID: macDeviceID, ownerKey: ownerKey ) + let explicitlyGrantedKeys = Set( + try fetchLegacyTailscaleRoutes( + macDeviceID: macDeviceID, + ownerKey: ownerKey + ).compactMap { route in + guard let endpoint = try? Self.encodeRouteEndpoint(route) else { return nil } + return "\(route.kind.rawValue)\u{1F}\(endpoint)" + } + ) var statement: OpaquePointer? defer { sqlite3_finalize(statement) } @@ -456,12 +465,15 @@ extension MobilePairedMacStore { pairedMacStoreLog.warning("dropping unparsable route row") continue } - if let endpoint = try? Self.encodeRouteEndpoint(route), - (removedKeys.contains("\(route.kind.rawValue)\u{1F}\(endpoint)") - || removedKeys.contains( + if let endpoint = try? Self.encodeRouteEndpoint(route) { + let key = "\(route.kind.rawValue)\u{1F}\(endpoint)" + let wildcardKey = "\(route.kind.rawValue)\u{1F}\(MobilePairedMacStore.routeRemovalWildcardEndpoint)" - )) { - continue + if removedKeys.contains(key) + || (removedKeys.contains(wildcardKey) + && !explicitlyGrantedKeys.contains(key)) { + continue + } } routes.append(route) } diff --git a/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore.swift b/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore.swift index 5dc5d344dbdf..05f012d53e4c 100644 --- a/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore.swift +++ b/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore.swift @@ -944,13 +944,12 @@ public actor MobilePairedMacStore: MobilePairedMacStoring { WHERE mac_device_id = ? AND owner_key = ? AND kind = ? - AND endpoint_json IN (?, ?); + AND endpoint_json = ?; """, binding: [ .text(macDeviceID), .text(ownerKey), .text(route.kind.rawValue), .text(encodedEndpoint), - .text(Self.routeRemovalWildcardEndpoint), ]) // The preceding passive refresh intentionally filtered this // endpoint because its tombstone was still present. Reinsert diff --git a/Packages/iOS/CmuxMobilePairedMac/Tests/CmuxMobilePairedMacTests/MobilePairedMacStoreTests.swift b/Packages/iOS/CmuxMobilePairedMac/Tests/CmuxMobilePairedMacTests/MobilePairedMacStoreTests.swift index ad12100bd829..5e401ca0e6bc 100644 --- a/Packages/iOS/CmuxMobilePairedMac/Tests/CmuxMobilePairedMacTests/MobilePairedMacStoreTests.swift +++ b/Packages/iOS/CmuxMobilePairedMac/Tests/CmuxMobilePairedMacTests/MobilePairedMacStoreTests.swift @@ -441,6 +441,17 @@ import Testing let restored = try #require(await store.activeMac(stackUserID: "user-1")) #expect(restored.routes.contains(iroh)) #expect(restored.routes.contains(tailscaleRoutes[0])) + + try await store.upsert( + macDeviceID: "churn-mac", + displayName: "Churn Mac", + routes: [iroh] + tailscaleRoutes, + markActive: true, + stackUserID: "user-1", + now: Date(timeIntervalSince1970: 4) + ) + let refreshed = try #require(await store.activeMac(stackUserID: "user-1")) + #expect(refreshed.routes == [iroh, tailscaleRoutes[0]]) } @Test func userGrantSurvivesAuthenticatedIrohPublication() async throws { From 3e1d24ba9772302e30648261f5241e015178bdae Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Fri, 4 Sep 2026 20:43:06 -0700 Subject: [PATCH 30/33] fix: honor wildcard route suppression during refresh --- .../MobilePairedMacStore.swift | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore.swift b/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore.swift index 05f012d53e4c..55ea9a23e380 100644 --- a/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore.swift +++ b/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore.swift @@ -1175,6 +1175,15 @@ public actor MobilePairedMacStore: MobilePairedMacStoring { ownerKey: ownerKey, origin: "user" ) + let explicitlyGrantedRouteKeys = Set( + try fetchLegacyTailscaleRoutes( + macDeviceID: macDeviceID, + ownerKey: ownerKey + ).compactMap { route in + guard let endpoint = try? Self.encodeRouteEndpoint(route) else { return nil } + return "\(route.kind.rawValue)\u{1F}\(endpoint)" + } + ) // A presence or backup refresh can publish only Iroh and Debug // routes after the user explicitly paired over Tailscale. Keep the // exact user-authorized endpoint in the visible route set while it @@ -1197,7 +1206,11 @@ public actor MobilePairedMacStore: MobilePairedMacStoring { for route in routes { let endpoint = try Self.encodeRouteEndpoint(route) let key = "\(route.kind.rawValue)\u{1F}\(endpoint)" - guard !removedRouteKeys.contains(key) else { continue } + let wildcardKey = + "\(route.kind.rawValue)\u{1F}\(Self.routeRemovalWildcardEndpoint)" + guard !removedRouteKeys.contains(key), + !(removedRouteKeys.contains(wildcardKey) + && !explicitlyGrantedRouteKeys.contains(key)) else { continue } routesToPersist.append(route) } if !pinnedIrohRoutes.isEmpty, !incomingHasIroh { From 904dba33f14fc1a82cb8b65894e81805397ef40d Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Fri, 4 Sep 2026 20:48:20 -0700 Subject: [PATCH 31/33] fix: align tombstone limit with sqlite count --- .../Sources/CmuxMobilePairedMac/MobilePairedMacStore.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore.swift b/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore.swift index 55ea9a23e380..89a5f587e063 100644 --- a/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore.swift +++ b/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore.swift @@ -18,7 +18,7 @@ public actor MobilePairedMacStore: MobilePairedMacStoring { /// Keep route-removal suppression bounded. Once a scope churns beyond this /// limit, it parks a conservative kind-wide marker until explicit pairing. - static let routeRemovalTombstoneLimit = 256 + static let routeRemovalTombstoneLimit: Int32 = 256 static let routeRemovalWildcardEndpoint = "*" private let dbPath: String From 0888b94c81adbedcb461c5643a97c56d01650bdc Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Fri, 4 Sep 2026 21:00:21 -0700 Subject: [PATCH 32/33] fix: report superseded preview pairing --- .../CmuxMobileShell/MobileShellComposite.swift | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift index aecf19da7bb2..b8cd9bb54b81 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift @@ -2619,12 +2619,17 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { } public func connectPreviewHost() { + _ = startPreviewHostConnection() + } + + @discardableResult + private func startPreviewHostConnection() -> Bool { let trimmedCode = pairingCode.trimmingCharacters(in: .whitespacesAndNewlines) guard !trimmedCode.isEmpty else { - return + return false } if CmxPairingURLScheme(urlString: trimmedCode) != nil { - return + return false } let attemptID = beginPairingAttempt() replaceRemoteClient(with: nil) @@ -2632,13 +2637,14 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { activeTicket = nil activeRoute = nil connectedHostName = PreviewMobileHost.hostName - guard isCurrentPairingAttempt(attemptID) else { return } + guard isCurrentPairingAttempt(attemptID) else { return false } connectionState = .connected markMacConnectionHealthy() if selectedWorkspaceID == nil { selectedWorkspaceID = workspaces.first?.id } syncSelectedTerminalForWorkspace() + return true } /// Connect using the current pairing input, accepting either a code or pairing URL. @@ -2671,8 +2677,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { } return .failed } - connectPreviewHost() - return .connected + return startPreviewHostConnection() ? .connected : .superseded } /// Connect to a manually-entered Mac host and optionally associate the From 113de2d7cd6af26f20c83e23561db24c395fb961 Mon Sep 17 00:00:00 2001 From: Abdulaziz Albahar <67667005+azooz2003-bit@users.noreply.github.com> Date: Fri, 4 Sep 2026 21:09:49 -0700 Subject: [PATCH 33/33] test: vary route compaction fixture endpoints --- .../CmuxMobilePairedMacTests/MobilePairedMacStoreTests.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Packages/iOS/CmuxMobilePairedMac/Tests/CmuxMobilePairedMacTests/MobilePairedMacStoreTests.swift b/Packages/iOS/CmuxMobilePairedMac/Tests/CmuxMobilePairedMacTests/MobilePairedMacStoreTests.swift index 5e401ca0e6bc..604d467c1b74 100644 --- a/Packages/iOS/CmuxMobilePairedMac/Tests/CmuxMobilePairedMacTests/MobilePairedMacStoreTests.swift +++ b/Packages/iOS/CmuxMobilePairedMac/Tests/CmuxMobilePairedMacTests/MobilePairedMacStoreTests.swift @@ -395,9 +395,9 @@ import Testing let iroh = try irohRoute() let tailscaleRoutes = try (0..<257).map { index in try CmxAttachRoute( - id: "tailscale-(index)", + id: "tailscale-\(index)", kind: .tailscale, - endpoint: .hostPort(host: "100.65.0.((index / 250) + 1)", port: 58_465 - index) + endpoint: .hostPort(host: "100.65.0.\((index / 250) + 1)", port: 58_465 - index) ) } try await store.upsert(