Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
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
@@ -0,0 +1,46 @@
public import CMUXMobileCore

/// A best-effort lookup of fresher attach routes for a paired Mac from the
/// team-scoped device registry.
///
/// The registry is a rendezvous layer, not an authority: it lets a re-launched
/// phone discover the current routes for the Mac it last paired with (e.g. when
/// the Mac moved networks or restarted on a different port). It is deliberately
/// fallible — a `nil` result means "registry unavailable, use what you have," so
/// reconnect always falls back to the locally persisted paired-Mac routes and
/// pairing survives the cloud registry being down.
public protocol DeviceRegistryRefreshing: Sendable {
/// Fetch the registry's current routes for the given Mac device id, scoped to
/// the signed-in user's team.
///
/// - Returns: The registry's routes for that Mac, or `nil` when the registry
/// is unreachable, the call is unauthorized, or the Mac is not registered.
/// `nil` and `[]` are both treated as "no fresher routes" by
/// ``DeviceRegistryRouteSelection/selectReconnectRoutes(local:registry:)``.
func freshRoutes(forMacDeviceID macDeviceID: String) async -> [CmxAttachRoute]?
}

/// Pure route-selection policy for reconnect, isolated so it is unit-testable
/// without any network or store. The reconnect path connects on `local` routes
/// immediately (no added latency on the common case) and only *replaces* the
/// persisted routes when the registry returns a usable, different set.
public enum DeviceRegistryRouteSelection {
/// Choose the routes to persist for the next reconnect.
///
/// - Parameters:
/// - local: The routes currently persisted for the paired Mac.
/// - registry: The registry's routes, or `nil` when it was unavailable.
/// - Returns: The registry routes when they are non-empty and differ from
/// `local` (so a stale-route Mac gets rescued on the next reconnect
/// trigger); otherwise `local`, so an unavailable or no-op registry never
/// discards working routes. The result is `nil` only to signal "no change
/// needed," letting callers skip a redundant store write.
public static func selectReconnectRoutes(
local: [CmxAttachRoute],
registry: [CmxAttachRoute]?
) -> [CmxAttachRoute]? {
guard let registry, !registry.isEmpty else { return nil }
guard registry != local else { return nil }
return registry
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
public import CMUXMobileCore
public import Foundation
import os

private let deviceRegistryLog = Logger(subsystem: "com.cmuxterm.app", category: "DeviceRegistry")

/// HTTP client for the team-scoped device registry (`/api/devices`).
///
/// Looks up fresher attach routes for a paired Mac on reload. P1 only needs the
/// phone to *read* the team's Macs; registering the phone itself as a `device`
/// row is deferred to the key-pinning phase (a phone row only matters once it
/// anchors a pinned key for revoke). `deviceID` is already plumbed here so that
/// phase has the persisted identity ready.
///
/// Auth mirrors ``PushRegistrationService``: native calls send
/// `Authorization: Bearer <access>` + `X-Stack-Refresh-Token: <refresh>`, plus an
/// optional `X-Cmux-Team-Id` so the server scopes to the chosen team (defaults to
/// the Stack-selected team when omitted). Tokens are supplied through injected
/// Sendable closures so this service needs no dependency on the auth package.
///
/// Every call is best-effort and failure-tolerant: a thrown/timed-out request
/// yields `nil` so reconnect falls back to locally persisted routes and pairing
/// survives the registry being down.
public actor DeviceRegistryService: DeviceRegistryRefreshing {
/// Supplies the bearer/refresh tokens for an authenticated request, or `nil`
/// when there is no valid session.
public struct TokenSource: Sendable {
public var accessToken: @Sendable () async -> String?
public var refreshToken: @Sendable () async -> String?

public init(
accessToken: @escaping @Sendable () async -> String?,
refreshToken: @escaping @Sendable () async -> String?
) {
self.accessToken = accessToken
self.refreshToken = refreshToken
}
}

private let apiBaseURL: String
private let deviceID: String
private let tokenSource: TokenSource
private let teamIDProvider: @Sendable () async -> String?
private let session: URLSession
private let requestTimeout: TimeInterval

/// - Parameters:
/// - apiBaseURL: The cmux web API base URL (no trailing slash).
/// - deviceID: This iOS device's registry id (``MobileDeviceIdentity``).
/// - tokenSource: Supplies the Stack access/refresh tokens.
/// - teamIDProvider: Supplies the team id to scope to, or `nil` to let the
/// server use the Stack-selected team.
/// - session: The URLSession used for API calls.
/// - requestTimeout: Per-request deadline, bounding the worst-case latency
/// of a registry call so it never stalls the reconnect refresh.
public init(
apiBaseURL: String,
deviceID: String,
tokenSource: TokenSource,
teamIDProvider: @escaping @Sendable () async -> String? = { nil },
session: sending URLSession = .shared,
requestTimeout: TimeInterval = 5
) {
self.apiBaseURL = apiBaseURL
self.deviceID = deviceID
self.tokenSource = tokenSource
self.teamIDProvider = teamIDProvider
self.session = session
self.requestTimeout = requestTimeout
}

// MARK: - DeviceRegistryRefreshing

public func freshRoutes(forMacDeviceID macDeviceID: String) async -> [CmxAttachRoute]? {
guard let request = await makeRequest(method: "GET", path: "/api/devices", body: nil) else {
return nil
}
let data: Data
do {
let (responseData, response) = try await session.data(for: request)
guard let http = response as? HTTPURLResponse, (200...299).contains(http.statusCode) else {
return nil
}
data = responseData
} catch {
deviceRegistryLog.debug("freshRoutes request failed: \(String(describing: error), privacy: .public)")
return nil
}
return Self.routes(forMacDeviceID: macDeviceID, in: data)
}

// MARK: - Parsing (pure, testable)

/// Decode the `/api/devices` list response and return the routes for the
/// device whose id matches `macDeviceID`, preferring its most recently seen
/// app instance. Returns `nil` when the device or routes are absent so the
/// caller falls back to local routes.
///
/// Each route is decoded *failably* and individually: a malformed or
/// unknown-kind route from any instance (even another Mac's) is skipped
/// rather than failing the whole response. This keeps one bad sibling row
/// from disabling registry refresh for every Mac, and makes old clients
/// forward-compatible when a newer build advertises a route kind they cannot
/// decode.
static func routes(forMacDeviceID macDeviceID: String, in data: Data) -> [CmxAttachRoute]? {
// Decode each route element through an optional wrapper so a single bad
// element decodes to `nil` and is dropped, never throwing for the array.
struct FailableRoute: Decodable {
let value: CmxAttachRoute?
init(from decoder: Decoder) throws {
value = try? CmxAttachRoute(from: decoder)
}
}
struct Instance: Decodable {
let routes: [FailableRoute]
}
struct Device: Decodable {
let deviceId: String
let instances: [Instance]
}
struct ListResponse: Decodable {
let devices: [Device]
}
guard let decoded = try? JSONDecoder().decode(ListResponse.self, from: data) else {
return nil
}
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
let target = macDeviceID.lowercased()
guard let device = decoded.devices.first(where: { $0.deviceId.lowercased() == target }) else {
return nil
}
// Instances are returned most-recently-seen first; the first instance
// with at least one decodable route is the freshest reachable one.
for instance in device.instances {
let routes = instance.routes.compactMap(\.value)
if !routes.isEmpty { return routes }
}
return nil

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale routes from older tags

Medium Severity

When resolving registry routes for a Mac, the client walks instances in recency order and returns the first with any decodable routes. If the newest instance has empty routes (e.g. pairing turned off) but an older (deviceId, tag) row still has routes, those stale endpoints are returned and can overwrite local routes via selectReconnectRoutes, undermining the Mac’s empty-route publish.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 90fc5e4. Configure here.

}

// MARK: - Request building

private func makeRequest(method: String, path: String, body: [String: Any]?) async -> URLRequest? {
guard let accessToken = await tokenSource.accessToken(),
let refreshToken = await tokenSource.refreshToken(),
let url = URL(string: apiBaseURL + path) else {
return nil
}
var request = URLRequest(url: url)
request.httpMethod = method
request.timeoutInterval = requestTimeout
request.setValue("Bearer \(accessToken)", forHTTPHeaderField: "Authorization")
request.setValue(refreshToken, forHTTPHeaderField: "X-Stack-Refresh-Token")
if let teamID = await teamIDProvider(), !teamID.isEmpty {
request.setValue(teamID, forHTTPHeaderField: "X-Cmux-Team-Id")
}
if let body {
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = try? JSONSerialization.data(withJSONObject: body)
}
return request
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
public import Foundation

/// This iOS device's stable cmux identity for the device registry.
///
/// A cmux-GENERATED persisted UUID (NOT `identifierForVendor`, which resets when
/// the last cmux app is removed, and NOT a hardware fingerprint). Persisted in
/// `UserDefaults` so it survives relaunch and reinstall-while-other-cmux-apps-
/// present, is cross-platform, and is user-renamable via its display name.
///
/// Mirrors the Mac side's `MobileHostIdentity.deviceID()` so both ends of the
/// registry use the same identity shape. The phone sends this id when it
/// registers itself as a device; the registry's key-pinning phase will later
/// anchor a pinned key to it for revoke.
public enum MobileDeviceIdentity {
private static let deviceIDKey = "cmux.deviceRegistry.iosDeviceID"

/// The persisted device UUID, generating and storing one on first use.
/// - Parameter defaults: Persistence store (injected for tests).
public static func deviceID(defaults: UserDefaults = .standard) -> String {
if let existing = defaults.string(forKey: deviceIDKey),
!existing.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
return existing
}
let generated = UUID().uuidString.lowercased()
defaults.set(generated, forKey: deviceIDKey)
return generated

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Make device ID initialization atomic and self-healing.

Line 20 through Line 26 performs a non-atomic check-then-set, so concurrent first lookups can return different UUIDs. It also accepts any non-empty persisted value, which can propagate invalid IDs across the registry boundary.

💡 Suggested fix
 public enum MobileDeviceIdentity {
     private static let deviceIDKey = "cmux.deviceRegistry.iosDeviceID"
+    private static let lock = NSLock()

     /// The persisted device UUID, generating and storing one on first use.
     /// - Parameter defaults: Persistence store (injected for tests).
     public static func deviceID(defaults: UserDefaults = .standard) -> String {
-        if let existing = defaults.string(forKey: deviceIDKey),
-           !existing.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
-            return existing
+        lock.lock()
+        defer { lock.unlock() }
+
+        if let raw = defaults.string(forKey: deviceIDKey) {
+            let trimmed = raw.trimmingCharacters(in: .whitespacesAndNewlines)
+            if let uuid = UUID(uuidString: trimmed) {
+                let canonical = uuid.uuidString.lowercased()
+                if canonical != raw {
+                    defaults.set(canonical, forKey: deviceIDKey)
+                }
+                return canonical
+            }
         }
+
         let generated = UUID().uuidString.lowercased()
         defaults.set(generated, forKey: deviceIDKey)
         return generated
     }
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
public static func deviceID(defaults: UserDefaults = .standard) -> String {
if let existing = defaults.string(forKey: deviceIDKey),
!existing.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
return existing
}
let generated = UUID().uuidString.lowercased()
defaults.set(generated, forKey: deviceIDKey)
return generated
public enum MobileDeviceIdentity {
private static let deviceIDKey = "cmux.deviceRegistry.iosDeviceID"
// NSLock exception: UserDefaults is shared mutable state accessed concurrently on first-use.
// Lock ensures atomic check-then-generate-and-persist to prevent duplicate device IDs.
private static let lock = NSLock()
/// The persisted device UUID, generating and storing one on first use.
/// - Parameter defaults: Persistence store (injected for tests).
public static func deviceID(defaults: UserDefaults = .standard) -> String {
lock.lock()
defer { lock.unlock() }
if let raw = defaults.string(forKey: deviceIDKey) {
let trimmed = raw.trimmingCharacters(in: .whitespacesAndNewlines)
if let uuid = UUID(uuidString: trimmed) {
let canonical = uuid.uuidString.lowercased()
if canonical != raw {
defaults.set(canonical, forKey: deviceIDKey)
}
return canonical
}
}
let generated = UUID().uuidString.lowercased()
defaults.set(generated, forKey: deviceIDKey)
return generated
}
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@Packages/CmuxMobileShell/Sources/CmuxMobileShell/MobileDeviceIdentity.swift`
around lines 19 - 26, The deviceID(defaults:) function currently does a
non-atomic check-then-set and accepts any non-empty string; make it atomic and
self-healing by serializing the check-and-write and validating stored values as
real UUIDs: create a private serial queue or use objc_sync_enter/exit around the
body of deviceID(defaults:) (reference deviceID(defaults:) and deviceIDKey) so
concurrent callers cannot race, read the stored string, validate it with
UUID(uuidString:) (and normalize with .lowercased()), and if missing or invalid
generate a new UUID().uuidString.lowercased(), persist it to defaults under
deviceIDKey, and return that value. Ensure you always overwrite invalid values
instead of returning them.

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,11 @@ public final class MobileShellComposite: MobileTerminalOutputSinking {

private let runtime: (any MobileSyncRuntime)?
private let pairedMacStore: (any MobilePairedMacStoring)?
/// Best-effort, team-scoped lookup of fresher attach routes from the device
/// registry. Optional and failure-tolerant: when `nil` or unreachable,
/// reconnect uses the locally persisted paired-Mac routes, so pairing
/// survives the cloud registry being down.
private let deviceRegistry: (any DeviceRegistryRefreshing)?
private let identityProvider: (any MobileIdentityProviding)?
private let reachability: any ReachabilityProviding
private let pairingHintDefaults: UserDefaults
Expand Down Expand Up @@ -323,6 +328,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking {
pairingCode: String = "",
workspaces: [MobileWorkspacePreview] = [],
pairedMacStore: (any MobilePairedMacStoring)? = nil,
deviceRegistry: (any DeviceRegistryRefreshing)? = nil,
clientIDRepository: MobileClientIDRepository = MobileClientIDRepository(defaults: .standard),
identityProvider: (any MobileIdentityProviding)? = nil,
reachability: any ReachabilityProviding = ReachabilityService(),
Expand All @@ -332,6 +338,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking {
) {
self.runtime = runtime
self.pairedMacStore = pairedMacStore
self.deviceRegistry = deviceRegistry
self.identityProvider = identityProvider
self.reachability = reachability
self.pairingHintDefaults = pairingHintDefaults
Expand Down Expand Up @@ -915,6 +922,12 @@ public final class MobileShellComposite: MobileTerminalOutputSinking {
finishStoredMacReconnectAttempt(generation: generation)
return false
}
// Kick off a best-effort registry refresh for this Mac in the background.
// It does NOT block the connect below: the common case (fresh local
// routes) reconnects immediately with no network round-trip. If the Mac
// moved networks / changed port, the refreshed routes land in the store
// and the next reconnect trigger (network change or Retry) uses them.
refreshRoutesFromRegistry(for: mac, stackUserID: stackUserID)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Use registry routes for the launch reconnect attempt

When the locally stored route is stale but /api/devices has the fresh address (the Mac moved networks or rebound to a new port), this starts the registry lookup in the background and then immediately reconnects with mac.routes below. The background task only upserts the store and reloads the paired-Mac list; it does not retry the in-flight launch reconnect, so the reload still fails until the user presses Retry or a network-change trigger happens, which misses the auto-pair-on-reload case this registry path is meant to rescue.

Useful? React with 👍 / 👎.

let supportedKinds = runtime?.supportedRouteKinds ?? []
guard let (host, port) = Self.firstReconnectHostPortRoute(
mac.routes,
Expand Down Expand Up @@ -980,6 +993,42 @@ public final class MobileShellComposite: MobileTerminalOutputSinking {
didFinishStoredMacReconnectAttempt = true
}

/// Best-effort, non-blocking registry refresh for the active paired Mac.
///
/// Runs detached so it never adds latency to the in-flight reconnect (which
/// connects on the locally persisted routes). When the registry returns
/// usable, *different* routes for this Mac, they are written back into the
/// store so the next reconnect trigger (network change / Retry) reaches the
/// Mac at its current address after it moved networks or changed port. A
/// missing registry, an unauthorized call, or no-change routes are no-ops, so
/// a registry outage never disturbs the locally stored routes.
private func refreshRoutesFromRegistry(for mac: MobilePairedMac, stackUserID: String?) {
guard let deviceRegistry, let pairedMacStore else { return }
let macDeviceID = mac.macDeviceID
let localRoutes = mac.routes
let displayName = mac.displayName
Task { [weak self] in
let registryRoutes = await deviceRegistry.freshRoutes(forMacDeviceID: macDeviceID)
guard let updated = DeviceRegistryRouteSelection.selectReconnectRoutes(
local: localRoutes,
registry: registryRoutes
) else { return }
do {
try await pairedMacStore.upsert(
macDeviceID: macDeviceID,
displayName: displayName,
routes: updated,
markActive: true,
stackUserID: stackUserID
)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
} catch {
mobileShellLog.debug("registry route refresh upsert failed: \(String(describing: error), privacy: .public)")
return
}
await self?.loadPairedMacs()
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
}
}
Comment on lines +1013 to +1051

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Background refresh silently overrides the user's active Mac

refreshRoutesFromRegistry runs in a detached Task and calls pairedMacStore.upsert(markActive: true, ...). markActive: true deactivates every other Mac for the user (via UPDATE paired_macs SET is_active = 0 WHERE stack_user_id IS ?) and then sets this Mac as active. If the user switches to a different Mac between when the reconnect starts and when the network response lands (e.g., a slow registry round-trip), the background upsert silently reverts the switch: the user's newly selected Mac is deactivated and the original Mac is re-activated.

The goal of this path is route freshness only — markActive: false updates the stored routes without touching the active-Mac selection, which is the correct invariant here.


// MARK: - Paired Mac switching

/// Every Mac paired with this device, for the host switcher. Refreshed via
Expand Down
Loading
Loading