Skip to content
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
Show all changes
38 commits
Select commit Hold shift + click to select a range
e067ee5
test: persist removed iOS routes
azooz2003-bit Sep 3, 2026
7cf8bce
fix: persist removed iOS route endpoints
azooz2003-bit Sep 3, 2026
de96fb6
fix: align workspace group snapshot arguments
azooz2003-bit Sep 4, 2026
66b690c
fix: carry route tombstones across scope claims
azooz2003-bit Sep 4, 2026
ec16a92
fix: fail closed on route tombstone read errors
azooz2003-bit Sep 4, 2026
2134b07
test: cover active route teardown on deletion
azooz2003-bit Sep 4, 2026
58eeb9c
fix: close live session when route is deleted
azooz2003-bit Sep 4, 2026
ee7f909
test: cover route reauthorization after deletion
azooz2003-bit Sep 4, 2026
a4b274b
fix: clear route tombstone when rescanned
azooz2003-bit Sep 4, 2026
cb59c89
test: model scanner route upsert
azooz2003-bit Sep 4, 2026
ff5ab93
test: require strict tailscale-only reconnect
azooz2003-bit Sep 4, 2026
756d741
test: retain user tailscale route across presence refresh
azooz2003-bit Sep 4, 2026
c12e121
fix: preserve authorized tailscale routes and fail closed
azooz2003-bit Sep 4, 2026
d6ebf92
test: cover tailscale replacement presentation
azooz2003-bit Sep 4, 2026
00e1d87
feat: rescan tailscale pairing from computer detail
azooz2003-bit Sep 4, 2026
1aaab8c
test: preserve tailscale tombstone during scope claim
azooz2003-bit Sep 4, 2026
cb43d04
test: validate route identity and transport drain
azooz2003-bit Sep 4, 2026
bfada19
fix: await and validate tailscale route removal
azooz2003-bit Sep 4, 2026
34f41f1
fix: localize tailscale replacement action
azooz2003-bit Sep 4, 2026
b8df7af
fix: preserve exact backup scope for route removal
azooz2003-bit Sep 4, 2026
6cb1af4
fix: cancel reconnect when route is deleted
azooz2003-bit Sep 4, 2026
dcc3d7c
Merge remote-tracking branch 'origin/main' into fix-ios-tailscale-pat…
azooz2003-bit Sep 4, 2026
32eeed2
chore: remove obsolete reconnect policy locals
azooz2003-bit Sep 4, 2026
b77bdc2
fix: suppress deleted routes during refresh
azooz2003-bit Sep 4, 2026
429571b
fix: bound route tombstone retention
azooz2003-bit Sep 4, 2026
e6987e0
fix: make replacement pairing fail closed
azooz2003-bit Sep 5, 2026
d30dd41
fix: replace stale tailscale routes on rescan
azooz2003-bit Sep 5, 2026
8498c3c
fix: retain route deletion tombstones
azooz2003-bit Sep 5, 2026
870a251
fix: bound route suppression without resurrection
azooz2003-bit Sep 5, 2026
7c80753
fix: preserve wildcard route suppression
azooz2003-bit Sep 5, 2026
6f2701c
Merge remote-tracking branch 'origin/main' into fix-ios-tailscale-pat…
azooz2003-bit Sep 5, 2026
572191c
Merge remote-tracking branch 'origin/main' into fix-ios-tailscale-pat…
azooz2003-bit Sep 5, 2026
3e1d24b
fix: honor wildcard route suppression during refresh
azooz2003-bit Sep 5, 2026
904dba3
fix: align tombstone limit with sqlite count
azooz2003-bit Sep 5, 2026
0888b94
fix: report superseded preview pairing
azooz2003-bit Sep 5, 2026
96a2779
Merge remote-tracking branch 'origin/main' into fix-ios-tailscale-pat…
azooz2003-bit Sep 5, 2026
113de2d
test: vary route compaction fixture endpoints
azooz2003-bit Sep 5, 2026
6e01f59
Merge remote-tracking branch 'origin/main' into fix-ios-tailscale-pat…
azooz2003-bit Sep 5, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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 = ?;
Expand Down Expand Up @@ -317,6 +326,42 @@ extension MobilePairedMacStore {
}

func fetchRoutes(macDeviceID: String, ownerKey: String) throws -> [CmxAttachRoute] {
var removedStatement: OpaquePointer?
defer { sqlite3_finalize(removedStatement) }
let removedRC = sqlite3_prepare_v2(
db,
"""
SELECT kind, endpoint_json
FROM mac_route_removals
WHERE mac_device_id = ? AND owner_key = ?;
""",
-1,
&removedStatement,
nil
)
guard removedRC == SQLITE_OK else {
throw MobilePairedMacStoreError.prepareFailed(removedRC, lastErrorMessage())
}
try bind(
statement: removedStatement,
parameters: [.text(macDeviceID), .text(ownerKey)]
)
var removedKeys: Set<String> = []
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)")
}

var statement: OpaquePointer?
defer { sqlite3_finalize(statement) }
let sql = """
Expand All @@ -341,6 +386,10 @@ extension MobilePairedMacStore {
pairedMacStoreLog.warning("dropping unparsable route row")
continue
}
if let endpoint = try? Self.encodeRouteEndpoint(route),
removedKeys.contains("\(route.kind.rawValue)\u{1F}\(endpoint)") {
continue
}
routes.append(route)
}
return routes
Expand Down Expand Up @@ -393,6 +442,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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ let pairedMacStoreLog = Logger(subsystem: "com.cmuxterm.app", category: "PairedM
/// inject it as `any MobilePairedMacStoring`.
public actor MobilePairedMacStore: MobilePairedMacStoring {
/// The schema version this build creates and migrates to.
public static let currentSchemaVersion: Int32 = 11
public static let currentSchemaVersion: Int32 = 12

private let dbPath: String
// `nonisolated(unsafe)` only so the (Swift 6 nonisolated) `deinit` can close
Expand Down Expand Up @@ -232,6 +232,12 @@ public actor MobilePairedMacStore: MobilePairedMacStoring {
"paired-mac store schema v\(version) is newer than this build (v\(Self.currentSchemaVersion)); reading known columns only"
)
}
if version < 12 {
try transaction {
try migrateToV12()
try setUserVersion(12)
}
}
}

private func migrateToV1() throws {
Expand Down Expand Up @@ -537,6 +543,31 @@ public actor MobilePairedMacStore: MobilePairedMacStoring {
try exec("ALTER TABLE paired_macs ADD COLUMN direct_addresses TEXT;")
}

/// v12: device-local route tombstones. A paired Mac can keep advertising a
/// route after the user removes it on this iPhone, so route refreshes must
/// remember the endpoint suppression independently of the host snapshot.
/// The table is intentionally not part of the backup record and is removed
/// with its paired-Mac row on forget/re-pair.
private func migrateToV12() throws {
try exec("""
CREATE TABLE IF NOT EXISTS mac_route_removals (
id INTEGER PRIMARY KEY AUTOINCREMENT,
mac_device_id TEXT NOT NULL,
owner_key TEXT NOT NULL,
kind TEXT NOT NULL,
endpoint_json TEXT NOT NULL,
UNIQUE (mac_device_id, owner_key, kind, endpoint_json),
FOREIGN KEY (mac_device_id, owner_key)
REFERENCES paired_macs(mac_device_id, owner_key)
ON DELETE CASCADE
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
);
""")
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<String> {
Expand Down Expand Up @@ -644,6 +675,114 @@ public actor MobilePairedMacStore: MobilePairedMacStoring {
)
}

/// Remove one route from a scoped pairing and persist an endpoint tombstone
/// so later registry/presence refreshes cannot resurrect it on this device.
@discardableResult
public func removeRouteIfAuthorized(
macDeviceID: String,
route: CmxAttachRoute,
condition: MobilePairedMacRouteWriteCondition,
stackUserID: String?,
teamID: String?,
now: Date
) async throws -> Bool {
guard route.kind != .iroh else { return false }
try ensureReady()
let macDeviceID = cmxCanonicalDeviceID(macDeviceID)
let instanceTag: String?
switch condition {
case .matchingInstanceTag(let tag): instanceTag = tag
case .unclaimed: instanceTag = nil
}
let ownerKey = Self.ownerKey(
stackUserID: stackUserID,
teamID: teamID,
instanceTag: instanceTag
)
var didWrite = false
try transaction {
guard let current = try fetchMacRow(
macDeviceID: macDeviceID,
ownerKey: ownerKey
) else { return }
switch condition {
case .matchingInstanceTag(let expected):
guard CmxMacAppInstanceIdentity(
macDeviceID: current.macDeviceID,
instanceTag: current.instanceTag
).id == CmxMacAppInstanceIdentity(
macDeviceID: macDeviceID,
instanceTag: expected
).id else { return }
case .unclaimed:
guard current.instanceTag == nil,
!(try hasClaimedSibling(
macDeviceID: macDeviceID,
stackUserID: stackUserID,
teamID: teamID
)) else { return }
}

let currentRoutes = try fetchRoutes(
macDeviceID: macDeviceID,
ownerKey: ownerKey
)
guard let removed = currentRoutes.first(where: { $0.id == route.id })
?? currentRoutes.first(where: {
$0.kind == route.kind && $0.endpoint == route.endpoint
}) else { return }
let remaining = currentRoutes.filter { $0.id != removed.id }
guard !remaining.isEmpty else { return }

let encoded = try Self.encodeRouteEndpoint(removed)
try exec("""
INSERT OR IGNORE INTO mac_route_removals (
mac_device_id, owner_key, kind, endpoint_json
) VALUES (?, ?, ?, ?);
""", binding: [
.text(macDeviceID),
.text(ownerKey),
.text(removed.kind.rawValue),
.text(encoded),
])
try upsertMacRow(
macDeviceID: macDeviceID,
ownerKey: ownerKey,
displayName: current.displayName,
instanceTag: current.instanceTag,
stackUserID: current.stackUserID,
teamID: current.teamID,
createdAt: current.createdAt,
lastSeenAt: now,
isActive: current.isActive
)
try exec(
"DELETE FROM mac_routes WHERE mac_device_id = ? AND owner_key = ?;",
binding: [.text(macDeviceID), .text(ownerKey)]
)
for remainingRoute in remaining {
guard let disclosed = remainingRoute.disclosed(
for: .authenticated,
at: now
) else { continue }
try exec("""
INSERT INTO mac_routes (
mac_device_id, owner_key, route_id, kind, endpoint_json, priority
) VALUES (?, ?, ?, ?, ?, ?);
""", binding: [
.text(macDeviceID),
.text(ownerKey),
.text(remainingRoute.id),
.text(remainingRoute.kind.rawValue),
.text(try Self.encodeRoute(disclosed)),
.int(Int64(remainingRoute.priority)),
])
}
didWrite = true
}
return didWrite
}

/// Persist `'user'`-origin Tailscale compatibility grants for routes the
/// user entered as a pairing code. Upgrades an existing `'migration'` grant
/// for the same destination to `'user'`, so a deliberate re-scan is not
Expand Down Expand Up @@ -1135,6 +1274,35 @@ public actor MobilePairedMacStore: MobilePairedMacStoring {
instanceTag: String?,
stackUserID: String? = nil,
teamID: String? = nil
) async throws {
try removeExactSync(
macDeviceID: macDeviceID,
instanceTag: instanceTag,
stackUserID: stackUserID,
teamID: teamID
)
}

/// Remove one tagged paired Mac in a specific owner scope.
public func remove(
macDeviceID: String,
instanceTag: String?,
stackUserID: String? = nil,
teamID: String? = nil
) throws {
try removeExactSync(
macDeviceID: macDeviceID,
instanceTag: instanceTag,
stackUserID: stackUserID,
teamID: teamID
)
}

private func removeExactSync(
macDeviceID: String,
instanceTag: String?,
stackUserID: String? = nil,
teamID: String? = nil
) throws {
try ensureReady()
let macDeviceID = cmxCanonicalDeviceID(macDeviceID)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -227,6 +241,48 @@ public protocol MobilePairedMacStoring: Sendable {
}

extension MobilePairedMacStoring {
/// In-memory/test fallback for stores that do not persist route tombstones.
/// Production SQLite and scope decorators override this requirement.
@discardableResult
public func removeRouteIfAuthorized(
macDeviceID: String,
route: CmxAttachRoute,
condition: MobilePairedMacRouteWriteCondition,
stackUserID: String?,
teamID: String?,
now: Date
) async throws -> Bool {
let instanceTag: String?
switch condition {
case .matchingInstanceTag(let tag): instanceTag = tag
case .unclaimed: instanceTag = nil
}
let current = try await loadAll(stackUserID: stackUserID, teamID: teamID)
.first {
cmxCanonicalDeviceID($0.macDeviceID) == cmxCanonicalDeviceID(macDeviceID)
&& CmxMacAppInstanceIdentity(
macDeviceID: $0.macDeviceID,
instanceTag: $0.instanceTag
).id == CmxMacAppInstanceIdentity(
macDeviceID: macDeviceID,
instanceTag: instanceTag
).id
}
guard let current else { return false }
let remaining = current.routes.filter { $0.id != route.id }
guard remaining.count < current.routes.count, !remaining.isEmpty else { return false }
return try await upsertRoutesIfAuthorized(
macDeviceID: macDeviceID,
displayName: current.displayName,
routes: remaining,
condition: condition,
markActive: nil,
stackUserID: stackUserID,
teamID: teamID,
now: now
)
}

/// Compatibility no-op for stores that predate per-Computer Direct
/// addresses (test fixtures); the SQLite store and decorators override.
public func setDirectAddresses(
Expand Down
Loading