diff --git a/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore+Records.swift b/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore+Records.swift index 4b32d5ddc3fa..0fe705af1d43 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 = ?; @@ -282,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, @@ -301,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 { @@ -316,7 +331,116 @@ extension MobilePairedMacStore { return routes } + func fetchRouteRemovalKeys( + macDeviceID: String, + ownerKey: String + ) throws -> Set { + 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 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 + } + removedKeys.insert("\(kind)\u{1F}\(endpoint)") + } + 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, + 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) } let sql = """ @@ -341,6 +465,16 @@ extension MobilePairedMacStore { pairedMacStoreLog.warning("dropping unparsable route row") continue } + if let endpoint = try? Self.encodeRouteEndpoint(route) { + let key = "\(route.kind.rawValue)\u{1F}\(endpoint)" + let wildcardKey = + "\(route.kind.rawValue)\u{1F}\(MobilePairedMacStore.routeRemovalWildcardEndpoint)" + if removedKeys.contains(key) + || (removedKeys.contains(wildcardKey) + && !explicitlyGrantedKeys.contains(key)) { + continue + } + } routes.append(route) } return routes @@ -393,6 +527,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..89a5f587e063 100644 --- a/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore.swift +++ b/Packages/iOS/CmuxMobilePairedMac/Sources/CmuxMobilePairedMac/MobilePairedMacStore.swift @@ -14,7 +14,12 @@ 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 + + /// 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: Int32 = 256 + static let routeRemovalWildcardEndpoint = "*" private let dbPath: String // `nonisolated(unsafe)` only so the (Swift 6 nonisolated) `deinit` can close @@ -232,6 +237,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 +548,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 +680,196 @@ 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 + ) + // 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 removedIndex = currentRoutes.firstIndex(where: { + $0.kind == route.kind && $0.endpoint == route.endpoint + }) 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) + 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 compactRouteRemovalTombstones( + macDeviceID: macDeviceID, + ownerKey: ownerKey, + kind: removed.kind + ) + _ = try revokeLegacyTailscaleGrant( + macDeviceID: macDeviceID, + ownerKey: ownerKey, + endpoint: removed.endpoint + ) + 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 + } + + /// 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 -> Bool { + 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)] + ) + } + return !encodedMatches.isEmpty + } + /// 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 @@ -677,8 +903,26 @@ public actor MobilePairedMacStore: MobilePairedMacStoring { // unknown row would strand an unowned bearer capability. return } + var currentRoutes = try fetchRoutes( + 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 @@ -691,6 +935,84 @@ 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), + ]) + // 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) + } + } + 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)] + ) + 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)), + ]) } } } @@ -842,16 +1164,65 @@ 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( + macDeviceID: macDeviceID, + 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 + // 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: [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)" + 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 { + 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 @@ -1135,6 +1506,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..92e77558e5d0 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,52 @@ 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 } + guard let removedIndex = current.routes.firstIndex(where: { + $0.kind == route.kind && $0.endpoint == route.endpoint + }) else { return false } + 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, + 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/CmuxMobilePairedMac/Tests/CmuxMobilePairedMacTests/MobilePairedMacRouteAuthorityTests.swift b/Packages/iOS/CmuxMobilePairedMac/Tests/CmuxMobilePairedMacTests/MobilePairedMacRouteAuthorityTests.swift index 349d4bae4d17..384cd520339f 100644 --- a/Packages/iOS/CmuxMobilePairedMac/Tests/CmuxMobilePairedMacTests/MobilePairedMacRouteAuthorityTests.swift +++ b/Packages/iOS/CmuxMobilePairedMac/Tests/CmuxMobilePairedMacTests/MobilePairedMacRouteAuthorityTests.swift @@ -133,6 +133,100 @@ 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. + 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: 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"]) + } + + @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/CmuxMobilePairedMac/Tests/CmuxMobilePairedMacTests/MobilePairedMacStoreTests.swift b/Packages/iOS/CmuxMobilePairedMac/Tests/CmuxMobilePairedMacTests/MobilePairedMacStoreTests.swift index 0c447556f3ce..604d467c1b74 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) } @@ -278,6 +341,119 @@ 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") + let iroh = try irohRoute() + + 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] + ) + // 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: [iroh, newRoute], + condition: .unclaimed, + markActive: true, + stackUserID: "user-1", + teamID: nil, + now: Date(timeIntervalSince1970: 2) + )) + 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 == [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])) + + 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 { // Unlike the v8 migration capability, a grant the user minted by // entering the Mac's pairing code stays available after Iroh persists, @@ -316,6 +492,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) } @@ -776,6 +1010,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) } diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/BackingUpPairedMacStore+AuthorizedRoutes.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/BackingUpPairedMacStore+AuthorizedRoutes.swift index bfb87589f4f2..9304ff8b0a05 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/BackingUpPairedMacStore+AuthorizedRoutes.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/BackingUpPairedMacStore+AuthorizedRoutes.swift @@ -3,6 +3,63 @@ 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 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: 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: verifiedDestination ?? visible?.teamID, + includesCustomizations: false, + instanceAuthority: .compareAndSet, + resolvesNilTeam: false + ) + return true + } + @discardableResult public func upsertRoutesIfAuthorized( macDeviceID: String, 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) 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+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+ReconnectRoutes.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ReconnectRoutes.swift index 3289f75a2a64..a69933d7111c 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ReconnectRoutes.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+ReconnectRoutes.swift @@ -271,7 +271,10 @@ 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] diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+RouteRemoval.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+RouteRemoval.swift index 5b883c8fd2dc..d792da19c277 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+RouteRemoval.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+RouteRemoval.swift @@ -4,6 +4,88 @@ import Foundation @MainActor extension MobileShellComposite { + /// 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.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 + ) 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 { + routeMatchesForRemoval(removedRoute, $0) + } == true || focused.map { + routeMatchesForRemoval(removedRoute, $0.route) + } == true) + + 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 + // after this route is deleted. + if let focused { + removeControlCapability(ifMatching: focused) + removeFocusedConnection(ifMatching: focused) + } + disconnectLiveConnection(preservingOtherMacWorkspaceState: true) + await foregroundClient?.disconnectAndWaitForTransportDrain() + return + } + + if let focused, + routeMatchesForRemoval(removedRoute, focused.route) { + removeFocusedConnection(ifMatching: focused) + focused.client.retire() + await focused.client.disconnectAndWaitForTransportDrain() + 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 @@ -20,8 +102,12 @@ 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 removedRouteIndex = mac.routes.firstIndex(where: { + routeMatchesForRemoval(route, $0) + }) else { return false } + let removedRoute = mac.routes[removedRouteIndex] + var routes = mac.routes + routes.remove(at: removedRouteIndex) do { if routes.isEmpty { guard deleteComputerIfLastRoute else { return false } @@ -32,12 +118,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: removedRoute, condition: .matchingInstanceTag(mac.instanceTag), - markActive: nil, stackUserID: mac.stackUserID ?? scope.userID, teamID: mac.teamID, now: Date() @@ -45,6 +129,13 @@ extension MobileShellComposite { guard wrote else { return false } } guard await isScopeCurrent(scope) else { return false } + await disconnectLiveRouteIfNeeded( + removedRoute, + ownerKey: MacPairingKey( + macDeviceID: mac.macDeviceID, + instanceTag: mac.instanceTag + ) + ) await loadPairedMacs() await loadRegistryDevices() return true diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift index 0b39f2967367..8c0ddc192d06 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift @@ -2620,12 +2620,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) @@ -2633,28 +2638,47 @@ 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. - public func connectPairingInput() async { + 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 + 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, + acceptedVersionWarning: false, + userEnteredPairingCode: true, + pairedMacDeviceID: pairedMacDeviceID, + instanceTagExpectation: Self.pairingInstanceTagExpectation(instanceTag) + ) + } + guard allowPreview else { + applyPairingValidationFailure(.invalidCode) + if connectionState != .connected { + connectionState = .disconnected + macConnectionStatus = .unavailable + clearRemoteConnectionContext() + } + return .failed } - connectPreviewHost() + return startPreviewHostConnection() ? .connected : .superseded } /// Connect to a manually-entered Mac host and optionally associate the @@ -2665,11 +2689,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 ) } @@ -2682,7 +2725,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 { @@ -2700,7 +2743,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 { @@ -2718,7 +2761,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { "failure_phase": .string("validation"), "is_first_pair": .bool(!hasKnownPairedMac), ]) - return + return .failed } guard let directRoute = try? Self.manualHostRoute( @@ -2743,7 +2786,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { "failure_phase": .string("validation"), "is_first_pair": .bool(!hasKnownPairedMac), ]) - return + return .failed } let isLoopbackRoute = MobileShellRouteAuthPolicy.routeIsLoopback(directRoute) @@ -2769,7 +2812,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 @@ -2799,7 +2842,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { "failure_phase": .string("validation"), "is_first_pair": .bool(!hasKnownPairedMac), ]) - return + return .failed } } else { userTailscalePairingAuthorization = nil @@ -2838,7 +2881,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { phase: "preflight", routes: manualRoutes ) == .proceed else { - return + return .superseded } } do { @@ -2851,10 +2894,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( @@ -2868,45 +2911,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 } } @@ -4829,6 +4876,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 @@ -4855,7 +4909,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)" @@ -5000,7 +5056,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 { @@ -5114,7 +5172,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 @@ -5124,7 +5185,9 @@ public final class MobileShellComposite: MobileTerminalOutputSinking { return await connectPairingURLResult( rawURL, acceptedVersionWarning: true, - userEnteredPairingCode: wasUserEntered + userEnteredPairingCode: wasUserEntered, + pairedMacDeviceID: pairedMacDeviceID, + instanceTagExpectation: Self.pairingInstanceTagExpectation(instanceTag) ) } @@ -9797,13 +9860,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 @@ -10646,6 +10708,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): 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/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellCompositeRouteRemovalTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellCompositeRouteRemovalTests.swift new file mode 100644 index 000000000000..b5a5d386ceef --- /dev/null +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/MobileShellCompositeRouteRemovalTests.swift @@ -0,0 +1,192 @@ +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-active", + 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 + ) + + 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) + 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) + } +} diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/TailscalePairingRegressionTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/TailscalePairingRegressionTests.swift index 0b26e5559045..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() @@ -120,6 +162,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() @@ -182,6 +299,65 @@ 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 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() + 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 6d4c3024a1c2..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() @@ -604,9 +604,10 @@ struct CMUXMobileRootView: View { if result == .connected { dismissAddDeviceSheet() } + 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 e0f34225cc74..a32bc0f43c62 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 = "" @@ -282,17 +285,39 @@ 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() }, + 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 } + cancel: { showsAddTailscaleConnection = false }, + onPairingResult: { result in + if result == .connected { + showsAddTailscaleConnection = false + } + } ) } .onChange(of: computerHasUsableTailscaleAuthorization) { _, authorized in @@ -555,7 +580,7 @@ struct MacComputerDetailView: View { } .accessibilityIdentifier("MobileComputerTailscaleUnauthorizedWarning") Button { - showsAddTailscaleConnection = true + presentTailscalePairing(.tailscaleSetup) } label: { Label( L10n.string( @@ -1126,6 +1151,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: { @@ -1200,6 +1239,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..4292753b0a16 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 connectManualHost: (String, String, Int) async -> Void + let connectPairingCode: () async -> MobilePairingURLConnectionResult + let acceptVersionWarning: () async -> MobilePairingURLConnectionResult + let connectManualHost: (String, String, Int) async -> MobilePairingURLConnectionResult 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, - connectManualHost: @escaping (String, String, Int) async -> Void, + connectPairingCode: @escaping () async -> MobilePairingURLConnectionResult, + acceptVersionWarning: @escaping () async -> MobilePairingURLConnectionResult, + connectManualHost: @escaping (String, String, Int) async -> MobilePairingURLConnectionResult, 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 } @@ -426,7 +438,8 @@ struct PairingView: View { } startPairingTask { - await connectManualHost(deviceName, trimmedHost, parsedPort) + let result = await connectManualHost(deviceName, trimmedHost, parsedPort) + onPairingResult?(result) } } diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Resources/Localizable.xcstrings b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/Resources/Localizable.xcstrings index d1c799cbe028..196c401d013c 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": { 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()