Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
fix(spaces-macos): make a spare Mac a Spaces host you can use from another Mac (#4512)
ddupont410578a4a18e
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppEnvironment.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppEnvironment.swiftindex f58528a8a5..24e1f895e4 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppEnvironment.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppEnvironment.swift@@ -115,6 +115,14 @@ public enum AppEnvironment {devices: devices,presence: fixtures ? FixturePresence() : LivePresence(),loginItem: fixtures ? fixtureLoginItem(env["CUA_SPACES_LOGIN_ITEM"]) : MainAppLoginItem())+ if !fixtures, live != nil {+ // Ask for Local Network access while someone is at this Mac+ // (the first run's setup, and launch on a Mac that provides+ // Spaces); one request shared by both.+ let localNetwork = LiveLocalNetworkPermission()+ model.host.localNetwork = localNetwork+ onboarding.host.localNetwork = localNetwork+ }if let live {let auth = live.cua.auth()// Signed out is nil (setup signs in first); anything else (nodiff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swiftindex 09b1803f66..c51491d9da 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swift@@ -202,6 +202,10 @@ public final class AppModel {if case .failed = self.signIn { return false }return self.identity != nil}+ // Onboarding's This machine step has its own HostModel: give it the+ // same inline sign-in, or a skipped sign-in fails setup with "Not+ // signed in" instead of opening the browser and carrying on.+ self.onboarding.host.signIn = self.host.signIn// A row takes a window drop by the core's rule (the notch tiles' too).dropTargets.isDropTarget = { [weak self] id inself?.spaces.first { $0.id == id }.map { appSpaceAcceptsDrop(space: $0) } ?? false@@ -666,6 +670,7 @@ public final class AppModel {guard case .waiting = signIn else { return }identity = who ?? account.identity()host.identity = identity+ onboarding.host.identity = identitydevices.signedIn = identity != nil// Activation funnel: the first run records `signed_in` on its// sign-in page; a sign-in from the main window (first run done or@@ -687,6 +692,7 @@ public final class AppModel {try? await account?.signOut()identity = nilhost.identity = nil+ onboarding.host.identity = nildevices.signedIn = falseawait devices.refresh()signIn = .idlediff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/DevicesModel.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/DevicesModel.swiftindex 082e4d179b..9486bd14e9 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/DevicesModel.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/DevicesModel.swift@@ -40,7 +40,18 @@ public final class LiveDevices: DevicesRunning, @unchecked Sendable {public func enroll() async throws -> DeviceEnrollment { try await inner.enroll() }public func checkEnrolled() async -> Bool { await inner.checkEnrolled() }public func approve(code: String?, deviceId: String?) async throws {- _ = try await inner.approve(code: code, deviceId: deviceId)+ try Self.requireEnrolled(try await inner.approve(code: code, deviceId: deviceId))+ }++ /// Only say "approved" when the relay says the device is enrolled:+ /// anything else would leave the other device waiting while this one+ /// reads success.+ static func requireEnrolled(_ device: RelayDevice) throws {+ guard device.state == "enrolled" else {+ throw CuaError.Runtime(+ message: "The relay did not enroll \(device.name) (\(device.id)): it is \(device.state). "+ + "Ask that device for a new code and try again.")+ }}public func rename(id: String, name: String) async throws { _ = try await inner.rename(id: id, name: name) }public func revoke(id: String) async throws { _ = try await inner.revoke(id: id) }diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/HostModel.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/HostModel.swiftindex bd0cbd8286..0c804f88fd 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/HostModel.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/HostModel.swift@@ -142,6 +142,10 @@ public final class HostModel {"Sign in to Cua in your browser to continue. Setup finishes on its own after that."/// Called whenever the state changes (the roster's entry follows it).public var onChange: (() -> Void)?+ /// Asks macOS for Local Network access once this Mac provides Spaces+ /// (see `LocalNetworkPermissionRequesting`); nil in fixtures and tests.+ public var localNetwork: LocalNetworkPermissionRequesting?+ private var askedLocalNetwork = falsepublic init(host: HostRunning?) {self.host = host@@ -154,6 +158,13 @@ public final class HostModel {func apply(_ status: HostStatus) {state = appHostState(status: status)+ // Setup that provides Spaces, launch on a Mac that already does, or+ // Spaces turned on: ask now, while someone is at this Mac, not when+ // the first Space boots (see `LocalNetworkPermissionRequesting`).+ if let state, state.configured, state.provideSpaces, !askedLocalNetwork, let localNetwork {+ askedLocalNetwork = true+ localNetwork.request()+ }onChange?()}diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/LocalNetworkPermission.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/LocalNetworkPermission.swiftnew file mode 100644index 0000000000..a8bf5ca61b--- /dev/null+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/LocalNetworkPermission.swift@@ -0,0 +1,107 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import Darwin+import Foundation+import Network++/// Asks macOS for Local Network access for this app (fire and forget).+///+/// Why: a Mac that provides Spaces boots macOS VMs (Lume, on vmnet+/// 192.168.64.x) and its `cua daemon` (inside this app's bundle) must reach+/// the guest. macOS blocks that ("No route to host") until Local Network+/// access is allowed, and it asks only the first time the app reaches the+/// local network, at most once per boot, on this Mac's own screen. The app+/// is not even listed under System Settings > Privacy & Security > Local+/// Network until it has been asked. Left alone, the prompt appears when the+/// first Space is created, often from another Mac while nobody is at this+/// one, and the create fails. So the app asks while the user is here: when+/// "Set up for access" succeeds with Spaces provided, and when it launches+/// on a Mac already set up to provide them.+public protocol LocalNetworkPermissionRequesting: AnyObject, Sendable {+ /// Triggers the prompt if macOS has not decided yet. Never blocks.+ func request()+}++/// The live request: a short-lived UDP datagram to an address on this Mac's+/// local network (the first active IPv4 interface's subnet, and vmnet's+/// 192.168.64.1, where the VMs live). Each connection is cancelled after a+/// few seconds whatever happens; nothing waits for it. Asks once per+/// process (macOS asks at most once per boot anyway).+public final class LiveLocalNetworkPermission: LocalNetworkPermissionRequesting, @unchecked Sendable {+ private let lock = NSLock()+ private var asked = false+ private let queue = DispatchQueue(label: "com.trycua.cua-spaces.local-network")+ /// How long each probe may live.+ let lifetime: TimeInterval++ public init(lifetime: TimeInterval = 3) {+ self.lifetime = lifetime+ }++ public func request() {+ lock.lock()+ let first = !asked+ asked = true+ lock.unlock()+ guard first else { return }+ queue.async { [self] in+ for host in Self.targets() { probe(host) }+ }+ }++ private func probe(_ host: String) {+ // Port 9 (discard): any datagram to a local address is what makes+ // macOS ask; nothing has to answer.+ let connection = NWConnection(host: NWEndpoint.Host(host), port: 9, using: .udp)+ connection.stateUpdateHandler = { state in+ switch state {+ case .ready:+ connection.send(content: Data([0]), completion: .contentProcessed { _ in })+ case .failed, .waiting:+ connection.cancel()+ default:+ break+ }+ }+ connection.start(queue: queue)+ queue.asyncAfter(deadline: .now() + lifetime) { connection.cancel() }+ }++ /// The addresses to reach: the first active non-loopback IPv4+ /// interface's first host (usually the router), then vmnet's gateway.+ static func targets() -> [String] {+ var out: [String] = []+ if let lan = firstSubnetHost() { out.append(lan) }+ if !out.contains(vmnetGateway) { out.append(vmnetGateway) }+ return out+ }++ static let vmnetGateway = "192.168.64.1"++ static func firstSubnetHost() -> String? {+ var list: UnsafeMutablePointer<ifaddrs>?+ guard getifaddrs(&list) == 0, let first = list else { return nil }+ defer { freeifaddrs(list) }+ for cursor in sequence(first: first, next: { $0.pointee.ifa_next }) {+ let ifa = cursor.pointee+ let flags = Int32(ifa.ifa_flags)+ guard flags & IFF_UP != 0, flags & IFF_RUNNING != 0, flags & IFF_LOOPBACK == 0,+ let addr = ifa.ifa_addr, addr.pointee.sa_family == sa_family_t(AF_INET),+ let mask = ifa.ifa_netmask else { continue }+ let ip = addr.withMemoryRebound(to: sockaddr_in.self, capacity: 1) { UInt32(bigEndian: $0.pointee.sin_addr.s_addr) }+ let m = mask.withMemoryRebound(to: sockaddr_in.self, capacity: 1) { UInt32(bigEndian: $0.pointee.sin_addr.s_addr) }+ if let host = subnetHost(ip: ip, mask: m) { return host }+ }+ return nil+ }++ /// The subnet's first host (`192.168.1.23/24` → `192.168.1.1`); nil for+ /// link-local or a subnet with no room for another host.+ static func subnetHost(ip: UInt32, mask: UInt32) -> String? {+ guard ip >> 16 != 0xA9FE, mask != 0, ~mask >= 2 else { return nil }+ var target = (ip & mask) + 1+ if target == ip { target += 1 }+ return [24, 16, 8, 0].map { String((target >> UInt32($0)) & 0xFF) }.joined(separator: ".")+ }+}diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/OnboardingModel.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/OnboardingModel.swiftindex 1ed6db8437..3ae23ac551 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/OnboardingModel.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/OnboardingModel.swift@@ -127,6 +127,14 @@ public final class OnboardingModel {if let installed { send(.cliInstalled(target: installed.target)) }}+ /// Another `cua` that comes first on PATH (an old Python cua-cli, say),+ /// so typing `cua` runs it rather than the installed path Done shows:+ /// Done notes it under "cua command".+ public var cliShadowedBy: String? {+ guard state.cliTarget != nil, let other = cliPlan?.shadowedBy, !other.isEmpty else { return nil }+ return other+ }+// MARK: - Where it shows up/// A presentation card was picked: the flow shows it and the app savesdiff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/OnboardingView.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/OnboardingView.swiftindex 41398634f8..53f0981699 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/OnboardingView.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/OnboardingView.swift@@ -265,6 +265,12 @@ public struct OnboardingView: View {}}}+ if let other = onboarding.cliShadowedBy {+ Text("Another \(Text("cua").monospaced()) at \(other) comes first on PATH.")+ .font(.caption).foregroundStyle(.secondary)+ .fixedSize(horizontal: false, vertical: true)+ .accessibilityIdentifier("onboarding-cli-shadowed")+ }if !onboarding.hostPermissions.isEmpty {Text(copy.permissionsTitle).font(.headline).padding(.top, 8)PermissionRows(rows: onboarding.hostPermissions, openLabel: copy.openSettings)diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/DevicesTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/DevicesTests.swiftindex eae9300306..20a1fab015 100644--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/DevicesTests.swift+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/DevicesTests.swift@@ -72,6 +72,30 @@ struct DevicesTests {#expect(m.approval == nil)}+ /// The relay answers an approval with the device still pending: the+ /// sheet shows an error, never "approved".+ @Test func anApprovalTheRelayDidNotEnrollIsAnError() async {+ func relayDevice(_ state: String) -> RelayDevice {+ RelayDevice(id: "dev_work", name: "Work laptop", state: state, platform: "macos",+ createdAt: Self.now, enrolledUntil: nil, lastSeen: nil, current: false)+ }+ #expect(throws: Never.self) { try LiveDevices.requireEnrolled(relayDevice("enrolled")) }+ #expect(throws: CuaError.self) { try LiveDevices.requireEnrolled(relayDevice("pending")) }+ let relay = RelayAnswering(state: "pending")+ let live = DevicesModel(devices: relay, presence: FixturePresence())+ live.pollInterval = .milliseconds(1)+ live.signedIn = true+ await live.refresh()+ #expect(live.approval?.deviceId == "dev_work")+ live.setCode("k7qxm2rp")+ await live.approve()+ #expect(live.approval != nil, "still open: nothing was approved")+ #expect(live.approvalView?.error?.contains("pending") == true)+ relay.state = "enrolled"+ await live.approve()+ #expect(live.approval == nil)+ }+@Test func denyRevokesANewDeviceAndNotNowPutsOffReverification() async {let fixture = FixtureDevices(snapshot: FixtureDevices.sample(now: Self.now))let m = model(fixture)@@ -164,3 +188,24 @@ struct DevicesTests {#expect(m.view.rows.contains { $0.title == "Studio Mini" })}}++/// FixtureDevices whose approvals answer with the relay's device in `state`,+/// through LiveDevices' guard.+final class RelayAnswering: DevicesRunning, @unchecked Sendable {+ let fixture = FixtureDevices(snapshot: FixtureDevices.sample(now: DevicesTests.now))+ var state: String+ init(state: String) { self.state = state }++ func snapshot() async throws -> DevicesSnapshot { try await fixture.snapshot() }+ func enroll() async throws -> DeviceEnrollment { try await fixture.enroll() }+ func checkEnrolled() async -> Bool { await fixture.checkEnrolled() }+ func approve(code: String?, deviceId: String?) async throws {+ try LiveDevices.requireEnrolled(RelayDevice(+ id: "dev_work", name: "Work laptop", state: state, platform: "macos",+ createdAt: DevicesTests.now, enrolledUntil: nil, lastSeen: nil, current: false))+ try await fixture.approve(code: code, deviceId: deviceId)+ }+ func rename(id: String, name: String) async throws { try await fixture.rename(id: id, name: name) }+ func revoke(id: String) async throws { try await fixture.revoke(id: id) }+ func confirmMachine(id: String) async throws { try await fixture.confirmMachine(id: id) }+}diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/LocalNetworkPermissionTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/LocalNetworkPermissionTests.swiftnew file mode 100644index 0000000000..f66a7181bd--- /dev/null+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/LocalNetworkPermissionTests.swift@@ -0,0 +1,75 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import CuaSDK+import CuaSpacesFFI+@testable import CuaSpacesMacKit+import Foundation+import Testing++/// Counts Local Network requests; never touches the network.+final class FakeLocalNetwork: LocalNetworkPermissionRequesting, @unchecked Sendable {+ private(set) var requests = 0+ func request() { requests += 1 }+}++@MainActor+@Suite("Local Network access")+struct LocalNetworkPermissionTests {+ func setUp(profile: String, host: FixtureHost = FixtureHost()) async -> (HostModel, FakeLocalNetwork) {+ let m = HostModel(host: host)+ let fake = FakeLocalNetwork()+ m.localNetwork = fake+ m.openForm()+ m.send(.setProfile(profile: profile))+ await m.submit()+ return (m, fake)+ }++ @Test func setupThatProvidesSpacesAsksOnce() async {+ let (m, fake) = await setUp(profile: "spare")+ #expect(m.form == nil)+ #expect(m.state?.provideSpaces == true)+ #expect(fake.requests == 1)+ // Later refreshes do not ask again.+ await m.refresh()+ await m.refresh()+ #expect(fake.requests == 1)+ }++ @Test func desktopOnlySetupDoesNotAsk() async {+ let (m, fake) = await setUp(profile: "desktop")+ #expect(m.state?.configured == true)+ #expect(m.state?.provideSpaces == false)+ #expect(fake.requests == 0)+ }++ @Test func failedSetupDoesNotAsk() async {+ let host = FixtureHost()+ host.failSetup = "boom"+ let (_, fake) = await setUp(profile: "spare", host: host)+ #expect(fake.requests == 0)+ }++ @Test func launchOnAMacThatProvidesSpacesAsks() async throws {+ // A Mac set up earlier: the first status read at launch asks.+ let earlier = FixtureHost()+ _ = try await earlier.setupRequest(+ request: AppHostSetupRequest(mode: "relay", relayUrl: nil, direct: nil, name: nil, allow: nil,+ profile: "spare", shareDesktop: nil, provideSpaces: nil),+ accountToken: nil)+ let m = HostModel(host: FixtureHost(status: earlier.current))+ let fake = FakeLocalNetwork()+ m.localNetwork = fake+ await m.refresh()+ #expect(fake.requests == 1)+ }++ @Test func subnetHostIsTheFirstAddress() {+ let ip: UInt32 = 0xC0A8_0117 // 192.168.1.23+ #expect(LiveLocalNetworkPermission.subnetHost(ip: ip, mask: 0xFFFF_FF00) == "192.168.1.1")+ #expect(LiveLocalNetworkPermission.subnetHost(ip: 0xC0A8_0101, mask: 0xFFFF_FF00) == "192.168.1.2")+ #expect(LiveLocalNetworkPermission.subnetHost(ip: 0xA9FE_0102, mask: 0xFFFF_0000) == nil)+ #expect(LiveLocalNetworkPermission.subnetHost(ip: ip, mask: 0xFFFF_FFFF) == nil)+ }+}diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/OnboardingTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/OnboardingTests.swiftindex fcd668c478..45bb435100 100644--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/OnboardingTests.swift+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/OnboardingTests.swift@@ -51,10 +51,10 @@ struct TempInstall {}/// The SDK's installer (the app core's) over these paths only.- func installer(bundled: Bool = true) -> AppCliInstaller {+ func installer(bundled: Bool = true, pathEnv: String = "/usr/bin:/bin") -> AppCliInstaller {AppCliInstaller.withPaths(bundled: bundled ? cua.path : nil,binDir: home.appendingPathComponent(".local/bin").path,- pathEnv: "/usr/bin:/bin",+ pathEnv: pathEnv,profile: home.appendingPathComponent(".zshrc").path)}@@ -107,12 +107,38 @@ struct OnboardingTests {o.send(.driveContinue)o.send(.modeChosen(mode: .client))#expect(o.view.summary.first { $0.label == "cua command" }?.value == target)+ #expect(o.cliShadowedBy == nil, "nothing else on PATH")// A second launch finds it current and writes nothing new.let again = OnboardingModel(statePath: nil, cli: tmp.installer())await again.installCliSilently()#expect(again.cliPlan?.upToDate == true && again.state.cliTarget == target)}+ /// Another `cua` earlier on PATH (a stale Python cua-cli, say): Done+ /// still shows the installed path and notes the one that runs first.+ @Test func anotherCuaEarlierOnPathIsNotedOnDone() async throws {+ let tmp = try TempInstall()+ defer { tmp.remove() }+ let stale = tmp.root.appendingPathComponent("stale/bin")+ try FileManager.default.createDirectory(at: stale, withIntermediateDirectories: true)+ let other = stale.appendingPathComponent("cua")+ try Data("#!/bin/sh\necho \"cua-cli 0.1.0 (python)\"\n".utf8).write(to: other)+ try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: other.path)+ let binDir = tmp.home.appendingPathComponent(".local/bin").path+ let o = OnboardingModel(statePath: nil,+ cli: tmp.installer(pathEnv: "\(stale.path):\(binDir):/usr/bin:/bin"))+ #expect(o.cliShadowedBy == nil, "nothing installed yet")+ await o.installCliSilently()+ let target = tmp.home.appendingPathComponent(".local/bin/cua").path+ #expect(o.state.cliTarget == target)+ #expect(o.cliShadowedBy == other.path)+ o.send(.start)+ toMode(o)+ o.send(.modeChosen(mode: .client))+ #expect(o.view.step == .done)+ #expect(o.view.summary.first { $0.label == "cua command" }?.value == target, "Done shows the installed path")+ }+@Test func withoutABundledCliNothingIsInstalled() async throws {let tmp = try TempInstall()defer { tmp.remove() }@@ -180,6 +206,34 @@ struct OnboardingTests {#expect(l.view.usage?.on == false)}+ /// Sign-in skipped, then "Set up for access": the This machine step's+ /// own HostModel signs in inline through the app's sign-in (wired by+ /// AppModel), then finishes setup with the new session's token.+ @Test func skippedSignInSignsInInlineFromThisMachineThenFinishes() async {+ let host = FakeHost()+ let dir = FileManager.default.temporaryDirectory.appendingPathComponent("cua-mac-tests-\(UUID().uuidString)")+ defer { try? FileManager.default.removeItem(at: dir) }+ let o = OnboardingModel(statePath: nil, host: host)+ let account = FixtureAccount()+ let app = AppModel(backend: FixtureSpacesBackend(),+ keyvault: KeyvaultModel(client: nil, clock: { fixtureNow }),+ onboarding: o, settingsPath: dir.appendingPathComponent("settings.json").path,+ account: account, telemetry: FixtureTelemetry())+ o.accountToken = { _ in account.identity() == nil ? nil : "tok-signed-in" }+ o.send(.start)+ toMode(o)+ #expect(o.host.identity == nil)+ o.host.openForm()+ await o.setUpHost()+ #expect(app.identity == "[email protected]", "the app's sign-in ran")+ #expect(o.host.identity == "[email protected]")+ #expect(host.requests.count == 1)+ #expect(host.requests.first?.1 == "tok-signed-in")+ #expect(o.host.formView?.error == nil)+ #expect(o.view.step == .done)+ #expect(o.state.mode == .host)+ }+@Test func hostSetupRunsWithTheAccountTokenThenFinishes() async {let host = FakeHost()let o = model(host: host)diff --git a/docs/content/docs/cua-sdk/reference/auth.mdx b/docs/content/docs/cua-sdk/reference/auth.mdxindex 18d6b9931c..0a88d3762d 100644--- a/docs/content/docs/cua-sdk/reference/auth.mdx+++ b/docs/content/docs/cua-sdk/reference/auth.mdx@@ -26,7 +26,7 @@ Returned by [`Cua.auth`](/cua-sdk/reference/cua#cua).| --- | --- || [`access_token`](#authaccess_token) | A valid access token (refreshed when it expires within a minute, or when `force`). || [`begin_login`](#authbegin_login) | Starts a sign-in. |-| [`devices`](#authdevices) | This device on `relay_url` (`None` = `CUA_RELAY_URL`, else `https://relay.cua.ai`) as the signed-in account, shown as `name` (default: the host name). |+| [`devices`](#authdevices) | This device on `relay_url` (`None` = the relay `cua` uses: `CUA_RELAY_URL`, else this machine's host setup, else `https://relay.cua.ai`) as the signed-in account, shown as `name` (default: this computer's name). || [`logout`](#authlogout) | Revokes (best effort) and removes the session. || [`status`](#authstatus) | The stored session (no network). |@@ -132,9 +132,10 @@ pub async fn begin_login(&self, flow: Option<String>) -> Result<Arc<LoginAttempt### `Auth.devices`-This device on `relay_url` (`None` = `CUA_RELAY_URL`, else+This device on `relay_url` (`None` = the relay `cua` uses:+`CUA_RELAY_URL`, else this machine's host setup, else`https://relay.cua.ai`) as the signed-in account, shown as `name`-(default: the host name).+(default: this computer's name).<Tabs items={['Python', 'TypeScript', 'Swift', 'Kotlin', 'Rust']} groupId="sdk-lang" persist><Tab value="Python">@@ -295,10 +296,11 @@ Returned by [`Auth.begin_login`](#authbegin_login).Waits for the user, stores the session and returns who signed in.Only the first call waits; later calls fail.-A device that already enrolled (it has a device key) then-re-registers with the relay (`CUA_RELAY_URL`, else relay.cua.ai), so-the fresh sign-in enrolls or re-verifies it without an approval.-That step is best effort and never fails the sign-in.+This device then registers with the relay (the one `cua` uses:+`CUA_RELAY_URL`, else this machine's host setup, else relay.cua.ai),+creating its device key on first use, so the fresh sign-in enrolls+or re-verifies it without an approval. That step is best effort and+never fails the sign-in.<Tabs items={['Python', 'TypeScript', 'Swift', 'Kotlin', 'Rust']} groupId="sdk-lang" persist><Tab value="Python">diff --git a/docs/content/docs/cua-sdk/reference/rust/cua-spaces.mdx b/docs/content/docs/cua-sdk/reference/rust/cua-spaces.mdxindex eb41793b22..9498a34e02 100644--- a/docs/content/docs/cua-sdk/reference/rust/cua-spaces.mdx+++ b/docs/content/docs/cua-sdk/reference/rust/cua-spaces.mdx@@ -1597,6 +1597,7 @@ pub struct SpaceInfo {pub cloud: String,pub cloud_place: String,pub cloud_delete: String,+ pub status: String,}```diff --git a/docs/content/docs/cua-sdk/reference/spaces/host.mdx b/docs/content/docs/cua-sdk/reference/spaces/host.mdxindex 1991566e58..dfcd989629 100644--- a/docs/content/docs/cua-sdk/reference/spaces/host.mdx+++ b/docs/content/docs/cua-sdk/reference/spaces/host.mdx@@ -364,7 +364,7 @@ The signed-in account's view of a cua-relay.| Method | Description || --- | --- |-| [`new`](#relaynew) | A relay (`None` = `CUA_RELAY_URL`, else `https://relay.cua.ai`) seen as the account behind `account_token` (a cua.ai access token). |+| [`new`](#relaynew) | A relay (`None` = the relay `cua` uses: `CUA_RELAY_URL`, else this machine's host setup, else `https://relay.cua.ai`) seen as the account behind `account_token` (a cua.ai access token). || [`connect`](#relayconnect) | Connects to a machine's spacesd through `<relay>/m/<id>`, with the account token as bearer (the relay swaps it for its signed identity). || [`machine`](#relaymachine) | One machine. || [`machines`](#relaymachines) | Machines the account owns or that are shared with it. |@@ -377,8 +377,9 @@ The signed-in account's view of a cua-relay.### `Relay.new`-A relay (`None` = `CUA_RELAY_URL`, else `https://relay.cua.ai`) seen-as the account behind `account_token` (a cua.ai access token).+A relay (`None` = the relay `cua` uses: `CUA_RELAY_URL`, else this+machine's host setup, else `https://relay.cua.ai`) seen as the+account behind `account_token` (a cua.ai access token).<Tabs items={['Python', 'TypeScript', 'Swift', 'Kotlin', 'Rust']} groupId="sdk-lang" persist><Tab value="Python">diff --git a/libs/cua-spacesd/crates/cua-relay/README.md b/libs/cua-spacesd/crates/cua-relay/README.mdindex de7839435e..224665d6ef 100644--- a/libs/cua-spacesd/crates/cua-relay/README.md+++ b/libs/cua-spacesd/crates/cua-relay/README.md@@ -77,20 +77,33 @@ state of this work.60 s) that the machine verifies with the relay's key(`/.well-known/jwks.json`, also sent on the join handshake).- **Device enrollment.** A device that lists or reaches an account's- machines holds a P-256 key (OS keychain, or a `0600` file) and is enrolled- with a second factor: a fresh interactive sign-in (`auth_time` at most 10- minutes old; for any device after the account's first, also a verified- email), or approval from an enrolled device by one-time code or device- id. Devices report a machine id (a hash of the host's hardware or install- identity, stored keyed per account): when a new key of the same machine- enrolls, it replaces the machine's older records (revoked as superseded,- audited as `device_rekeyed`, left out of listings), so switching builds or- losing a key does not leave duplicates. The machine id never enrolls- anything on its own. Enrollment lasts 30 days, then one approval or fresh- sign-in re-verifies it. Per session the device signs a timestamp+ machines holds a P-256 key (OS keychain, or a `0600` file) and is+ enrolled by a fresh interactive sign-in (`auth_time` at most 10 minutes+ old, plus proof of the device key) or by approval from an enrolled device+ (one-time code or device id). By default a fresh sign-in enrolls any+ device of the account, the way signing in adds a device to a tailnet:+ whoever can complete the account's sign-in already is the account, so the+ defences sit at sign-in (the identity provider's MFA) and in what a+ stolen credential cannot do here -- a refreshed or long-lived token never+ enrolls, a token without the device key opens no session, every+ enrollment is audited with how it happened (a new device by sign-in is+ `device_enrolled` / `bootstrap:fresh-sign-in`, "new device of the+ account"), and any enrolled device revokes another at once.+ `CUA_RELAY_DEVICE_REQUIRE_APPROVAL=true` restores the strict policy: a+ fresh sign-in then enrolls only the account's first device, a re-key of a+ machine it already has, or (verified email) a sign-in proving MFA; other+ new devices wait for an approval. Devices report a machine id (a hash of+ the host's hardware or install identity, stored keyed per account): when+ a new key of the same machine enrolls, it replaces the machine's older+ records (revoked as superseded, audited as `device_rekeyed`, left out of+ listings), so switching builds or losing a key does not leave duplicates.+ The machine id never enrolls anything on its own. Enrollment lasts 30+ days and slides while the device is in use (each session moves the end to+ 30 days from then); a device unused for 30 days needs a fresh sign-in or+ one approval again. Per session the device signs a timestamp(`POST /v1/devices/session`) and sends the token as `x-cua-device-session`.- For 14 days after enrollment is first turned on, devices signed in from- before keep access, flagged and audited.+ During a migration grace period (`CUA_RELAY_DEVICE_GRACE_DAYS`, none by+ default), devices signed in from before keep access, flagged and audited.- **Audit.** Every enrollment change, device session, machine access, sharechange, registration and sharing stop is recorded in the account's auditlog (`GET /v1/audit`, `cua devices audit`), bounded and persisted with the@@ -211,9 +224,10 @@ register machines: `CUA_RELAY_TOKENS`/`CUA_RELAY_TOKEN_FILE` or| `CUA_RELAY_DEVICES_FILE` | next to the state file | Devices and audit log (`machines.json` gives `machines.devices.json`; in memory without a state file). Its audit hash-chain key (S9) is generated alongside it, 0600, at `<devices file>.audit-key`; back this file up with the devices file, or the chain from before a restore stops verifying (a fresh key generates rather than fail closed, since a lost audit key must not mean a lost relay). || `CUA_RELAY_MAX_MACHINES_PER_ACCOUNT` | `32` | Machines one account may register. || `CUA_RELAY_DEVICE_ENROLLMENT` | `on` | Require enrolled client devices (`on` / `off`). |-| `CUA_RELAY_DEVICE_TTL_DAYS` | `30` | Days an enrollment lasts. |+| `CUA_RELAY_DEVICE_TTL_DAYS` | `30` | Days an enrollment lasts without use (each device session renews it). || `CUA_RELAY_DEVICE_GRACE_DAYS` | `0` (ended) | Days unenrolled devices keep access after enrollment is first on. Set this only for a time-boxed rollout window (S3): a stolen account token alone reaches every machine while it is open. || `CUA_RELAY_DEVICE_BOOTSTRAP_MAX_AUTH_AGE_SECS` | `600` | Max sign-in age that enrolls a device without an approval. |+| `CUA_RELAY_DEVICE_REQUIRE_APPROVAL` | off | Strict enrollment: a fresh sign-in enrolls only an account's first device, a re-key of a known machine, or (verified email) a sign-in proving MFA; other new devices need an approval from an enrolled device. || `CUA_RELAY_TOKENS` | unset | Static mode: comma-separated registration tokens. || `CUA_RELAY_TOKEN_FILE` | unset | Static mode: one token per line (`#` comments). || `CUA_RELAY_MAX_MACHINES_PER_TOKEN` | `16` | Static mode: machines per registration token. |diff --git a/libs/cua-spacesd/crates/cua-relay/src/device_api.rs b/libs/cua-spacesd/crates/cua-relay/src/device_api.rsindex 761a1ee131..a743e8943a 100644--- a/libs/cua-spacesd/crates/cua-relay/src/device_api.rs+++ b/libs/cua-spacesd/crates/cua-relay/src/device_api.rs@@ -59,7 +59,7 @@ impl Gate {/// The error an unenrolled device gets once the grace period is over.pub const NOT_ENROLLED: &str =- "this device is not enrolled for your cua.ai account: run `cua devices enroll` (or approve it from the Cua Spaces app on an enrolled device)";+ "this device is not enrolled for your cua.ai account: sign in again (`cua auth login`) to enroll it, run `cua devices enroll`, or approve it from the Cua Spaces app on an enrolled device";/// Checks the device behind an account request: an enrolled device's live/// session, else (during the grace period) a flagged pass, else an error.diff --git a/libs/cua-spacesd/crates/cua-relay/src/devices.rs b/libs/cua-spacesd/crates/cua-relay/src/devices.rsindex b75d50cd5e..1a4a30ca4f 100644--- a/libs/cua-spacesd/crates/cua-relay/src/devices.rs+++ b/libs/cua-spacesd/crates/cua-relay/src/devices.rs@@ -5,38 +5,66 @@//!//! A device that acts as a client of an account (lists its machines,//! connects to them) holds a P-256 key pair (the OS keychain on macOS and-//! Windows, a 0600 file elsewhere) and is enrolled with a second factor:+//! Windows, a 0600 file elsewhere) and is enrolled one of two ways://!+//! - a fresh interactive sign-in: the account token's `auth_time` is no+//! older than the bootstrap window ([`DevicePolicy::bootstrap_max_auth_age_secs`],+//! 10 minutes by default), plus proof of the device key. By default this+//! enrolls *any* device of the account at once -- its first, a re-key of a+//! machine it already has, or a brand-new one -- the way signing in adds a+//! device to a tailnet. A brand-new device enrolled so is audited as+//! `device_enrolled` by [`BY_FRESH_SIGN_IN`] with a detail naming it a+//! new device of the account;//! - approval from an already enrolled device of the same account, by the//! one-time code the new device shows or by picking it from the pending-//! list;-//! - a fresh interactive sign-in (`auth_time` of the account token no older-//! than the bootstrap window), plus proof of the device key, the way-//! signing in adds a device to a tailnet. Three cases need no approval:-//! an account's first device (or its only one, after it expired); a-//! re-key of a machine that already has a live device on the account-//! (same machine id, a new key -- another build, or the old key was-//! lost); and, for a verified email, a token whose authentication context-//! proves a second factor (`acr`/`amr`; see [`crate::oidc::Identity::mfa`]).-//! A brand-new device on an account that already has a strong enrolled-//! device, from a sign-in that does not prove a second factor, still-//! needs an approval: a verified email alone is not enough (closes the-//! "any account compromise silently enrolls a device" gap). During the-//! migration grace period (ended by default; see [`DevicePolicy::grace_secs`])-//! an account with no enrolled device may also bootstrap without a fresh-//! sign-in (audited).+//! list. A device on a long-lived (refreshed) session -- no fresh+//! `auth_time` -- always needs this.+//!+//! Why a fresh sign-in alone is enough by default: whoever can complete an+//! interactive sign-in to the account already *is* the account to the+//! identity provider; requiring a second device to approve the first does+//! not stop an account takeover, it only makes the owner's own second Mac+//! wait for a code (and an identity provider that does not mark a social+//! login's email verified, or report `amr`, made that the common case).+//! Account compromise is sign-in compromise, and the defences belong+//! there (the IdP's MFA and session policy). The relay narrows what a+//! stolen credential can do: a refreshed or long-lived token cannot enroll+//! (fresh `auth_time` only), a stolen token without the device key cannot+//! open a session (key proof per session), every enrollment is audited+//! with how it happened, any enrolled device can revoke another (ending its+//! sessions at once), and a relay may switch to the stricter policy.+//!+//! The strict policy ([`DevicePolicy::require_approval`],+//! `--device-require-approval` / `CUA_RELAY_DEVICE_REQUIRE_APPROVAL`, off by+//! default) restores approval for brand-new devices: a fresh sign-in then+//! enrolls only an account's first device (or its only one, after it+//! expired; while no device enrolled through a real second factor exists),+//! a re-key of a machine that already has a live device on the account+//! (same machine id, a new key), and, for a verified email, a token whose+//! authentication context proves a second factor (`acr`/`amr`; see+//! [`crate::oidc::Identity::mfa`]). Any other new device waits for an+//! approval.+//!+//! During the migration grace period (ended by default; see+//! [`DevicePolicy::grace_secs`]) an account with no enrolled device may also+//! bootstrap without a fresh sign-in (audited).//!//! A device may report a machine id (a hash of the host's hardware or//! install identity, keyed per account here). When a new key of the same//! machine enrolls (another build of the app keeps its own key, the key was//! lost), it replaces the machine's older records: they are revoked as//! superseded, their sessions end, and listings show the machine once. The-//! machine id is a claim, never a factor for *whom* it replaces; it is,-//! however, one of the ways a fresh sign-in alone is allowed to enroll-//! without an approval (a re-key of a machine the account already trusts).+//! machine id is a claim, never a factor for *whom* it replaces; under the+//! strict policy it is, however, one of the ways a fresh sign-in alone is+//! allowed to enroll without an approval (a re-key of a machine the account+//! already trusts).//!-//! Enrollment lasts `device_ttl` (30 days by default); after that the device-//! needs one approval or a fresh sign-in again. Per session the device proves its key+//! Enrollment lasts `device_ttl` (30 days by default) and slides while the+//! device is in use: each session it opens (a proof of its key) moves the+//! end to `device_ttl` from then, persisted when that moves it by more than+//! [`RENEW_STEP_SECS`]. A device unused for `device_ttl` expires and needs+//! one approval or a fresh sign-in again; a session never revives an+//! expired device. Per session the device proves its key//! (`POST /v1/devices/session`, a signed timestamp) and gets a short-lived//! opaque session token it sends as `x-cua-device-session` with its account//! token. Hosts are never involved: a hosted-only machine registers with its@@ -77,6 +105,10 @@ pub const ACCESS_AUDIT_INTERVAL_SECS: u64 = 600;pub const MAX_DEVICES_PER_ACCOUNT: usize = 64;/// `enrolled_by` of a device enrolled by a fresh interactive sign-in.pub const BY_FRESH_SIGN_IN: &str = "bootstrap:fresh-sign-in";+/// Minimum move of `enrolled_until` that a session's sliding renewal+/// records (at most half the TTL), so an active device is not rewritten+/// for every session.+pub const RENEW_STEP_SECS: u64 = 86_400;/// `enrolled_by` of a device enrolled during the migration grace period.pub const BY_GRACE: &str = "bootstrap:grace";@@ -554,6 +586,11 @@ pub struct DevicePolicy {pub bootstrap_max_auth_age_secs: u64,/// Device session lifetime.pub session_ttl_secs: u64,+ /// Strict policy: a fresh sign-in enrolls only an account's first+ /// device, a re-key of a machine it already has, or (verified email) a+ /// sign-in proving MFA; other new devices need an approval. Off by+ /// default: a fresh sign-in enrolls any device of the account.+ pub require_approval: bool,}impl Default for DevicePolicy {@@ -568,6 +605,7 @@ impl Default for DevicePolicy {grace_secs: 0,bootstrap_max_auth_age_secs: 600,session_ttl_secs: 3600,+ require_approval: false,}}}@@ -944,11 +982,12 @@ impl DeviceStore {////// - A revoked key never comes back./// - `bootstrap` asks to enroll without an approval. A fresh sign-in- /// (`auth_time` within the bootstrap window) grants it: for the- /// account's first device (while no device enrolled through a real- /// second factor exists), and for any other device when the account's- /// email is verified. During the migration grace period an account- /// with no enrolled device bootstraps without one.+ /// (`auth_time` within the bootstrap window) grants it for any device+ /// of the account; under [`DevicePolicy::require_approval`] only for+ /// the account's first device (while no device enrolled through a+ /// real second factor exists), a re-key of a known machine, or a+ /// verified email with MFA. During the migration grace period an+ /// account with no enrolled device bootstraps without one./// - A fresh sign-in newer than an enrolled device's enrollment/// re-verifies it; otherwise an enrolled device stays as it is./// - Else the device is (again) pending with a fresh one-time code.@@ -1064,21 +1103,31 @@ impl DeviceStore {.values().any(|d| d.account == account && d.id != id && d.revoked_at.is_none() && d.machine.as_deref() == Some(m))});- // A fresh sign-in enrolls: the first device (while no device- // enrolled through a real second factor exists, so an owner can- // recover from devices someone enrolled on the grace period's- // word, and revoke them); a re-key of an already-enrolled- // machine; and, for a brand-new device on an account that- // already has a strong enrolled device, only when the token- // also proves a second factor (`Identity::mfa`) -- a verified- // email alone is no longer enough for that case (S4). The other- // route for a brand-new device is an approval from an enrolled- // device ([`Self::approve`]). The grace period bootstraps only- // an account's very first device.+ // A brand-new device of an account that already has an enrolled+ // device: never enrolled before, not a re-key of a known machine.+ let new_device = device.enrolled_at.is_none()+ && !is_rekey+ && Self::has_enrolled(state, account, now, false);+ // By default a fresh sign-in (plus the key proof checked above)+ // enrolls any device of the account, the way signing in adds a+ // device to a tailnet: account compromise is sign-in+ // compromise, and a refreshed / long-lived token never counts+ // as fresh. Under the strict policy (`require_approval`) it+ // enrolls only: the first device (while no device enrolled+ // through a real second factor exists, so an owner can recover+ // from devices someone enrolled on the grace period's word, and+ // revoke them); a re-key of an already-enrolled machine; and,+ // for a brand-new device on an account that already has a+ // strong enrolled device, a token that also proves a second+ // factor (`Identity::mfa`) with a verified email (S4). The+ // other route for a brand-new device is an approval from an+ // enrolled device ([`Self::approve`]). The grace period+ // bootstraps only an account's very first device.let by = if !r.bootstrap {None} else if fresh_sign_in.is_some()- && (enrolled+ && (!policy.require_approval+ || enrolled|| is_rekey|| !Self::has_enrolled(state, account, now, true)|| (r.email_verified && r.mfa))@@ -1102,9 +1151,12 @@ impl DeviceStore {AuditEvent::new("device_enrolled").device(Some(&id)).subject(by)- .detail(match (by, enrolled) {- (BY_FRESH_SIGN_IN, true) => "re-verified by fresh sign-in",- (BY_FRESH_SIGN_IN, false) => "enrolled by fresh sign-in",+ .detail(match (by, enrolled, new_device) {+ (BY_FRESH_SIGN_IN, true, _) => "re-verified by fresh sign-in",+ (BY_FRESH_SIGN_IN, false, true) => {+ "enrolled by fresh sign-in (new device of the account)"+ }+ (BY_FRESH_SIGN_IN, false, false) => "enrolled by fresh sign-in",_ => "enrolled during the grace period",}),&audit_key,@@ -1229,6 +1281,12 @@ impl DeviceStore {/// Opens a device session: `sig` over [`session_message`] with the/// device key. Returns the session token and its expiry.+ ///+ /// The session renews an enrolled device's enrollment (sliding): its+ /// end moves to `ttl` from now, recorded when that moves it by more+ /// than [`RENEW_STEP_SECS`] (at most half the TTL), so a device in use+ /// does not expire. An expired, pending or revoked device gets no+ /// session and is not renewed.pub fn open_session(&self,account: &str,@@ -1246,46 +1304,63 @@ impl DeviceStore {let until = match record.state(now) {DeviceState::Enrolled => record.enrolled_until.unwrap_or(now),DeviceState::Pending => {- return Err(DeviceError::Forbidden(- "this device is waiting for approval from an enrolled device".into(),- ))+ return Err(DeviceError::Forbidden(if self.policy.require_approval {+ "this device is waiting for approval from an enrolled device".into()+ } else {+ "this device is not enrolled yet: sign in again (`cua auth login`) to enroll it, or approve it from an enrolled device".into()+ }))}DeviceState::Expired => {- return Err(DeviceError::Forbidden(- "this device needs re-verification: approve it from an enrolled device".into(),- ))+ return Err(DeviceError::Forbidden(if self.policy.require_approval {+ "this device needs re-verification: approve it from an enrolled device".into()+ } else {+ "this device's enrollment expired after a period without use: sign in again (`cua auth login`) to re-verify it, or approve it from an enrolled device".into()+ }))}DeviceState::Revoked => {return Err(DeviceError::Forbidden("this device was revoked".into()))}};+ let ttl = self.policy.ttl_secs;+ let step = RENEW_STEP_SECS.min(ttl / 2);+ let audit_key = self.audit_key;+ let until = self+ .mutate(|state| {+ let mut until = until;+ if let Some(d) = state.devices.get_mut(device) {+ d.last_seen = Some(now);+ // Re-checked under the lock: revoked or expired since+ // the read above stays as it is.+ if d.state(now) == DeviceState::Enrolled {+ let current = d.enrolled_until.unwrap_or(now);+ let renewed = now + ttl;+ if renewed > current.saturating_add(step) {+ d.enrolled_until = Some(renewed);+ }+ until = d.enrolled_until.unwrap_or(until);+ }+ }+ Self::push_audit(+ state,+ account,+ AuditEvent::new("device_session").device(Some(device)),+ &audit_key,+ );+ Ok(until)+ })+ .unwrap_or(until);let expires = (now + self.policy.session_ttl_secs).min(until);let token = new_session_token();- {- let mut sessions = self.sessions.lock().expect("sessions");- sessions.retain(|_, s| s.expires > now);- sessions.insert(- sha256_hex(&token),- Session {- account: account.to_owned(),- device: device.to_owned(),- expires,- },- );- }- let audit_key = self.audit_key;- let _ = self.mutate(|state| {- if let Some(d) = state.devices.get_mut(device) {- d.last_seen = Some(now);- }- Self::push_audit(- state,- account,- AuditEvent::new("device_session").device(Some(device)),- &audit_key,- );- Ok(())- });+ let mut sessions = self.sessions.lock().expect("sessions");+ sessions.retain(|_, s| s.expires > now);+ sessions.insert(+ sha256_hex(&token),+ Session {+ account: account.to_owned(),+ device: device.to_owned(),+ expires,+ },+ );Ok((token, expires))}@@ -1512,10 +1587,9 @@ pub(crate) mod tests {// The session is bound to its account.assert!(store.session_device("other", &token).is_none());- // Without a verified email, a second device cannot bootstrap, even- // with a fresh sign-in.+ // On a long-lived session a second device cannot bootstrap.let second = TestKey::new();- let pending = register(&store, "acct", &second, true, Some(now_secs())).unwrap();+ let pending = register(&store, "acct", &second, true, Some(now_secs() - 3600)).unwrap();assert_eq!(pending.device.state(now_secs()), DeviceState::Pending);let code = pending.code.unwrap();// ...until an enrolled device confirms its code.@@ -1574,8 +1648,13 @@ pub(crate) mod tests {#[test]fn a_fresh_sign_in_recovers_from_devices_enrolled_on_the_grace_periods_word() {- // During the grace period someone with a stolen session enrolls first.- let store = DeviceStore::in_memory(with_grace());+ // During the grace period someone with a stolen session enrolls+ // first. (Strict policy: by default a fresh sign-in enrolls any+ // device, so the last step below is strict-only.)+ let store = DeviceStore::in_memory(DevicePolicy {+ require_approval: true,+ ..with_grace()+ });let thief = TestKey::new();let r = register(&store, "acct", &thief, true, None).unwrap();assert_eq!(r.device.enrolled_by.as_deref(), Some("bootstrap:grace"));@@ -1999,13 +2078,195 @@ pub(crate) mod tests {assert_eq!(enrolled.subject.as_deref(), Some(BY_FRESH_SIGN_IN));assert_eq!(enrolled.detail.as_deref(),- Some("enrolled by fresh sign-in")+ Some("enrolled by fresh sign-in (new device of the account)"));}+ /// The default policy: a fresh interactive sign-in enrolls another+ /// device of the account at once, whether or not the issuer marked the+ /// email verified or the token proves MFA (a social login on Keycloak:+ /// `acr` "1", no `amr`, `email_verified` false).#[test]- fn a_brand_new_device_needs_mfa_or_approval_once_the_account_has_a_strong_device() {+ fn a_fresh_sign_in_enrolls_a_second_device_without_verified_email_or_mfa() {let store = DeviceStore::in_memory(enforcing());+ assert!(!store.policy().require_approval);+ let first = TestKey::new();+ register(&store, "acct", &first, true, Some(now_secs())).unwrap();+ assert!(store.get(&first.id()).unwrap().strong);+ // Seconds-old sign-in on a second Mac: enrolled, no code.+ let second = TestKey::new();+ let r = register(&store, "acct", &second, true, Some(now_secs() - 5)).unwrap();+ assert_eq!(r.device.state(now_secs()), DeviceState::Enrolled);+ assert_eq!(r.device.enrolled_by.as_deref(), Some(BY_FRESH_SIGN_IN));+ assert!(r.code.is_none());+ assert!(r.superseded.is_empty());+ assert!(session(&store, "acct", &second).is_ok());+ assert!(store.get(&first.id()).unwrap().revoked_at.is_none());+ let log = store.audit_log("acct", 100);+ let enrolled = log.iter().rfind(|e| e.kind == "device_enrolled").unwrap();+ assert_eq!(enrolled.device.as_deref(), Some(second.id().as_str()));+ assert_eq!(enrolled.subject.as_deref(), Some(BY_FRESH_SIGN_IN));+ assert_eq!(+ enrolled.detail.as_deref(),+ Some("enrolled by fresh sign-in (new device of the account)")+ );+ // The account's first device was not a "new device of the account".+ let first_enrolled = log.iter().find(|e| e.kind == "device_enrolled").unwrap();+ assert_eq!(+ first_enrolled.detail.as_deref(),+ Some("enrolled by fresh sign-in")+ );+ // A long-lived (refreshed) session still needs an approval, as does+ // a token without auth_time or a register that did not ask.+ let third = TestKey::new();+ let stale = register(&store, "acct", &third, true, Some(now_secs() - 3600)).unwrap();+ assert_eq!(stale.device.state(now_secs()), DeviceState::Pending);+ assert!(stale.code.is_some());+ assert!(register(&store, "acct", &third, true, None)+ .unwrap()+ .code+ .is_some());+ assert!(register(&store, "acct", &third, false, Some(now_secs()))+ .unwrap()+ .code+ .is_some());+ assert!(session(&store, "acct", &third).is_err());+ // Just past the bootstrap window is stale too.+ let window = store.policy().bootstrap_max_auth_age_secs;+ assert!(+ register(&store, "acct", &third, true, Some(now_secs() - window - 5))+ .unwrap()+ .code+ .is_some()+ );+ }++ /// `require_approval` restores the strict rule: a fresh sign-in enrolls+ /// the first device, but a brand-new second one needs an approval+ /// unless the token proves MFA with a verified email.+ #[test]+ fn the_strict_switch_requires_approval_for_a_brand_new_device() {+ let store = DeviceStore::in_memory(DevicePolicy {+ require_approval: true,+ ..enforcing()+ });+ let first = TestKey::new();+ let r = register(&store, "acct", &first, true, Some(now_secs())).unwrap();+ assert_eq!(r.device.state(now_secs()), DeviceState::Enrolled);+ let second = TestKey::new();+ let pending = register(&store, "acct", &second, true, Some(now_secs())).unwrap();+ assert_eq!(pending.device.state(now_secs()), DeviceState::Pending);+ assert!(pending.code.is_some());+ let err = session(&store, "acct", &second).unwrap_err();+ assert!(+ matches!(&err, DeviceError::Forbidden(m) if m.contains("waiting for approval")),+ "{err:?}"+ );+ // Verified email alone is not enough; with MFA it is.+ let r = register_on(+ &store,+ "acct",+ &second,+ true,+ Some(now_secs()),+ true,+ None,+ false,+ )+ .unwrap();+ assert!(r.code.is_some());+ let r = register_on(+ &store,+ "acct",+ &second,+ true,+ Some(now_secs()),+ true,+ None,+ true,+ )+ .unwrap();+ assert_eq!(r.device.state(now_secs()), DeviceState::Enrolled);+ // Or an approval from an enrolled device.+ let third = TestKey::new();+ let code = register(&store, "acct", &third, true, Some(now_secs()))+ .unwrap()+ .code+ .unwrap();+ store+ .approve("acct", &first.id(), Some(&code), None)+ .unwrap();+ assert!(session(&store, "acct", &third).is_ok());+ }++ /// A session renews the enrollment (sliding), persisting only a move+ /// worth recording, and never revives an expired device.+ #[test]+ fn a_session_slides_the_enrollment_but_does_not_revive_an_expired_device() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("devices.json");+ let store = DeviceStore::open(path.clone(), enforcing()).unwrap();+ let ttl = store.policy().ttl_secs;+ let key = TestKey::new();+ register(&store, "acct", &key, true, Some(now_secs())).unwrap();+ let set_until = |until: u64| {+ store+ .state+ .lock()+ .unwrap()+ .devices+ .get_mut(&key.id())+ .unwrap()+ .enrolled_until = Some(until);+ };+ let until = || store.get(&key.id()).unwrap().enrolled_until.unwrap();+ // Three days left: a session moves the end to a full TTL from now,+ // on disk too.+ set_until(now_secs() + 3 * 86_400);+ session(&store, "acct", &key).unwrap();+ let renewed = until();+ assert!(renewed + 5 >= now_secs() + ttl, "{renewed}");+ let reopened = DeviceStore::open(path.clone(), enforcing()).unwrap();+ assert_eq!(+ reopened.get(&key.id()).unwrap().enrolled_until,+ Some(renewed)+ );+ drop(reopened);+ // Within a day of a full TTL: left as it is.+ let near = now_secs() + ttl - 3600;+ set_until(near);+ session(&store, "acct", &key).unwrap();+ assert_eq!(until(), near);+ // Expired: no session, no renewal; re-verification is still due.+ let past = now_secs() - 1;+ set_until(past);+ let err = session(&store, "acct", &key).unwrap_err();+ assert!(+ matches!(&err, DeviceError::Forbidden(m) if m.contains("sign in again")),+ "{err:?}"+ );+ assert_eq!(until(), past);+ assert_eq!(+ store.get(&key.id()).unwrap().state(now_secs()),+ DeviceState::Expired+ );+ // A revoked device is not renewed either.+ let other = TestKey::new();+ register(&store, "acct", &other, true, Some(now_secs())).unwrap();+ set_until(now_secs() + 3 * 86_400);+ session(&store, "acct", &key).unwrap();+ store.revoke("acct", &other.id(), &key.id()).unwrap();+ let revoked_until = until();+ assert!(session(&store, "acct", &key).is_err());+ assert_eq!(until(), revoked_until);+ }++ #[test]+ fn strict_a_brand_new_device_needs_mfa_or_approval_once_the_account_has_a_strong_device() {+ let store = DeviceStore::in_memory(DevicePolicy {+ require_approval: true,+ ..enforcing()+ });let first = TestKey::new();register_on(&store,diff --git a/libs/cua-spacesd/crates/cua-relay/src/main.rs b/libs/cua-spacesd/crates/cua-relay/src/main.rsindex 5885437792..877311299e 100644--- a/libs/cua-spacesd/crates/cua-relay/src/main.rs+++ b/libs/cua-spacesd/crates/cua-relay/src/main.rs@@ -94,7 +94,8 @@ struct Args {/// Account mode: require enrolled client devices (`on` / `off`).#[arg(long, env = "CUA_RELAY_DEVICE_ENROLLMENT", default_value = "on")]device_enrollment: String,- /// Days a device enrollment lasts before one approval re-verifies it.+ /// Days a device enrollment lasts without use (each session renews it)+ /// before a fresh sign-in or one approval re-verifies it.#[arg(long, env = "CUA_RELAY_DEVICE_TTL_DAYS", default_value_t = 30)]device_ttl_days: u64,/// Days after the first start with device enrollment during which@@ -111,6 +112,13 @@ struct Args {default_value_t = 600)]device_bootstrap_max_auth_age_secs: u64,+ /// Strict enrollment: a fresh sign-in enrolls only an account's first+ /// device, a re-key of a machine it already has, or (verified email) a+ /// sign-in proving MFA; any other new device needs an approval from an+ /// enrolled device. Off by default: a fresh sign-in enrolls any device+ /// of the account.+ #[arg(long, env = "CUA_RELAY_DEVICE_REQUIRE_APPROVAL")]+ device_require_approval: bool,/// Devices and audit log file (default: `<state file>.devices.json`).#[arg(long, env = "CUA_RELAY_DEVICES_FILE")]devices_file: Option<std::path::PathBuf>,@@ -217,6 +225,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {ttl_secs: args.device_ttl_days.max(1) * 86_400,grace_secs: args.device_grace_days * 86_400,bootstrap_max_auth_age_secs: args.device_bootstrap_max_auth_age_secs,+ require_approval: args.device_require_approval,..cua_relay::devices::DevicePolicy::default()},devices_file: args.devices_file,diff --git a/libs/cua-spacesd/crates/cua-relay/tests/device_enrollment.rs b/libs/cua-spacesd/crates/cua-relay/tests/device_enrollment.rsindex c329c83665..3ac38f7557 100644--- a/libs/cua-spacesd/crates/cua-relay/tests/device_enrollment.rs+++ b/libs/cua-spacesd/crates/cua-relay/tests/device_enrollment.rs@@ -23,15 +23,23 @@ fn now() -> u64 {}async fn start(issuer: &FakeIssuer, grace_secs: u64) -> String {+ start_with(+ issuer,+ DevicePolicy {+ grace_secs,+ ..DevicePolicy::default()+ },+ )+ .await+}++async fn start_with(issuer: &FakeIssuer, device_policy: DevicePolicy) -> String {let relay = Relay::new(RelayConfig {oidc: Some(Arc::new(OidcValidator::with_jwks(OidcConfig::new(ISSUER),issuer.jwks(),))),- device_policy: DevicePolicy {- grace_secs,- ..DevicePolicy::default()- },+ device_policy,..RelayConfig::default()});let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();@@ -716,26 +724,15 @@ async fn a_fresh_sign_in_enrolls_this_device_and_replaces_its_old_key() {.collect();assert_eq!(ids, std::slice::from_ref(&signed.id));- // A brand-new machine, from a session that does not prove a second- // factor: a verified email is no longer enough on its own once the- // account has a strong enrolled device (S4). It waits for approval.+ // A brand-new machine, from the same fresh sign-in (no MFA proof):+ // enrolled at once by default, keeping both machines.let laptop = Device::new();let r = laptop.register_on(&base, &again, true, Some("linux-machine-id-hash")).await;- assert_eq!(r["device"]["state"], "pending");- assert!(r["code"].is_string());-- // The same sign-in, now proving MFA (Keycloak `amr`), enrolls it at- // once and keeps both machines.- issuer.set_amr("ada", &["otp"]);- let mfa_signed_in = issuer.token("ada", Some("[email protected]"), "cua-relay", 300);- let r = laptop- .register_on(&base, &mfa_signed_in, true, Some("linux-machine-id-hash"))- .await;assert_eq!(r["device"]["state"], "enrolled");+ assert!(r["code"].is_null());assert_eq!(r["superseded"], json!([]));- issuer.set_amr("ada", &[]);// The audit log says how each device got in.let audit: Value = get(&base, "/v1/audit", &again, Some(&s_new))@@ -746,13 +743,27 @@ async fn a_fresh_sign_in_enrolls_this_device_and_replaces_its_old_key() {let events = audit["events"].as_array().unwrap();let by_sign_in: Vec<_> = events.iter()- .filter(|e| e["kind"] == "device_enrolled" && e["detail"] == "enrolled by fresh sign-in")+ .filter(|e| {+ e["kind"] == "device_enrolled"+ && e["detail"]+ .as_str()+ .is_some_and(|d| d.starts_with("enrolled by fresh sign-in"))+ }).map(|e| e["device"].as_str().unwrap().to_owned()).collect();assert_eq!(by_sign_in,[unsigned.id.clone(), signed.id.clone(), laptop.id.clone()]);+ let new_device = events+ .iter()+ .find(|e| e["kind"] == "device_enrolled" && e["device"] == laptop.id.as_str())+ .unwrap();+ assert_eq!(new_device["subject"], "bootstrap:fresh-sign-in");+ assert_eq!(+ new_device["detail"],+ "enrolled by fresh sign-in (new device of the account)"+ );let rekeyed = events.iter().find(|e| e["kind"] == "device_rekeyed")@@ -761,12 +772,47 @@ async fn a_fresh_sign_in_enrolls_this_device_and_replaces_its_old_key() {assert_eq!(rekeyed["subject"], unsigned.id.as_str());}+/// The dogfood case: a social login whose email the issuer does not mark+/// verified, no `amr`. A fresh sign-in on a second machine enrolls it; a+/// long-lived session still shows a code.#[tokio::test]-async fn an_unverified_email_needs_an_approval_for_further_devices() {+async fn a_fresh_sign_in_enrolls_further_devices_of_an_unverified_email() {let issuer = FakeIssuer::new(ISSUER);let base = start(&issuer, 0).await;issuer.set_auth_time("eve", now() as i64);let unverified = issuer.token_with("eve", Some("[email protected]"), false, "cua-relay", 300);+ let first = Device::new();+ let r = first.register(&base, &unverified, true).await;+ assert_eq!(r["device"]["state"], "enrolled");+ let second = Device::new();+ let r = second.register(&base, &unverified, true).await;+ assert_eq!(r["device"]["state"], "enrolled");+ assert_eq!(r["device"]["enrolled_by"], "bootstrap:fresh-sign-in");+ assert!(r["code"].is_null());+ assert!(second.session(&base, &unverified).await.is_ok());+ issuer.set_auth_time("eve", now() as i64 - 3600);+ let stale = issuer.token_with("eve", Some("[email protected]"), false, "cua-relay", 300);+ let third = Device::new();+ let r = third.register(&base, &stale, true).await;+ assert_eq!(r["device"]["state"], "pending");+ assert!(r["code"].is_string());+}++/// The strict policy (`CUA_RELAY_DEVICE_REQUIRE_APPROVAL`).+#[tokio::test]+async fn strict_an_unverified_email_needs_an_approval_for_further_devices() {+ let issuer = FakeIssuer::new(ISSUER);+ let base = start_with(+ &issuer,+ DevicePolicy {+ grace_secs: 0,+ require_approval: true,+ ..DevicePolicy::default()+ },+ )+ .await;+ issuer.set_auth_time("eve", now() as i64);+ let unverified = issuer.token_with("eve", Some("[email protected]"), false, "cua-relay", 300);// The account's first device still enrolls by a fresh sign-in.let first = Device::new();let r = first.register(&base, &unverified, true).await;diff --git a/libs/cua-spacesd/tests/spaces-e2e/tests/relay_devices.rs b/libs/cua-spacesd/tests/spaces-e2e/tests/relay_devices.rsindex 28b828d956..edc1180a8b 100644--- a/libs/cua-spacesd/tests/spaces-e2e/tests/relay_devices.rs+++ b/libs/cua-spacesd/tests/spaces-e2e/tests/relay_devices.rs@@ -38,13 +38,14 @@ async fn relay(issuer: &FakeIssuer) -> String {url}-/// Relay device policy (S4) this suite pins: a fresh sign-in on an account-/// with a verified email enrolls a brand-new additional device (another-/// machine) without an approval (cua-relay 4f62b9c91). When the relay-/// requires an approval or MFA for those again, set this to `false`: the-/// asserts that read it expect `Pending` and approve by code instead. The-/// first device and a same-machine re-key stay approval-free either way.-const FRESH_SIGN_IN_ENROLLS_A_NEW_MACHINE: bool = false;+/// Relay device policy this suite pins: by default a fresh sign-in enrolls+/// a brand-new additional device (another machine) of the account without+/// an approval, whether or not the email is verified or the token proves+/// MFA. Under the relay's strict policy (`DevicePolicy::require_approval`,+/// `CUA_RELAY_DEVICE_REQUIRE_APPROVAL`) set this to `false`: the asserts+/// that read it expect `Pending` and approve by code instead. The first+/// device and a same-machine re-key stay approval-free either way.+const FRESH_SIGN_IN_ENROLLS_A_NEW_MACHINE: bool = true;/// A device with a fresh key on the machine `machine` (the machine id it/// reports; never this host's, so the suite neither reads the host'sdiff --git a/libs/cua/Cargo.lock b/libs/cua/Cargo.lockindex e030aa2b61..857b97a919 100644--- a/libs/cua/Cargo.lock+++ b/libs/cua/Cargo.lock@@ -2655,6 +2655,7 @@ dependencies = ["tokio-stream","tokio-tungstenite 0.29.0","tonic",+ "tonic-web","tracing","url",]diff --git a/libs/cua/crates/cua-auth/src/lib.rs b/libs/cua/crates/cua-auth/src/lib.rsindex 716de54771..a2c21ff465 100644--- a/libs/cua/crates/cua-auth/src/lib.rs+++ b/libs/cua/crates/cua-auth/src/lib.rs@@ -77,6 +77,18 @@ pub enum Error {/// Result alias.pub type Result<T, E = Error> = std::result::Result<T, E>;+#[cfg(target_os = "macos")]+mod macos_keychain;++/// What to do when the login keychain cannot be used without a prompt this+/// session cannot show (an SSH session).+pub const KEYCHAIN_LOCKED_HINT: &str = "the macOS login keychain cannot be used from this session \+ without a prompt (it is locked, or this cua is not yet allowed to read the Cua sign-in \+ item, and an SSH session cannot show the dialog). Run `security unlock-keychain` first \+ (and approve the Cua item once at the console if it still asks), or sign in with \+ CUA_CREDENTIAL_STORE=file (and keep it set for later commands) to store the session in \+ ~/.cua/credentials.json";+fn http_err(e: impl std::fmt::Display) -> Error {Error::Http(e.to_string())}@@ -374,6 +386,28 @@ impl Store {}}+ /// Checks, before an interactive sign-in, that the session can be+ /// saved here without a prompt this process cannot show: on macOS, from+ /// an SSH session (no window server access) the login keychain must be+ /// unlocked and an existing Cua item readable. Failing here, before the+ /// browser or device code is shown, beats failing after the user+ /// approved the sign-in. Other stores and console sessions always pass.+ pub fn check_writable(&self) -> Result<()> {+ #[cfg(target_os = "macos")]+ if matches!(self, Store::Keyring) && !macos_keychain::has_graphic_access() {+ if macos_keychain::default_keychain_unlocked() == Some(false) {+ return Err(Error::Store(KEYCHAIN_LOCKED_HINT.into()));+ }+ // No prompt can appear here: a read that needs one fails.+ if let Err(e) = keyring_entry()?.get_password()+ && interaction_not_allowed(&e)+ {+ return Err(Error::Store(KEYCHAIN_LOCKED_HINT.into()));+ }+ }+ Ok(())+ }+/// Loads credentials (`None` when there are none).pub fn load(&self) -> Result<Option<Credentials>> {let raw = match self {@@ -422,7 +456,7 @@ impl Store {match self {Store::File(p) => write_private(p, raw.as_bytes()).map_err(store_err)?,#[cfg(any(target_os = "macos", target_os = "windows"))]- Store::Keyring => keyring_entry()?.set_password(&raw).map_err(store_err)?,+ Store::Keyring => vault_set(KEYRING_ACCOUNT, &raw)?,Store::TestKeychain(d) => {write_private(&d.join("vault.json"), raw.as_bytes()).map_err(store_err)?}@@ -639,7 +673,7 @@ impl Store {let path = self.secret_path(name)?;match self {#[cfg(any(target_os = "macos", target_os = "windows"))]- Store::Keyring => secret_entry(name)?.set_password(text).map_err(store_err),+ Store::Keyring => vault_set(&format!("{KEYRING_ACCOUNT}.{name}"), text),_ => write_private(&path, text.as_bytes()).map_err(store_err),}}@@ -715,6 +749,41 @@ impl Store {}}+/// Writes the OS vault item `account` (service [`KEYRING_SERVICE`]). On+/// macOS the item trusts every Cua executable of this machine, so the app,+/// the daemon and the CLI share it without a keychain prompt (see+/// `macos_keychain`).+#[cfg(target_os = "macos")]+fn vault_set(account: &str, text: &str) -> Result<()> {+ macos_keychain::set_generic_password(KEYRING_SERVICE, account, text.as_bytes()).map_err(|e| {+ if e.0 == macos_keychain::ERR_SEC_INTERACTION_NOT_ALLOWED {+ Error::Store(format!("{e}: {KEYCHAIN_LOCKED_HINT}"))+ } else {+ store_err(e)+ }+ })+}++#[cfg(target_os = "windows")]+fn vault_set(account: &str, text: &str) -> Result<()> {+ keyring::Entry::new(KEYRING_SERVICE, account)+ .map_err(store_err)?+ .set_password(text)+ .map_err(store_err)+}++/// Whether a keychain error is macOS refusing to show a prompt+/// (`errSecInteractionNotAllowed`).+#[cfg(target_os = "macos")]+fn interaction_not_allowed(e: &keyring::Error) -> bool {+ match e {+ keyring::Error::PlatformFailure(inner) | keyring::Error::NoStorageAccess(inner) => inner+ .downcast_ref::<security_framework::base::Error>()+ .is_some_and(|e| e.code() == macos_keychain::ERR_SEC_INTERACTION_NOT_ALLOWED),+ _ => false,+ }+}+#[cfg(any(target_os = "macos", target_os = "windows"))]fn keyring_entry() -> Result<keyring::Entry> {keyring::Entry::new(KEYRING_SERVICE, KEYRING_ACCOUNT).map_err(store_err)diff --git a/libs/cua/crates/cua-auth/src/macos_keychain.rs b/libs/cua/crates/cua-auth/src/macos_keychain.rsnew file mode 100644index 0000000000..c1091ae3ef--- /dev/null+++ b/libs/cua/crates/cua-auth/src/macos_keychain.rs@@ -0,0 +1,430 @@+//! The macOS login keychain item behind [`crate::Store::Keyring`], written+//! with an access list that trusts every Cua executable of this machine.+//!+//! Why: the legacy keychain gives a new generic password the default+//! access list, which trusts only the executable that created it. The Cua+//! Spaces app (`Contents/MacOS/CuaSpacesMac`) signs in and creates the+//! `run.cua.ai` / `cua-cli` item; the bundled `cua` daemon and CLI+//! (`Contents/MacOS/cua`, same Developer ID team, different executable)+//! then read it and macOS asks for the login password ("cua wants to use+//! your confidential information stored in run.cua.ai"), right after every+//! first sign-in.+//!+//! The fix keeps the default model (an explicit list of trusted+//! applications, everyone else is asked) and only widens the list: the+//! creating executable plus the other executables of the same app bundle+//! (`Contents/MacOS/*`) and, for a `cua` outside a bundle, those of the+//! installed `Cua Spaces.app`. Trusted-application entries record each+//! binary's designated requirement (bundle id + Cua's team), so they keep+//! matching after updates, and a copy of `cua` elsewhere with the same+//! signature matches too. Unlike an "allow all applications" entry+//! (`SecACLSetContents` with no application list; note an *empty*+//! `SecAccessCreate` list trusts no one, and NULL trusts only the caller),+//! this never depends on the item's partition list (`teamid:YCK386LBJ7`)+//! to keep other apps out.+//!+//! An access list can only be given when an item is created (changing the+//! access list of an existing item asks for the keychain password since+//! macOS 10.12), so an item that an older build created with the default+//! list is deleted and created again the next time its creator writes it+//! (token refreshes write it often). Items written this way carry the+//! comment [`ACL_MARKER`], so that happens once.++use std::ffi::{CString, c_char, c_void};+use std::path::{Path, PathBuf};+use std::ptr;++type OSStatus = i32;+type CFTypeRef = *const c_void;+type CFStringRef = *const c_void;+type CFArrayRef = *const c_void;+type SecRef = *mut c_void;++#[repr(C)]+struct SecKeychainAttribute {+ tag: u32,+ length: u32,+ data: *mut c_void,+}++#[repr(C)]+struct SecKeychainAttributeList {+ count: u32,+ attr: *mut SecKeychainAttribute,+}++#[repr(C)]+struct CFArrayCallBacks {+ _private: [u8; 0],+}++#[link(name = "CoreFoundation", kind = "framework")]+unsafe extern "C" {+ static kCFTypeArrayCallBacks: CFArrayCallBacks;+ fn CFRelease(cf: CFTypeRef);+ fn CFArrayCreate(+ allocator: CFTypeRef,+ values: *const CFTypeRef,+ count: isize,+ callbacks: *const CFArrayCallBacks,+ ) -> CFArrayRef;+ fn CFStringCreateWithCString(+ allocator: CFTypeRef,+ s: *const c_char,+ encoding: u32,+ ) -> CFStringRef;+}++#[link(name = "Security", kind = "framework")]+unsafe extern "C" {+ fn SecKeychainCopyDefault(keychain: *mut SecRef) -> OSStatus;+ fn SecKeychainGetStatus(keychain: SecRef, status: *mut u32) -> OSStatus;+ fn SecKeychainFindGenericPassword(+ keychain_or_array: CFTypeRef,+ service_len: u32,+ service: *const c_char,+ account_len: u32,+ account: *const c_char,+ password_len: *mut u32,+ password: *mut *mut c_void,+ item: *mut SecRef,+ ) -> OSStatus;+ fn SecKeychainItemCopyContent(+ item: SecRef,+ item_class: *mut u32,+ attr_list: *mut SecKeychainAttributeList,+ length: *mut u32,+ out_data: *mut *mut c_void,+ ) -> OSStatus;+ fn SecKeychainItemFreeContent(+ attr_list: *mut SecKeychainAttributeList,+ data: *mut c_void,+ ) -> OSStatus;+ fn SecKeychainItemModifyAttributesAndData(+ item: SecRef,+ attr_list: *const SecKeychainAttributeList,+ length: u32,+ data: *const c_void,+ ) -> OSStatus;+ fn SecKeychainItemDelete(item: SecRef) -> OSStatus;+ fn SecKeychainItemCreateFromContent(+ item_class: u32,+ attr_list: *mut SecKeychainAttributeList,+ length: u32,+ data: *const c_void,+ keychain: SecRef,+ initial_access: SecRef,+ item: *mut SecRef,+ ) -> OSStatus;+ fn SecTrustedApplicationCreateFromPath(path: *const c_char, app: *mut SecRef) -> OSStatus;+ fn SecAccessCreate(+ descriptor: CFStringRef,+ trusted_list: CFArrayRef,+ access: *mut SecRef,+ ) -> OSStatus;+ fn SessionGetInfo(session: u32, session_id: *mut u32, attributes: *mut u32) -> OSStatus;+}++const ERR_SEC_SUCCESS: OSStatus = 0;+const ERR_SEC_ITEM_NOT_FOUND: OSStatus = -25300;+/// `errSecInteractionNotAllowed`: the keychain needs a prompt (unlock or+/// access confirmation) that this session cannot show (an SSH session).+pub(crate) const ERR_SEC_INTERACTION_NOT_ALLOWED: OSStatus = -25308;++const GENERIC_PASSWORD_CLASS: u32 = u32::from_be_bytes(*b"genp");+const ATTR_SERVICE: u32 = u32::from_be_bytes(*b"svce");+const ATTR_ACCOUNT: u32 = u32::from_be_bytes(*b"acct");+const ATTR_LABEL: u32 = u32::from_be_bytes(*b"labl");+const ATTR_COMMENT: u32 = u32::from_be_bytes(*b"icmt");+const UNLOCKED: u32 = 1;+const CALLER_SECURITY_SESSION: u32 = u32::MAX;+const SESSION_HAS_GRAPHIC_ACCESS: u32 = 0x0010;+const UTF8: u32 = 0x0800_0100;++/// The comment of an item written with the Cua access list.+pub(crate) const ACL_MARKER: &str = "cua-acl/v2";++/// The installed app a `cua` outside a bundle also trusts.+const INSTALLED_APP: &str = "/Applications/Cua Spaces.app";++/// A Security / CoreFoundation object released on drop.+struct Owned(SecRef);++impl Drop for Owned {+ fn drop(&mut self) {+ if !self.0.is_null() {+ unsafe { CFRelease(self.0 as CFTypeRef) };+ }+ }+}++/// A Security framework failure.+#[derive(Debug)]+pub(crate) struct Status(pub OSStatus);++impl std::fmt::Display for Status {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(f, "{}", security_framework::base::Error::from_code(self.0))+ }+}++fn check(status: OSStatus) -> Result<(), Status> {+ if status == ERR_SEC_SUCCESS {+ Ok(())+ } else {+ Err(Status(status))+ }+}++/// The executables an item this process creates trusts besides itself:+/// the other executables in the `Contents/MacOS` of the app bundle `exe`+/// runs from, else (a `cua` outside a bundle) those of `installed_app`.+pub(crate) fn companion_executables(exe: &Path, installed_app: &Path) -> Vec<PathBuf> {+ let exe = exe.canonicalize().unwrap_or_else(|_| exe.to_path_buf());+ let bundle = exe+ .ancestors()+ .find(|d| d.extension().is_some_and(|e| e == "app"))+ .map(Path::to_path_buf)+ .unwrap_or_else(|| installed_app.to_path_buf());+ let Ok(entries) = std::fs::read_dir(bundle.join("Contents/MacOS")) else {+ return vec![];+ };+ let mut out: Vec<PathBuf> = entries+ .filter_map(|e| e.ok()?.path().canonicalize().ok())+ .filter(|p| p != &exe && is_executable(p))+ .collect();+ out.sort();+ out.dedup();+ out+}++fn is_executable(p: &Path) -> bool {+ use std::os::unix::fs::PermissionsExt as _;+ std::fs::metadata(p).is_ok_and(|m| m.is_file() && m.permissions().mode() & 0o111 != 0)+}++/// An access object trusting this process and its companion executables.+fn cua_access(descriptor: &str) -> Result<Owned, Status> {+ let mut apps: Vec<Owned> = Vec::new();+ let mut me: SecRef = ptr::null_mut();+ // NULL: the calling application.+ check(unsafe { SecTrustedApplicationCreateFromPath(ptr::null(), &mut me) })?;+ apps.push(Owned(me));+ let exe = std::env::current_exe().unwrap_or_default();+ for path in companion_executables(&exe, Path::new(INSTALLED_APP)) {+ let Ok(c) = CString::new(path.as_os_str().as_encoded_bytes()) else {+ continue;+ };+ let mut app: SecRef = ptr::null_mut();+ // A companion that cannot be described is left out (it asks).+ if unsafe { SecTrustedApplicationCreateFromPath(c.as_ptr(), &mut app) } == ERR_SEC_SUCCESS {+ apps.push(Owned(app));+ }+ }+ let values: Vec<CFTypeRef> = apps.iter().map(|a| a.0 as CFTypeRef).collect();+ let list = Owned(unsafe {+ CFArrayCreate(+ ptr::null(),+ values.as_ptr(),+ values.len() as isize,+ &kCFTypeArrayCallBacks,+ )+ } as SecRef);+ let desc = CString::new(descriptor).unwrap_or_default();+ let desc =+ Owned(unsafe { CFStringCreateWithCString(ptr::null(), desc.as_ptr(), UTF8) } as SecRef);+ if list.0.is_null() || desc.0.is_null() {+ return Err(Status(-108)); // memFullErr+ }+ let mut access: SecRef = ptr::null_mut();+ check(unsafe { SecAccessCreate(desc.0 as CFStringRef, list.0 as CFArrayRef, &mut access) })?;+ Ok(Owned(access))+}++fn default_keychain() -> Result<Owned, Status> {+ let mut kc: SecRef = ptr::null_mut();+ check(unsafe { SecKeychainCopyDefault(&mut kc) })?;+ Ok(Owned(kc))+}++/// The item, without reading its secret (no prompt).+fn find_item(kc: &Owned, service: &str, account: &str) -> Result<Option<Owned>, Status> {+ let mut item: SecRef = ptr::null_mut();+ let status = unsafe {+ SecKeychainFindGenericPassword(+ kc.0 as CFTypeRef,+ service.len() as u32,+ service.as_ptr().cast(),+ account.len() as u32,+ account.as_ptr().cast(),+ ptr::null_mut(),+ ptr::null_mut(),+ &mut item,+ )+ };+ match status {+ ERR_SEC_SUCCESS => Ok(Some(Owned(item))),+ ERR_SEC_ITEM_NOT_FOUND => Ok(None),+ s => Err(Status(s)),+ }+}++/// The item's comment (an unencrypted attribute: no prompt).+fn comment(item: &Owned) -> Option<String> {+ let mut attr = SecKeychainAttribute {+ tag: ATTR_COMMENT,+ length: 0,+ data: ptr::null_mut(),+ };+ let mut list = SecKeychainAttributeList {+ count: 1,+ attr: &mut attr,+ };+ let status = unsafe {+ SecKeychainItemCopyContent(+ item.0,+ ptr::null_mut(),+ &mut list,+ ptr::null_mut(),+ ptr::null_mut(),+ )+ };+ if status != ERR_SEC_SUCCESS {+ return None;+ }+ let a = unsafe { &*list.attr };+ let text = (!a.data.is_null()).then(|| {+ let bytes = unsafe { std::slice::from_raw_parts(a.data as *const u8, a.length as usize) };+ String::from_utf8_lossy(bytes).into_owned()+ });+ unsafe { SecKeychainItemFreeContent(&mut list, ptr::null_mut()) };+ text+}++fn create(kc: &Owned, service: &str, account: &str, secret: &[u8]) -> Result<(), Status> {+ let access = cua_access(service)?;+ let attr = |tag: u32, v: &str| SecKeychainAttribute {+ tag,+ length: v.len() as u32,+ data: v.as_ptr() as *mut c_void,+ };+ let mut attrs = [+ attr(ATTR_SERVICE, service),+ attr(ATTR_ACCOUNT, account),+ attr(ATTR_LABEL, service),+ attr(ATTR_COMMENT, ACL_MARKER),+ ];+ let mut list = SecKeychainAttributeList {+ count: attrs.len() as u32,+ attr: attrs.as_mut_ptr(),+ };+ let mut item: SecRef = ptr::null_mut();+ check(unsafe {+ SecKeychainItemCreateFromContent(+ GENERIC_PASSWORD_CLASS,+ &mut list,+ secret.len() as u32,+ secret.as_ptr().cast(),+ kc.0,+ access.0,+ &mut item,+ )+ })?;+ drop(Owned(item));+ Ok(())+}++fn modify(item: &Owned, secret: &[u8]) -> Result<(), Status> {+ check(unsafe {+ SecKeychainItemModifyAttributesAndData(+ item.0,+ ptr::null(),+ secret.len() as u32,+ secret.as_ptr().cast(),+ )+ })+}++/// Stores `secret` as the generic password `service` / `account` in the+/// default keychain, trusted by the Cua executables (see the module docs).+pub(crate) fn set_generic_password(+ service: &str,+ account: &str,+ secret: &[u8],+) -> Result<(), Status> {+ let kc = default_keychain()?;+ match find_item(&kc, service, account)? {+ None => create(&kc, service, account, secret),+ Some(item) if comment(&item).as_deref() == Some(ACL_MARKER) => modify(&item, secret),+ Some(item) => {+ // Written by an older build with the default access list:+ // recreate it with the Cua one. If it cannot be deleted (not+ // ours to delete), update it in place as before.+ if unsafe { SecKeychainItemDelete(item.0) } == ERR_SEC_SUCCESS {+ drop(item);+ create(&kc, service, account, secret)+ } else {+ modify(&item, secret)+ }+ }+ }+}++/// Whether this process's security session can show UI (a console login+/// can; an SSH session cannot). `true` when unknown.+pub(crate) fn has_graphic_access() -> bool {+ let (mut id, mut attrs) = (0u32, 0u32);+ if unsafe { SessionGetInfo(CALLER_SECURITY_SESSION, &mut id, &mut attrs) } != ERR_SEC_SUCCESS {+ return true;+ }+ attrs & SESSION_HAS_GRAPHIC_ACCESS != 0+}++/// Whether the default keychain is unlocked (`None` when unknown).+pub(crate) fn default_keychain_unlocked() -> Option<bool> {+ let kc = default_keychain().ok()?;+ let mut status = 0u32;+ (unsafe { SecKeychainGetStatus(kc.0, &mut status) } == ERR_SEC_SUCCESS)+ .then_some(status & UNLOCKED != 0)+}++#[cfg(test)]+mod tests {+ use super::*;++ fn exe(p: &Path) {+ use std::os::unix::fs::PermissionsExt as _;+ std::fs::create_dir_all(p.parent().unwrap()).unwrap();+ std::fs::write(p, b"\0").unwrap();+ std::fs::set_permissions(p, std::fs::Permissions::from_mode(0o755)).unwrap();+ }++ #[test]+ fn companions_are_the_other_executables_of_the_bundle() {+ let d = tempfile::tempdir().unwrap();+ let macos = d.path().join("Cua Spaces.app/Contents/MacOS");+ exe(&macos.join("CuaSpacesMac"));+ exe(&macos.join("cua"));+ std::fs::write(macos.join("notes.txt"), b"x").unwrap();+ let installed = d.path().join("Elsewhere.app");+ let app = macos.join("CuaSpacesMac").canonicalize().unwrap();+ let cua = macos.join("cua").canonicalize().unwrap();+ assert_eq!(companion_executables(&app, &installed), vec![cua.clone()]);+ assert_eq!(companion_executables(&cua, &installed), vec![app.clone()]);+ // A `cua` outside a bundle trusts the installed app's executables.+ let loose = d.path().join("bin/cua");+ exe(&loose);+ let other = d.path().join("Cua Spaces.app");+ let mut both = companion_executables(&loose, &other);+ both.sort();+ assert_eq!(both, vec![app, cua]);+ // No app installed: nobody else.+ assert!(companion_executables(&loose, &installed).is_empty());+ }++ #[test]+ fn four_char_codes() {+ assert_eq!(GENERIC_PASSWORD_CLASS, 0x6765_6e70);+ assert_eq!(ATTR_COMMENT, 0x6963_6d74);+ }+}diff --git a/libs/cua/crates/cua-cli/src/auth.rs b/libs/cua/crates/cua-cli/src/auth.rsindex 54f7ad5779..6408cd61f5 100644--- a/libs/cua/crates/cua-cli/src/auth.rs+++ b/libs/cua/crates/cua-cli/src/auth.rs@@ -166,6 +166,9 @@ pub async fn login(opts: &LoginOptions, out: &mut dyn Write) -> Result<i32, CuaENone => cua_auth::Flow::Auto,};let s = session();+ // Fail before the user approves anything when the session could not be+ // saved afterwards (the macOS login keychain from an SSH session).+ s.store().check_writable().map_err(auth_err)?;let pending = s.begin_login(flow).await.map_err(auth_err)?;if let Some(note) = &pending.note {line(out, format!("{}.", note.trim_end_matches('.')));diff --git a/libs/cua/crates/cua-cli/src/devices_cmd.rs b/libs/cua/crates/cua-cli/src/devices_cmd.rsindex 27927a2c8f..e4be25a234 100644--- a/libs/cua/crates/cua-cli/src/devices_cmd.rs+++ b/libs/cua/crates/cua-cli/src/devices_cmd.rs@@ -2,8 +2,8 @@//! relay. A device that lists or reaches your machines through the relay is//! enrolled once with a second factor (a fresh sign-in, or an approval from//! an enrolled device) and re-verified after the relay's TTL. A new key of-//! the same machine replaces its old record. Hosting never enrolls a-//! device.+//! the same machine replaces its old record. Hosting alone never enrolls a+//! device; `cua auth login` does (see [`after_login`]).use crate::auth;use crate::util::{self, line};@@ -132,9 +132,10 @@ pub fn device_auth(relay_url: &str) -> Result<Arc<DeviceAuth>, CuaError> {named_device_auth(relay_url, None)}-/// [`device_auth`] shown as `name` (default: the host name).+/// [`device_auth`] shown as `name` (default: this computer's name). It+/// remembers the code it shows in `~/.cua/device-pending.json`.fn named_device_auth(relay_url: &str, name: Option<&str>) -> Result<Arc<DeviceAuth>, CuaError> {- DeviceAuth::new(+ let auth = DeviceAuth::new(relay_url,Arc::new(crate::host::SessionTokens),Arc::new(auth::Store::from_env()),@@ -143,14 +144,16 @@ fn named_device_auth(relay_url: &str, name: Option<&str>) -> Result<Arc<DeviceAu.map(str::to_string).unwrap_or_else(cua_host::device_name),)- .map(Arc::new)- .map_err(crate::host::host_err)+ .map_err(crate::host::host_err)?;+ Ok(Arc::new(auth.with_pending_file(+ cua_host::device_pending_file(&util::cua_home()),+ )))}-/// After `cua auth login`: a device that already has a key re-registers,-/// so the fresh sign-in enrolls (or re-verifies) it without an approval.-/// Best effort: a relay that is down, slow or refuses never fails the-/// login, and a device that never enrolled stays unregistered.+/// After `cua auth login`: registers this device (creating its key on a+/// new device), so the fresh sign-in enrolls (or re-verifies) it without an+/// approval, and says how that went. Best effort: a relay that is down,+/// slow or refuses never fails the login.pub async fn after_login(home: &Path, out: &mut dyn Write) {let Ok(auth) = device_auth(&crate::host::relay_url(None, home)) else {return;@@ -163,7 +166,7 @@ pub async fn after_login(home: &Path, out: &mut dyn Write) {// `cua_device_enroll`: enrolled by this sign-in (`rekey` when it// replaced the machine's other key), or failed; nothing otherwise.let enrolled = match &result {- Ok(Ok(Some(r))) if r.device.state == DeviceState::Enrolled => Some((+ Ok(Ok(r)) if r.device.state == DeviceState::Enrolled => Some((if r.superseded.is_empty() {"sign_in"} else {@@ -178,7 +181,7 @@ pub async fn after_login(home: &Path, out: &mut dyn Write) {cua_telemetry::capture(e);}match result {- Ok(Ok(Some(r))) if r.device.state == DeviceState::Enrolled => line(+ Ok(Ok(r)) if r.device.state == DeviceState::Enrolled => line(out,format!("This device ({}) is enrolled until {}.",@@ -186,19 +189,48 @@ pub async fn after_login(home: &Path, out: &mut dyn Write) {when(r.device.enrolled_until)),),- Ok(Ok(Some(r))) => {+ Ok(Ok(r)) => {if let Some(code) = r.code {line(out,format!(- "This device is waiting for approval: approve it from an enrolled device with `cua devices approve {code}`."+ "This device is waiting for approval (code {code}): approve it from an enrolled device with `cua devices approve {code}` or in the Cua Spaces app."),);}}- // Not enrolled before, or the relay is unreachable: `cua devices- // enroll` says more.- Ok(Ok(None)) | Ok(Err(_)) | Err(_) => {}+ Ok(Err(e)) => line(+ out,+ format!(+ "Signed in, but this device could not be enrolled yet ({e}); run `cua devices enroll`."+ ),+ ),+ Err(_) => line(+ out,+ "Signed in, but the relay did not answer in time to enroll this device; run `cua devices enroll`.",+ ),+ }+}++/// Where the relay says this device stands, from opening a session: its+/// state, or `None` when the relay does not know it.+async fn relay_state(auth: &DeviceAuth) -> Result<Option<DeviceState>, cua_host::Error> {+ match auth.session().await {+ Ok(_) => Ok(Some(DeviceState::Enrolled)),+ Err(cua_host::Error::NotFound(_)) => Ok(None),+ Err(e) => cua_host::device::refused_state(&e).map(Some).ok_or(e),+ }+}++/// `cua devices approve` without `--yes` needs a terminal to ask in.+fn approve_needs_terminal(cmd: &DevicesCmd, interactive: bool) -> Option<CuaError> {+ match cmd {+ DevicesCmd::Approve { yes: false, .. } if !interactive => Some(CuaError::InvalidArgument(+ "`cua devices approve` needs --yes when not run in a terminal (it cannot ask \+ for confirmation): approving lets that device list and reach your machines"+ .into(),+ )),+ _ => None,}}@@ -242,6 +274,17 @@ pub async fn run_with(.and_then(|l| l.into_iter().find(|d| &d.id == id)),None => None,};+ // Listing needs an enrolled device: otherwise ask the relay+ // where this device stands (waiting, re-verification due,+ // revoked, or unknown to it).+ let state = match (&id, &this) {+ (_, Some(d)) => Ok(Some(d.state)),+ (Some(_), None) => relay_state(auth).await,+ (None, None) => Ok(None),+ };+ let pending = auth+ .pending_code()+ .filter(|_| matches!(state, Ok(Some(DeviceState::Pending))));if json {line(out,@@ -249,6 +292,9 @@ pub async fn run_with("relay": auth.relay_url(),"device_id": id,"device": this.as_ref().map(view_json),+ "state": state.as_ref().ok().cloned().flatten(),+ "code": pending.as_ref().map(|p| p.code.clone()),+ "code_expires": pending.as_ref().map(|p| p.expires_at),}).to_string(),);@@ -262,13 +308,32 @@ pub async fn run_with();return Ok(1);}- (Some(id), None) => line(- out,- format!(- "This device ({id}) is not registered on {}.",- auth.relay_url()+ (Some(id), None) => match state {+ Ok(None) => line(+ out,+ format!(+ "This device ({id}) is not registered on {} (run `cua devices enroll`).",+ auth.relay_url()+ ),+ ),+ Ok(Some(s)) => line(+ out,+ format!(+ "This device ({id}): {}",+ state_label(&DeviceView {+ state: s,+ ..Default::default()+ })+ ),),- ),+ Err(e) => line(+ out,+ format!(+ "This device ({id}): could not check with {} ({e}).",+ auth.relay_url()+ ),+ ),+ },(Some(_), Some(d)) => {line(out, format!("{} ({}): {}", d.name, d.id, state_label(d)));if d.state == DeviceState::Enrolled {@@ -276,6 +341,16 @@ pub async fn run_with(}}}+ if let Some(p) = pending {+ line(+ out,+ format!(+ " approve it from an enrolled device: `cua devices approve {}` (code expires {})",+ p.code,+ when(Some(p.expires_at))+ ),+ );+ }}DevicesCmd::Enroll { wait, .. } => {let r = auth.enroll().await.map_err(err)?;@@ -316,7 +391,13 @@ pub async fn run_with(line(out, format!(" cua devices approve {code}"));line(out,- "(or approve it in the Cua Spaces app). The code expires in 10 minutes.",+ format!(+ "(or approve it in the Cua Spaces app). The code expires {}.",+ r.device+ .code_expires+ .map(|t| format!("at {}", when(Some(t))))+ .unwrap_or_else(|| "in 10 minutes".into())+ ),);line(out,@@ -474,6 +555,9 @@ pub async fn run(DevicesCmd::Enroll { name, .. } => name.clone(),_ => None,};+ if let Some(e) = approve_needs_terminal(&cmd, util::interactive()) {+ return Err(e);+ }let auth = named_device_auth(&url, name.as_deref())?;run_with(cmd,@@ -691,4 +775,79 @@ mod tests {.unwrap_err();assert!(e.to_string().contains("approve by id"), "{e}");}++ #[test]+ fn approve_without_yes_needs_a_terminal() {+ let approve = |yes| DevicesCmd::Approve {+ code: Some("K7QX-M2RP".into()),+ device: None,+ yes,+ relay: None,+ };+ let e = approve_needs_terminal(&approve(false), false).unwrap();+ assert!(matches!(e, CuaError::InvalidArgument(_)), "{e:?}");+ assert!(+ e.to_string()+ .contains("needs --yes when not run in a terminal"),+ "{e}"+ );+ assert!(approve_needs_terminal(&approve(true), false).is_none());+ assert!(approve_needs_terminal(&approve(false), true).is_none());+ assert!(approve_needs_terminal(&DevicesCmd::Ls { relay: None }, false).is_none());+ }++ #[tokio::test]+ async fn status_tells_waiting_from_not_registered() {+ let relay = FakeRelay::start().await;+ relay.add_account("acct", "user-1", Some("[email protected]"));+ relay.require_devices(true);+ relay.fresh_sign_in("user-1");+ let laptop = device(&relay, "laptop");+ laptop.enroll().await.unwrap();+ relay.stale_sign_in("user-1");+ let dir = tempfile::tempdir().unwrap();+ let phone = device(&relay, "phone").with_pending_file(dir.path().join("pending.json"));+ let enrolled = phone.enroll().await.unwrap();+ let code = enrolled.code.unwrap();+ let status = || DevicesCmd::Status { relay: None };+ let text = run_text(status(), &phone, false).await.unwrap();+ assert!(text.contains("waiting for approval"), "{text}");+ assert!(!text.contains("not registered"), "{text}");+ assert!(+ text.contains(&format!("cua devices approve {code}")),+ "{text}"+ );+ // `enroll` shows the same code again.+ let text = run_text(+ DevicesCmd::Enroll {+ name: None,+ wait: false,+ relay: None,+ },+ &phone,+ false,+ )+ .await+ .unwrap();+ assert!(text.contains(&code), "{text}");+ // Revoked shows as such.+ let phone_id = phone.device_id().unwrap().unwrap();+ laptop.approve(Some(&code), None).await.unwrap();+ laptop.revoke(&phone_id).await.unwrap();+ let text = run_text(status(), &phone, false).await.unwrap();+ assert!(text.contains("revoked"), "{text}");+ // A key the relay never saw is not registered.+ let slot = MemoryKeySlot::default();+ let (_, pkcs8) = cua_host::DeviceKey::generate().unwrap();+ cua_host::KeySlot::save(&slot, &pkcs8).unwrap();+ let unknown = DeviceAuth::new(+ &relay.url,+ Arc::new(StaticToken("acct".into())),+ Arc::new(slot),+ "unknown",+ )+ .unwrap();+ let text = run_text(status(), &unknown, false).await.unwrap();+ assert!(text.contains("is not registered on"), "{text}");+ }}diff --git a/libs/cua/crates/cua-cli/src/host.rs b/libs/cua/crates/cua-cli/src/host.rsindex 253514cb92..ee95e6214a 100644--- a/libs/cua/crates/cua-cli/src/host.rs+++ b/libs/cua/crates/cua-cli/src/host.rs@@ -1441,14 +1441,7 @@ pub fn attach_relay_account(/// `--relay`, else `CUA_RELAY_URL`, else the relay this machine is set up/// with, else the default relay.pub fn relay_url(flag: Option<String>, home: &Path) -> String {- flag.filter(|u| !u.trim().is_empty())- .or_else(|| {- std::env::var("CUA_RELAY_URL")- .ok()- .filter(|u| !u.trim().is_empty())- })- .or_else(|| Host::new(home).config().ok().flatten()?.relay_url)- .unwrap_or_else(cua_host::relay_url_from_env)+ cua_host::relay_url_for(flag.as_deref(), home)}/// `cua spaces ls` rows: every Space, with the Spaces a machine provides@@ -1464,9 +1457,11 @@ fn grouped_lines(list: &[cua_spaces::SpaceInfo]) -> Vec<String> {s.spacesd_version,width = 48usize.saturating_sub(indent.len()),);- // A Space turned off says so (`cua spaces start` turns it on).- match s.power_state.as_str() {- "suspended" | "stopped" => format!("{} ({})", line.trim_end(), s.power_state),+ // A Space turned off says so (`cua spaces start` turns it on), as+ // does a machine the relay cannot reach now (offline, not sharing).+ match (s.power_state.as_str(), s.status.as_str()) {+ ("suspended" | "stopped", _) => format!("{} ({})", line.trim_end(), s.power_state),+ (_, status) if !status.is_empty() => format!("{} ({status})", line.trim_end()),_ => line,}};@@ -1784,6 +1779,7 @@ mod tests {cloud: String::new(),cloud_place: String::new(),cloud_delete: String::new(),+ status: String::new(),};let lines = grouped_lines(&[space("relay:space-1", "mini1234"),@@ -1814,6 +1810,14 @@ mod tests {"{lines:?}");assert_eq!(lines.len(), 2, "{lines:?}");+ // A machine the relay cannot reach now says why.+ let mut stopped = space("relay:mini1234", "");+ stopped.status = "not sharing".into();+ let mut off = space("relay:studio99", "");+ off.status = "offline".into();+ let lines = grouped_lines(&[stopped, off]);+ assert!(lines[0].ends_with("(not sharing)"), "{lines:?}");+ assert!(lines[1].ends_with("(offline)"), "{lines:?}");}#[test]diff --git a/libs/cua/crates/cua-cli/tests/common/mod.rs b/libs/cua/crates/cua-cli/tests/common/mod.rsindex 83d094728c..77bcf11c33 100644--- a/libs/cua/crates/cua-cli/tests/common/mod.rs+++ b/libs/cua/crates/cua-cli/tests/common/mod.rs@@ -90,6 +90,9 @@ impl Home {// Never touch the OS keychain, never open a browser.env.insert("CUA_CREDENTIAL_STORE".into(), "file".into());env.insert("CUA_NO_BROWSER".into(), "1".into());+ // `cua auth login` enrolls this device on the relay afterwards:+ // never the real one (port 9 refuses at once).+ env.insert("CUA_RELAY_URL".into(), "http://127.0.0.1:9".into());env.insert("CUA_LOG".into(), "error".into());// Never read a real registry for the Fleet runtime/image rule.env.insert("CUA_FLEET_IMAGE_INSPECT".into(), "0".into());diff --git a/libs/cua/crates/cua-host/src/device.rs b/libs/cua/crates/cua-host/src/device.rsindex 674daf0897..6017cd070f 100644--- a/libs/cua/crates/cua-host/src/device.rs+++ b/libs/cua/crates/cua-host/src/device.rs@@ -5,7 +5,8 @@//! file; see [`KeySlot`]) and is enrolled once with a second factor://!//! - a fresh interactive sign-in enrolls it right away (`cua auth login` or-//! the app's sign-in re-registers a device that already has a key);+//! the app's sign-in registers this device, creating its key on first+//! use);//! - otherwise it shows a one-time code that an enrolled device confirms//! (`cua devices approve <code>`, or the Cua Spaces app). Relays that//! predate sign-in enrollment for every device enroll only an account's@@ -235,6 +236,41 @@ pub struct DeviceAuth {name: String,machine_id: std::sync::OnceLock<Option<String>>,session: tokio::sync::Mutex<Option<(String, u64)>>,+ pending_file: Option<PathBuf>,+}++/// The one-time code this device last showed, remembered (in+/// `~/.cua/device-pending.json`) so `cua devices status` can show it again+/// and `cua devices enroll` reuses it instead of re-registering: a new+/// registration replaces the code and silently invalidates the one the user+/// may be typing on the other device.+#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]+pub struct PendingCode {+ /// Relay base URL.+ pub relay: String,+ /// `dev_…`.+ pub device_id: String,+ /// The one-time code.+ pub code: String,+ /// Unix seconds the code expires at.+ pub expires_at: u64,+}++/// A pending code's lifetime when the relay does not say.+const DEFAULT_CODE_TTL_SECS: u64 = 600;+/// Do not reuse a code that expires sooner than this.+const CODE_REUSE_MARGIN_SECS: u64 = 60;+/// A sign-in at most this old may still enroll by registering again (the+/// relay's default bootstrap window).+const FRESH_SIGN_IN_SECS: u64 = 600;++/// The unverified `auth_time` claim of a JWT access token (display and+/// local decisions only; the relay verifies).+fn token_auth_time(token: &str) -> Option<u64> {+ let payload = token.split('.').nth(1)?;+ let bytes = b64().decode(payload.trim_end_matches('=')).ok()?;+ let claims: serde_json::Value = serde_json::from_slice(&bytes).ok()?;+ claims.get("auth_time")?.as_u64()}impl std::fmt::Debug for DeviceAuth {@@ -264,9 +300,61 @@ impl DeviceAuth {name: name.into(),machine_id: std::sync::OnceLock::new(),session: tokio::sync::Mutex::new(None),+ pending_file: None,})}+ /// Remembers this device's pending code in `path` (see+ /// [`PendingCode`]).+ pub fn with_pending_file(mut self, path: impl Into<PathBuf>) -> Self {+ self.pending_file = Some(path.into());+ self+ }++ /// The unexpired pending code this device last showed on this relay.+ pub fn pending_code(&self) -> Option<PendingCode> {+ let path = self.pending_file.as_ref()?;+ let p: PendingCode = serde_json::from_slice(&std::fs::read(path).ok()?).ok()?;+ let id = self.device_id().ok()??;+ (p.relay == self.relay.base()+ && p.device_id == id+ && p.expires_at > now_secs() + CODE_REUSE_MARGIN_SECS)+ .then_some(p)+ }++ fn remember_pending(&self, enrollment: &Enrollment) {+ let Some(path) = &self.pending_file else {+ return;+ };+ // A test never writes the user's real ~/.cua.+ if cua_home::guard_write(path).is_err() {+ return;+ }+ let result = match (&enrollment.device.state, &enrollment.code) {+ (DeviceState::Pending, Some(code)) => {+ let p = PendingCode {+ relay: self.relay.base().to_string(),+ device_id: enrollment.device.id.clone(),+ code: code.clone(),+ expires_at: enrollment+ .device+ .code_expires+ .unwrap_or_else(|| now_secs() + DEFAULT_CODE_TTL_SECS),+ };+ serde_json::to_vec_pretty(&p)+ .map_err(std::io::Error::other)+ .and_then(|bytes| cua_home::write_private(path, &bytes))+ }+ _ => match std::fs::remove_file(path) {+ Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(e),+ _ => Ok(()),+ },+ };+ if let Err(e) = result {+ tracing::debug!(error = %e, "could not remember the pending device code");+ }+ }+/// Reports `machine_id` instead of this machine's/// ([`crate::machine::machine_id`]); `None` reports none.pub fn with_machine_id(self, machine_id: Option<String>) -> Self {@@ -322,20 +410,50 @@ impl DeviceAuth {/// relay already enrolled wins and the other is retired, so the machine/// stays one device. A key the relay revoked (or replaced) can never/// enroll again, so it is replaced by a new one.+ ///+ /// While this device still waits with an unexpired code it remembers+ /// (see [`DeviceAuth::with_pending_file`]) and the sign-in is not fresh+ /// enough to enroll by itself, the code is shown again instead of+ /// registering anew (which would replace it).pub async fn enroll(&self) -> Result<Enrollment> {+ if let Some(p) = self.pending_code() {+ let token = self.tokens.access_token().await?;+ let fresh = token_auth_time(&token)+ .is_some_and(|t| now_secs().saturating_sub(t) <= FRESH_SIGN_IN_SECS);+ if !fresh+ && let Err(e) = self.session().await+ && refused_state(&e) == Some(DeviceState::Pending)+ {+ return Ok(Enrollment {+ device: DeviceView {+ id: p.device_id,+ name: self.name.clone(),+ state: DeviceState::Pending,+ code_expires: Some(p.expires_at),+ current: true,+ ..Default::default()+ },+ code: Some(p.code),+ ..Default::default()+ });+ }+ }self.register_this(&self.name).await}- /// After an interactive sign-in: re-registers this device when it- /// already has a key, so a fresh sign-in enrolls (or re-verifies) it- /// without an approval. Keeps the name the relay knows. `None` when- /// this device never enrolled (no key): signing in alone creates no- /// device.- pub async fn enroll_after_sign_in(&self) -> Result<Option<Enrollment>> {- if self.key()?.is_none() && self.alternate_key()?.is_none() {- return Ok(None);- }- self.register_this("").await.map(Some)+ /// After an interactive sign-in: registers this device so the fresh+ /// sign-in enrolls (or re-verifies) it without an approval. A device+ /// with a key keeps the name the relay knows; a new one gets its key+ /// now and registers under this device's name, so signing in on a new+ /// computer is enough to use it (a relay that does not take the+ /// sign-in as a second factor leaves it pending with a code).+ pub async fn enroll_after_sign_in(&self) -> Result<Enrollment> {+ let name = if self.key()?.is_none() && self.alternate_key()?.is_none() {+ self.name.clone()+ } else {+ String::new()+ };+ self.register_this(&name).await}async fn register_this(&self, name: &str) -> Result<Enrollment> {@@ -373,6 +491,7 @@ impl DeviceAuth {other => other?,};*self.session.lock().await = None;+ self.remember_pending(&enrollment);if enrollment.device.state == DeviceState::Enrolled&& let Some(other) =other.filter(|o| o != &enrollment.device.id && !enrollment.superseded.contains(o))@@ -600,6 +719,24 @@ impl DeviceAuth {}}+/// The state a relay's refusal to open a device session reports: pending+/// (waiting for approval), re-verification due, or revoked. `None` for any+/// other error (an unknown device is `Error::NotFound`).+pub fn refused_state(e: &Error) -> Option<DeviceState> {+ let Error::PermissionDenied(m) = e else {+ return None;+ };+ if m.contains("revoked") {+ Some(DeviceState::Revoked)+ } else if m.contains("waiting for approval") || m.contains("not enrolled yet") {+ Some(DeviceState::Pending)+ } else if m.contains("re-verif") || m.contains("enrollment expired") {+ Some(DeviceState::Expired)+ } else {+ None+ }+}+/// Whether `e` is the relay refusing a request specifically because of/// this device's session -- not a sign-in problem, not some other 403 --/// matching the two message shapes `cua-relay`'s device API emits for it:@@ -614,3 +751,46 @@ fn is_session_rejection(e: &Error) -> bool {matches!(e, Error::PermissionDenied(msg)if msg.contains("not enrolled") || msg.contains("from an enrolled device"))}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn refused_state_reads_the_relays_messages() {+ let denied = |m: &str| Error::PermissionDenied(m.into());+ for (m, want) in [+ (+ "this device is waiting for approval from an enrolled device",+ DeviceState::Pending,+ ),+ (+ "this device is not enrolled yet: sign in again (`cua auth login`) to enroll it",+ DeviceState::Pending,+ ),+ (+ "this device needs re-verification: approve it from an enrolled device",+ DeviceState::Expired,+ ),+ (+ "this device's enrollment expired after a period without use: sign in again",+ DeviceState::Expired,+ ),+ ("this device was revoked", DeviceState::Revoked),+ ] {+ assert_eq!(refused_state(&denied(m)), Some(want), "{m}");+ }+ assert_eq!(refused_state(&Error::NotFound("relay: gone".into())), None);+ assert_eq!(refused_state(&denied("forbidden")), None);+ }++ #[test]+ fn token_auth_time_reads_the_unverified_claim() {+ let claims = b64().encode(br#"{"sub":"u","auth_time":1700000000}"#);+ assert_eq!(+ token_auth_time(&format!("h.{claims}.s")),+ Some(1_700_000_000)+ );+ assert_eq!(token_auth_time("opaque-token"), None);+ }+}diff --git a/libs/cua/crates/cua-host/src/host.rs b/libs/cua/crates/cua-host/src/host.rsindex ef7aebd6a4..b7e8baa4db 100644--- a/libs/cua/crates/cua-host/src/host.rs+++ b/libs/cua/crates/cua-host/src/host.rs@@ -588,6 +588,43 @@ pub(crate) fn hostname() -> String {.unwrap_or_else(|| "this machine".into())}+/// The name a person knows this machine by, for display and as the default+/// relay machine / device name: `CUA_HOST_NAME` if set, then on macOS the+/// Sharing "Computer Name" ("cua's Mac Studio"), else the host name with a+/// trailing `.local` / `.localdomain` dropped ("Mac.localdomain" -> "Mac").+pub(crate) fn friendly_name() -> String {+ if let Ok(v) = std::env::var("CUA_HOST_NAME")+ && !v.trim().is_empty()+ {+ return v.trim().to_string();+ }+ #[cfg(target_os = "macos")]+ if let Some(name) = std::process::Command::new("/usr/sbin/scutil")+ .args(["--get", "ComputerName"])+ .output()+ .ok()+ .filter(|o| o.status.success())+ .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())+ .filter(|s| !s.is_empty())+ {+ return name;+ }+ strip_local_suffix(&hostname())+}++/// Drops an mDNS / resolver suffix from a host name; keeps the name when+/// nothing would be left.+fn strip_local_suffix(host: &str) -> String {+ let host = host.trim();+ let lower = host.to_ascii_lowercase();+ for suffix in [".localdomain", ".local"] {+ if lower.ends_with(suffix) && host.len() > suffix.len() {+ return host[..host.len() - suffix.len()].to_string();+ }+ }+ host.to_string()+}+/// The LAN address a direct client would use for an unspecified bind.fn lan_ip() -> Option<std::net::IpAddr> {// No packet is sent: connecting a UDP socket only picks a route.@@ -825,7 +862,7 @@ impl Host {.name.clone().filter(|n| !n.trim().is_empty())- .unwrap_or_else(hostname);+ .unwrap_or_else(friendly_name);if !opts.share_desktop && !opts.provide_spaces {return Err(Error::InvalidArgument("with neither the desktop nor Spaces there is nothing to share; turn on \@@ -1179,6 +1216,13 @@ impl Host {/// the driver reports granted (asked afresh on each status, so a grant/// shows without restarting anything). All of them when it cannot say.fn missing_permissions(&self, config: &HostConfig) -> Vec<PermissionHint> {+ // Screen Recording and Accessibility let people you share with see+ // and control this desktop. A machine that only provides Spaces+ // (a spare Mac) keeps its desktop private and runs Spaces in VMs,+ // so it needs neither.+ if !config.share_desktop {+ return vec![];+ }let hints = permission_hints(std::env::consts::OS, &config.driver_bin);if hints.is_empty() {return hints;@@ -1395,6 +1439,20 @@ impl Host {#[cfg(test)]mod tests {+ #[test]+ fn strip_local_suffix_drops_mdns_and_localdomain() {+ use super::strip_local_suffix;+ assert_eq!(strip_local_suffix("Mac.localdomain"), "Mac");+ assert_eq!(+ strip_local_suffix("Dillons-MacBook-Pro-2.local"),+ "Dillons-MacBook-Pro-2"+ );+ assert_eq!(strip_local_suffix("box.LOCAL"), "box");+ assert_eq!(strip_local_suffix("build.example.com"), "build.example.com");+ assert_eq!(strip_local_suffix(".local"), ".local");+ assert_eq!(strip_local_suffix(" ci "), "ci");+ }+use super::*;#[test]diff --git a/libs/cua/crates/cua-host/src/lib.rs b/libs/cua/crates/cua-host/src/lib.rsindex baf7c1e92c..1ae89052a0 100644--- a/libs/cua/crates/cua-host/src/lib.rs+++ b/libs/cua/crates/cua-host/src/lib.rs@@ -48,7 +48,7 @@ pub mod testing;#[cfg(test)]mod tests;-pub use device::{DeviceAuth, DeviceKey, FileKeySlot, KeySlot, MemoryKeySlot};+pub use device::{DeviceAuth, DeviceKey, FileKeySlot, KeySlot, MemoryKeySlot, PendingCode};pub use host::SetupStage;pub use host::{DirectHosting, Host, HostConfig, HostMode, HostPaths, HostPolicy, HostSettingsChange,@@ -65,9 +65,42 @@ pub use relay::{};pub use service::{RunnerKind, ServiceManager, ServiceSpec, ServiceState};-/// The default display name of this device (its host name).+/// The default display name of this device: the macOS Computer Name, else+/// the host name without a `.local` / `.localdomain` suffix.pub fn device_name() -> String {- host::hostname()+ host::friendly_name()+}++/// The relay this machine talks to: `flag` (e.g. `--relay`), else+/// `CUA_RELAY_URL`, else the relay this machine is set up with+/// (`<home>/host/config.json`), else the default relay. The CLI and the+/// app resolve it the same way, so both enroll and approve devices on one+/// relay.+pub fn relay_url_for(flag: Option<&str>, home: &std::path::Path) -> String {+ flag.map(str::trim)+ .filter(|u| !u.is_empty())+ .map(str::to_string)+ .or_else(|| {+ std::env::var("CUA_RELAY_URL")+ .ok()+ .map(|u| u.trim().to_string())+ .filter(|u| !u.is_empty())+ })+ .or_else(|| {+ Host::new(home)+ .config()+ .ok()+ .flatten()?+ .relay_url+ .filter(|u| !u.trim().is_empty())+ })+ .unwrap_or_else(relay_url_from_env)+}++/// Where this device remembers the one-time code it last showed (see+/// [`device::PendingCode`]).+pub fn device_pending_file(home: &std::path::Path) -> std::path::PathBuf {+ home.join("device-pending.json")}/// The operating system a device reports when it registers (`macos`,diff --git a/libs/cua/crates/cua-host/src/relay.rs b/libs/cua/crates/cua-host/src/relay.rsindex 70dfdd51e6..660574ab71 100644--- a/libs/cua/crates/cua-host/src/relay.rs+++ b/libs/cua/crates/cua-host/src/relay.rs@@ -124,8 +124,9 @@ pub struct Machine {/// Connected to the relay now.#[serde(default)]pub online: bool,- /// Accepting clients (false after "Stop sharing").- #[serde(default)]+ /// Accepting clients (false after "Stop sharing"). A relay that does+ /// not send it predates "Stop sharing", so its machines are sharing.+ #[serde(default = "sharing_default")]pub sharing: bool,/// spacesd version reported at connect.#[serde(default)]@@ -796,6 +797,10 @@ fn is_loopback_host(url: &url::Url) -> bool {}}+fn sharing_default() -> bool {+ true+}+#[cfg(test)]mod tests {use super::*;diff --git a/libs/cua/crates/cua-host/src/testing.rs b/libs/cua/crates/cua-host/src/testing.rsindex d197ab1ea7..d8efa8bfce 100644--- a/libs/cua/crates/cua-host/src/testing.rs+++ b/libs/cua/crates/cua-host/src/testing.rs@@ -9,7 +9,10 @@//! sign-in enrollment for every device and re-keying); with//! [`FakeRelay::require_devices`] the machine API refuses account calls//! without an enrolled device's session, as the real relay does after its-//! grace period. Requests to `/m/<id>/…` are recorded and answered 502.+//! grace period. Requests to `/m/<id>/…` are recorded; a machine that+//! stopped sharing refuses them as the real relay does, gRPC-Web requests+//! to a machine given a [`FakeRelay::tunnel`] are forwarded to it, and the+//! rest are answered 502.use crate::relay::{ConnectedClient, Identity, Machine};use axum::extract::{Path, State};@@ -72,6 +75,9 @@ struct State_ {fail_register: std::collections::VecDeque<u16>,/// Machine registrations received (including refused ones).register_calls: usize,+ /// machine id → `(path prefix, base URL)` its `/m/<id>/…` gRPC-Web+ /// requests go to (the longest matching prefix wins).+ tunnels: BTreeMap<String, Vec<(String, String)>>,}impl State_ {@@ -499,10 +505,10 @@ async fn device_register(&& if st.legacy {!has_enrolled && (fresh || !st.require_devices)} else {- // A fresh sign-in enrolls any device of an account with a- // (verified) email; the grace period only the first.- (fresh && (who.email.is_some() || !has_enrolled))- || (!has_enrolled && !st.require_devices)+ // As cua-relay's default policy: a fresh sign-in enrolls any+ // device of the account (verified email or not); the grace+ // period only the first.+ fresh || (!has_enrolled && !st.require_devices)};let machine = body["machine_id"].as_str()@@ -751,7 +757,35 @@ async fn audit(State(s): State<S>, headers: HeaderMap) -> Response {Json(serde_json::json!({ "events": events })).into_response()}-async fn proxied(State(s): State<S>, uri: axum::http::Uri, headers: HeaderMap) -> Response {+async fn proxied(+ State(s): State<S>,+ method: axum::http::Method,+ uri: axum::http::Uri,+ headers: HeaderMap,+ payload: axum::body::Bytes,+) -> Response {+ let (target, refused) = proxied_record(&s, &uri, &headers);+ if let Some(r) = refused {+ return r;+ }+ if let Some(target) = target+ && headers+ .get(axum::http::header::CONTENT_TYPE)+ .and_then(|v| v.to_str().ok())+ .is_some_and(|ct| ct.starts_with("application/grpc-web"))+ {+ return forward(&target, method, &uri, &headers, payload).await;+ }+ err(StatusCode::BAD_GATEWAY, "the fake relay does not tunnel")+}++/// Records a `/m/…` request; the machine's tunnel target, or the relay's+/// refusal.+fn proxied_record(+ s: &S,+ uri: &axum::http::Uri,+ headers: &HeaderMap,+) -> (Option<String>, Option<Response>) {let session = headers.get(crate::relay::DEVICE_SESSION_HEADER).and_then(|v| v.to_str().ok())@@ -764,8 +798,8 @@ async fn proxied(State(s): State<S>, uri: axum::http::Uri, headers: HeaderMap) -.and_then(|rest| rest.split('/').next()).filter(|id| st.machines.contains_key(*id)).map(str::to_string);- if let (Some(machine), Some(Caller::Account(who))) = (machine, caller(&st, &headers)) {- let device = st.device_of(&headers, &who);+ if let (Some(machine), Some(Caller::Account(who))) = (machine, caller(&st, headers)) {+ let device = st.device_of(headers, &who);let event = match &device {Some(d) => serde_json::json!({"ts": now_secs(), "kind": "machine_access", "device": d, "machine": machine, "detail": "owner",@@ -787,7 +821,79 @@ async fn proxied(State(s): State<S>, uri: axum::http::Uri, headers: HeaderMap) -}}st.proxied.push((uri.path().to_string(), session));- err(StatusCode::BAD_GATEWAY, "the fake relay does not tunnel")+ let id = uri+ .path()+ .strip_prefix("/m/")+ .and_then(|rest| rest.split('/').next())+ .unwrap_or("")+ .to_string();+ let content_type = headers+ .get(axum::http::header::CONTENT_TYPE)+ .and_then(|v| v.to_str().ok())+ .unwrap_or("")+ .to_string();+ let is_health = uri.path().ends_with("/health");+ // As the real relay: a machine that stopped sharing refuses everything+ // but its health check (a gRPC caller gets a gRPC status).+ if st.machines.get(&id).is_some_and(|r| !r.machine.sharing) && !is_health {+ let message = "the host stopped sharing this machine";+ if content_type.starts_with("application/grpc") {+ let r = Response::builder()+ .status(StatusCode::OK)+ .header(axum::http::header::CONTENT_TYPE, content_type)+ .header("grpc-status", "7")+ .header("grpc-message", message)+ .body(axum::body::Body::empty())+ .expect("refusal");+ return (None, Some(r));+ }+ return (None, Some((StatusCode::FORBIDDEN, message).into_response()));+ }+ let rest = uri.path().strip_prefix(&format!("/m/{id}")).unwrap_or("");+ let target = st.tunnels.get(&id).and_then(|routes| {+ routes+ .iter()+ .filter(|(prefix, _)| rest.starts_with(prefix.as_str()))+ .max_by_key(|(prefix, _)| prefix.len())+ .map(|(_, target)| target.clone())+ });+ (target, None)+}++/// One gRPC-Web request passed through to `target`, without the+/// `/m/<id>` prefix.+async fn forward(+ target: &str,+ method: axum::http::Method,+ uri: &axum::http::Uri,+ headers: &HeaderMap,+ payload: axum::body::Bytes,+) -> Response {+ let path = uri.path_and_query().map(|p| p.as_str()).unwrap_or("/");+ let path = path+ .strip_prefix("/m/")+ .and_then(|rest| rest.find('/').map(|i| &rest[i..]))+ .unwrap_or(path);+ let url = format!("{}{path}", target.trim_end_matches('/'));+ let mut req = reqwest::Client::new().request(method, url).body(payload);+ for (k, v) in headers {+ if k != axum::http::header::HOST && k != axum::http::header::CONTENT_LENGTH {+ req = req.header(k, v);+ }+ }+ let resp = match req.send().await {+ Ok(r) => r,+ Err(e) => return err(StatusCode::BAD_GATEWAY, &e.to_string()),+ };+ let mut out = Response::builder().status(resp.status());+ for (k, v) in resp.headers() {+ if k != axum::http::header::CONTENT_LENGTH && k != axum::http::header::TRANSFER_ENCODING {+ out = out.header(k, v);+ }+ }+ let bytes = resp.bytes().await.unwrap_or_default();+ out.body(axum::body::Body::from(bytes))+ .unwrap_or_else(|e| err(StatusCode::BAD_GATEWAY, &e.to_string()))}impl FakeRelay {@@ -967,6 +1073,26 @@ impl FakeRelay {self.state.lock().unwrap().proxied.clone()}+ /// Forwards the gRPC-Web requests to `/m/<id>/…` to `target` (a mock+ /// cua-spacesd), without the `/m/<id>` prefix, as if the machine's+ /// driver were connected.+ pub fn tunnel(&self, id: &str, target: &str) {+ self.tunnel_service(id, "", target);+ }++ /// As [`FakeRelay::tunnel`], for the requests whose path (after+ /// `/m/<id>`) starts with `prefix` only, such as+ /// `/cua.env.v1.HostSpacesService/`.+ pub fn tunnel_service(&self, id: &str, prefix: &str, target: &str) {+ self.state+ .lock()+ .unwrap()+ .tunnels+ .entry(id.to_string())+ .or_default()+ .push((prefix.to_string(), target.to_string()));+ }+/// The current machine token of `id`.pub fn machine_token(&self, id: &str) -> Option<String> {self.statediff --git a/libs/cua/crates/cua-host/src/tests.rs b/libs/cua/crates/cua-host/src/tests.rsindex db0712afc8..361e28a0f0 100644--- a/libs/cua/crates/cua-host/src/tests.rs+++ b/libs/cua/crates/cua-host/src/tests.rs@@ -994,7 +994,7 @@ async fn a_fresh_sign_in_enrolls_and_re_keys_this_machine() {assert!(r.superseded.is_empty());// After a fresh sign-in it enrolls, replacing the old key's record.relay.fresh_sign_in("user-1");- let r = signed.enroll_after_sign_in().await.unwrap().unwrap();+ let r = signed.enroll_after_sign_in().await.unwrap();assert_eq!(r.device.state, DeviceState::Enrolled);assert_eq!(r.superseded, vec![old.clone()]);// The name the relay knows stays.@@ -1004,10 +1004,14 @@ async fn a_fresh_sign_in_enrolls_and_re_keys_this_machine() {assert_eq!(list.len(), 1, "{list:?}");assert!(unsigned.session().await.is_err());- // A device that never enrolled creates nothing on sign-in.+ // A device that never enrolled gets its key on sign-in and the fresh+ // sign-in enrolls it under this device's name.let (fresh_device, slot) = device(&relay, "acct", "new");- assert!(fresh_device.enroll_after_sign_in().await.unwrap().is_none());- assert!(slot.load().unwrap().is_none());+ let r = fresh_device.enroll_after_sign_in().await.unwrap();+ assert_eq!(r.device.state, DeviceState::Enrolled);+ assert_eq!(r.device.name, "new");+ assert!(slot.load().unwrap().is_some());+ assert!(fresh_device.session().await.is_ok());// An older relay enrolls only an account's first device by sign-in:// the next one still gets its approval code.@@ -1289,4 +1293,80 @@ async fn status_lists_only_the_permissions_still_missing() {["accessibility"]);assert!(ids(with(Some((true, true))).status().await.unwrap()).is_empty());++ // A machine that only provides Spaces keeps its desktop private: it+ // asks for neither permission.+ let path = f.host().paths().config();+ let mut config: HostConfig = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();+ config.share_desktop = false;+ config.provide_spaces = true;+ std::fs::write(&path, serde_json::to_vec(&config).unwrap()).unwrap();+ assert!(ids(with(None).status().await.unwrap()).is_empty());+}++/// A pending device remembers its code: `enroll` shows the same code again+/// instead of registering anew (which would invalidate it), and forgets it+/// once enrolled.+#[tokio::test]+async fn a_pending_device_reuses_its_remembered_code() {+ let relay = FakeRelay::start().await;+ relay.add_account("acct", "user-1", Some("[email protected]"));+ relay.require_devices(true);+ relay.fresh_sign_in("user-1");+ let (laptop, _) = device(&relay, "acct", "laptop");+ laptop.enroll().await.unwrap();+ relay.stale_sign_in("user-1");+ let dir = tempfile::tempdir().unwrap();+ let file = dir.path().join("device-pending.json");+ let phone = on_machine(+ &relay,+ Arc::new(MemoryKeySlot::default()),+ "phone",+ "phone-1",+ )+ .with_pending_file(&file);+ assert!(phone.pending_code().is_none());+ let first = phone.enroll().await.unwrap();+ let code = first.code.clone().unwrap();+ assert_eq!(phone.pending_code().unwrap().code, code);+ let again = phone.enroll().await.unwrap();+ assert_eq!(again.device.state, DeviceState::Pending);+ assert_eq!(again.code.as_deref(), Some(code.as_str()));+ // The relay still takes the first code.+ let approved = laptop.approve(Some(&code), None).await.unwrap();+ assert_eq!(approved.state, DeviceState::Enrolled);+ // Enrolled: the next enroll registers (and forgets the code).+ let r = phone.enroll().await.unwrap();+ assert_eq!(r.device.state, DeviceState::Enrolled);+ assert!(phone.pending_code().is_none());+ assert!(!file.exists());+}++/// The flag wins; without it (and without `CUA_RELAY_URL`) the relay this+/// machine is set up with, else the default.+#[test]+fn relay_url_for_prefers_flag_then_env_then_host_config() {+ let home = tempfile::tempdir().unwrap();+ assert_eq!(+ crate::relay_url_for(Some(" https://flag.example "), home.path()),+ "https://flag.example"+ );+ let env = std::env::var("CUA_RELAY_URL")+ .ok()+ .filter(|u| !u.trim().is_empty());+ let expected_default = env+ .clone()+ .unwrap_or_else(|| crate::DEFAULT_RELAY_URL.into());+ assert_eq!(crate::relay_url_for(None, home.path()), expected_default);+ let host = Host::new(home.path());+ std::fs::create_dir_all(host.paths().config().parent().unwrap()).unwrap();+ let config = crate::HostConfig {+ relay_url: Some("https://host.example".into()),+ ..Default::default()+ };+ std::fs::write(host.paths().config(), serde_json::to_vec(&config).unwrap()).unwrap();+ assert_eq!(+ crate::relay_url_for(Some(" "), home.path()),+ env.unwrap_or_else(|| "https://host.example".into())+ );}diff --git a/libs/cua/crates/cua-sdk/src/native/auth.rs b/libs/cua/crates/cua-sdk/src/native/auth.rsindex 416c81c9d2..49618d1d6d 100644--- a/libs/cua/crates/cua-sdk/src/native/auth.rs+++ b/libs/cua/crates/cua-sdk/src/native/auth.rs@@ -118,10 +118,11 @@ impl LoginAttempt {/// Waits for the user, stores the session and returns who signed in./// Only the first call waits; later calls fail.///- /// A device that already enrolled (it has a device key) then- /// re-registers with the relay (`CUA_RELAY_URL`, else relay.cua.ai), so- /// the fresh sign-in enrolls or re-verifies it without an approval.- /// That step is best effort and never fails the sign-in.+ /// This device then registers with the relay (the one `cua` uses:+ /// `CUA_RELAY_URL`, else this machine's host setup, else relay.cua.ai),+ /// creating its device key on first use, so the fresh sign-in enrolls+ /// or re-verifies it without an approval. That step is best effort and+ /// never fails the sign-in.pub async fn wait(self: Arc<Self>) -> Result<AuthIdentity> {run(async move {let pending = self@@ -139,18 +140,20 @@ impl LoginAttempt {}}-/// Re-registers this device after an interactive sign-in (see+/// Registers this device after an interactive sign-in (see/// [`LoginAttempt::wait`]).#[cfg(feature = "host")]async fn enroll_after_sign_in(session: &Arc<cua_auth::Session>) {+ let home = cua_daemon::cua_home();let Ok(auth) = cua_host::DeviceAuth::new(- &cua_host::relay_url_from_env(),+ &cua_host::relay_url_for(None, &home),Arc::new(super::host::SessionTokens(session.clone())),Arc::new(session.store().clone()),cua_host::device_name(),) else {return;};+ let auth = auth.with_pending_file(cua_host::device_pending_file(&home));let r = tokio::time::timeout(std::time::Duration::from_secs(15),auth.enroll_after_sign_in(),@@ -161,18 +164,14 @@ async fn enroll_after_sign_in(session: &Arc<cua_auth::Session>) {/// `cua_device_enroll` for a sign-in that enrolled this device: `rekey`/// when it replaced this machine's other key, `sign_in` otherwise. A-/// device that never enrolled (no key) or still waits for an approval-/// records nothing.+/// device that still waits for an approval records nothing.#[cfg(feature = "host")]pub(crate) fn record_sign_in_enrollment<E>(- r: &std::result::Result<- std::result::Result<Option<cua_host::relay::Enrollment>, cua_host::Error>,- E,- >,+ r: &std::result::Result<std::result::Result<cua_host::relay::Enrollment, cua_host::Error>, E>,) {use cua_telemetry::Outcome;let (method, outcome) = match r {- Ok(Ok(Some(e))) if e.device.state == cua_host::relay::DeviceState::Enrolled => (+ Ok(Ok(e)) if e.device.state == cua_host::relay::DeviceState::Enrolled => (if e.superseded.is_empty() {"sign_in"} else {diff --git a/libs/cua/crates/cua-sdk/src/native/host.rs b/libs/cua/crates/cua-sdk/src/native/host.rsindex 33a57ebe8a..a7a3f2a93f 100644--- a/libs/cua/crates/cua-sdk/src/native/host.rs+++ b/libs/cua/crates/cua-sdk/src/native/host.rs@@ -113,13 +113,12 @@ pub struct Relay {#[uniffi::export]impl Relay {- /// A relay (`None` = `CUA_RELAY_URL`, else `https://relay.cua.ai`) seen- /// as the account behind `account_token` (a cua.ai access token).+ /// A relay (`None` = the relay `cua` uses: `CUA_RELAY_URL`, else this+ /// machine's host setup, else `https://relay.cua.ai`) seen as the+ /// account behind `account_token` (a cua.ai access token).#[uniffi::constructor]pub fn new(relay_url: Option<String>, account_token: String) -> Result<Arc<Self>> {- let url = relay_url- .filter(|u| !u.trim().is_empty())- .unwrap_or_else(cua_host::relay_url_from_env);+ let url = cua_host::relay_url_for(relay_url.as_deref(), &cua_daemon::cua_home());Ok(Arc::new(Self {client: cua_host::RelayClient::new(&url)?,account_token,@@ -752,13 +751,13 @@ pub struct Devices {#[uniffi::export]impl Auth {- /// This device on `relay_url` (`None` = `CUA_RELAY_URL`, else+ /// This device on `relay_url` (`None` = the relay `cua` uses:+ /// `CUA_RELAY_URL`, else this machine's host setup, else/// `https://relay.cua.ai`) as the signed-in account, shown as `name`- /// (default: the host name).+ /// (default: this computer's name).pub fn devices(&self, relay_url: Option<String>, name: Option<String>) -> Result<Arc<Devices>> {- let url = relay_url- .filter(|u| !u.trim().is_empty())- .unwrap_or_else(cua_host::relay_url_from_env);+ let home = cua_daemon::cua_home();+ let url = cua_host::relay_url_for(relay_url.as_deref(), &home);let session = self.session();let tokens = Arc::new(SessionTokens(session.clone()));let auth = cua_host::DeviceAuth::new(@@ -767,7 +766,8 @@ impl Auth {Arc::new(session.store().clone()),name.filter(|n| !n.trim().is_empty()).unwrap_or_else(cua_host::device_name),- )?;+ )?+ .with_pending_file(cua_host::device_pending_file(&home));Ok(Arc::new(Devices {auth: Arc::new(auth),tokens,diff --git a/libs/cua/crates/cua-spaces-app-core/src/installer.rs b/libs/cua/crates/cua-spaces-app-core/src/installer.rsindex 8468a9e0bb..db384ad069 100644--- a/libs/cua/crates/cua-spaces-app-core/src/installer.rs+++ b/libs/cua/crates/cua-spaces-app-core/src/installer.rs@@ -177,8 +177,18 @@ impl CliInstaller {pub async fn plan(&self) -> CliInstallPlan {let target = self.target();let installed = target.symlink_metadata().is_ok();+ let installed_version = if installed {+ cli_version(&target).await+ } else {+ None+ };+ // Up to date only when `target` is the bundled CLI and runs as it:+ // another `cua` there (an old Python cua-cli from `uv tool`, say)+ // or one that no longer starts gets replaced.let up_to_date = match (&self.bundled, installed) {- (Some(src), true) => same_file(src, &target),+ (Some(src), true) => {+ same_file(src, &target) && installed_version.as_deref().is_some_and(is_cua_cli)+ }_ => false,};let on_path = path_contains(&self.path_env, &self.bin_dir);@@ -208,11 +218,7 @@ impl CliInstaller {method: self.bundled.as_ref().map(|_| self.method()),installed,up_to_date,- installed_version: if installed {- cli_version(&target).await- } else {- None- },+ installed_version,bundled_version: match &self.bundled {Some(src) => cli_version(src).await,None => None,@@ -259,6 +265,18 @@ impl CliInstaller {let _ = std::fs::remove_file(&staging);format!("cannot install {}: {e}", target.display())})?;+ // What is there now must run as this CLI before the app shows it as+ // "the cua command".+ let version = cli_version(&target).await;+ if !version.as_deref().is_some_and(is_cua_cli) {+ return Err(format!(+ "installed {} but it does not run as the cua CLI (`cua --version` printed {})",+ target.display(),+ version+ .as_deref()+ .map_or("nothing".into(), |v| format!("{v:?}"))+ ));+ }if request.modify_path && !path_contains(&self.path_env, &self.bin_dir) {self.add_to_path()?;}@@ -364,6 +382,24 @@ fn on_path_before(path_env: &str, bin_dir: &Path) -> bool {true}+/// Whether a `cua --version` line is the Rust cua CLI's: `cua <semver>`+/// (an optional suffix such as a build or commit may follow).+pub fn is_cua_cli(version_line: &str) -> bool {+ let mut words = version_line.split_whitespace();+ if words.next() != Some("cua") {+ return false;+ }+ let Some(v) = words.next() else {+ return false;+ };+ let core = v.split(['-', '+']).next().unwrap_or_default();+ let parts: Vec<&str> = core.split('.').collect();+ parts.len() == 3+ && parts+ .iter()+ .all(|p| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit()))+}+/// `ETXTBSY` ("text file busy") on Linux and macOS.const ETXTBSY: i32 = 26;@@ -423,6 +459,17 @@ mod tests {);}+ #[test]+ fn only_the_rust_cli_version_counts_as_cua() {+ assert!(is_cua_cli("cua 0.4.0"));+ assert!(is_cua_cli("cua 1.2.3-rc.1 (abc123)"));+ assert!(!is_cua_cli("cua-cli 0.1.9"));+ assert!(!is_cua_cli("cua, version 0.1.9"));+ assert!(!is_cua_cli("cua 0.4"));+ assert!(!is_cua_cli("Traceback (most recent call last):"));+ assert!(!is_cua_cli(""));+ }+#[test]fn path_contains_matches_whole_entries() {let env = std::env::join_paths(["/usr/bin", "/h/.local/bin"]).unwrap();@@ -469,6 +516,27 @@ mod tests {rc.contains(PATH_MARKER) && rc.contains(".local/bin"),"{rc}");+ // A foreign `cua` at the target (an old Python cua-cli) is not up+ // to date: the next install replaces it.+ std::fs::remove_file(home.join(".local/bin/cua")).unwrap();+ std::fs::write(+ home.join(".local/bin/cua"),+ "#!/bin/sh\necho 'cua, version 0.1.9'\n",+ )+ .unwrap();+ std::fs::set_permissions(+ home.join(".local/bin/cua"),+ std::fs::Permissions::from_mode(0o755),+ )+ .unwrap();+ let plan = cli.plan().await;+ assert!(plan.installed && !plan.up_to_date, "{plan:?}");+ let done = cli.install(&CliInstallRequest::default()).await.unwrap();+ assert!(done.up_to_date, "{done:?}");+ assert_eq!(done.installed_version.as_deref(), Some("cua 1.2.3"));+ // A bundled CLI that does not run as cua is not reported installed.+ std::fs::write(&cua, "#!/bin/sh\nexit 1\n").unwrap();+ assert!(cli.install(&CliInstallRequest::default()).await.is_err());// Without a bundled CLI there is nothing to install.let none = CliInstaller {bundled: None,diff --git a/libs/cua/crates/cua-spaces/Cargo.toml b/libs/cua/crates/cua-spaces/Cargo.tomlindex cb55f0a81b..522fb8c0aa 100644--- a/libs/cua/crates/cua-spaces/Cargo.toml+++ b/libs/cua/crates/cua-spaces/Cargo.toml@@ -101,6 +101,7 @@ cua-fleet = { workspace = true, features = ["testing"] }cua-proto = { workspace = true, features = ["client", "server", "serde"] }tonic = { workspace = true, default-features = false, features = ["codegen", "server", "router", "channel"] }tokio-stream = { workspace = true, features = ["net"] }+tonic-web.workspace = truetokio = { workspace = true, features = ["test-util"] }tempfile.workspace = truereqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls-native-roots"] }diff --git a/libs/cua/crates/cua-spaces/src/host_spaces.rs b/libs/cua/crates/cua-spaces/src/host_spaces.rsindex b470906d4a..4ed85f395e 100644--- a/libs/cua/crates/cua-spaces/src/host_spaces.rs+++ b/libs/cua/crates/cua-spaces/src/host_spaces.rs@@ -780,6 +780,7 @@ impl HostSpacesServer {}.await;if let Err(e) = attached {+ let e = too_old_for_the_relay(e, &image);let _ = self.spaces.delete(&info.id).await;self.audit("failed",@@ -1245,6 +1246,51 @@ pub(crate) async fn forget_provided(spaces: &Spaces, space: &str) {let _ = provided::audit(&dir, "delete", "local", &record.relay_machine, space);}+/// A Space whose cua-spacesd predates `relay_attach` cannot join the relay,+/// so nothing off this machine can reach it: say that, and that the image+/// (not the caller) has to change. The catalog and the image labels do not+/// say which cua-spacesd an image carries, so this is known only once the+/// Space is up.+fn too_old_for_the_relay(e: Error, image: &str) -> Error {+ match e {+ Error::CapabilityMissing {+ space,+ feature,+ limitation,+ } if feature == RELAY_ATTACH_FEATURE => {+ let why = if limitation.is_empty() {+ String::new()+ } else {+ format!(" ({limitation})")+ };+ Error::CapabilityMissing {+ space,+ feature,+ limitation: format!(+ "this image's cua-spacesd is too old to be reached from your other devices{why}; \+ {image} needs republishing with a current cua-spacesd. Update the image (or \+ choose another one) and create the Space again"+ ),+ }+ }+ e => e,+ }+}++/// A machine whose owner stopped sharing it ("Stop sharing" in the app,+/// `cua host stop`): the relay refuses every call to it until they resume.+pub(crate) fn stopped_sharing(name: &str) -> Error {+ Error::Relay(cua_host::Error::PermissionDenied(format!(+ "{name} stopped sharing: ask its owner to Resume sharing (or run `cua host start` there)"+ )))+}++/// Whether a failed connection is the relay refusing a machine that+/// stopped sharing.+pub(crate) fn is_stopped_sharing(reason: &str) -> bool {+ reason.contains("stopped sharing this machine")+}+fn now_ms() -> u64 {std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)@@ -1721,6 +1767,13 @@ impl Spaces {),));}+ if !m.sharing {+ return Err(stopped_sharing(if m.name.is_empty() {+ &m.id+ } else {+ &m.name+ }));+ }if m.role == "viewer" {return Err(Error::Relay(cua_host::Error::PermissionDenied(format!("{} is shared with you to watch only; ask its owner to share it as an editor",@@ -1857,8 +1910,15 @@ impl Spaces {}.await;if let Err(e) = created {- // Nothing runs for it: take the machine off the relay again.- let _ = client.delete(&token, &machine).await;+ // Nothing runs for it: take the machine off the relay again, or+ // it lists as a Space forever (with a fresh token and device+ // session: the host may have taken long to fail).+ if let Err(gone) = self.remove_relay_machine(&machine).await {+ tracing::warn!(+ machine,+ "relay machine of the failed create not removed: {gone}"+ );+ }return Err(e);}// Its driver dials out on its own: wait (bounded) until the relay@@ -2050,15 +2110,23 @@ impl Spaces {let relay = self.relay()?;let token = relay.tokens.access_token().await?;let client = relay.client().await?;- let host = client.machine(&token, host_id).await.map_err(|e| match e {- cua_host::Error::NotFound(_) => Error::NotFound(format!(- "the host of relay:{} (machine {host_id}) is no longer on the relay",- machine.id- )),- other => other.into(),- })?;+ let host = match client.machine(&token, host_id).await {+ Ok(h) => h,+ // Its host is gone (removed, or set up again as a new machine):+ // nothing provides the Space any more, only its relay entry is+ // left.+ Err(cua_host::Error::NotFound(_)) => {+ self.remove_relay_machine(&machine.id).await?;+ return Ok(format!(+ "Removed relay:{}: a stale entry (its host, machine {host_id}, is no longer \+ on the relay).",+ machine.id+ ));+ }+ Err(e) => return Err(e.into()),+ };let space = self.host_space(&host).await?;- let message = space+ let deleted = space.spacesd()?.host_spaces().delete_host_space(pb::DeleteHostSpaceRequest {@@ -2066,7 +2134,26 @@ impl Spaces {}).await.map(|r| r.into_inner().message)- .map_err(|e| from_host(cua_spacesd_client::Error::from(e)))?;+ .map_err(|e| from_host(cua_spacesd_client::Error::from(e)));+ let message = match deleted {+ Ok(m) => m,+ // The host has no such Space (a create that failed before it+ // existed, or the host was set up again): only the relay entry+ // is left.+ Err(Error::NotFound(_)) => {+ self.remove_relay_machine(&machine.id).await?;+ return Ok(format!(+ "Removed relay:{}: a stale entry ({} no longer has this Space).",+ machine.id,+ if host.name.is_empty() {+ &host.id+ } else {+ &host.name+ }+ ));+ }+ Err(e) => return Err(e),+ };match client.delete(&token, &machine.id).await {Ok(()) | Err(cua_host::Error::NotFound(_)) => {}Err(e) => tracing::warn!(machine = %machine.id, "relay machine not removed: {e}"),@@ -2074,6 +2161,19 @@ impl Spaces {Ok(message)}+ /// Removes relay machine `machine` as the signed-in account, with a+ /// fresh token and device session; one already gone counts as removed.+ pub(crate) async fn remove_relay_machine(&self, machine: &str) -> Result<()> {+ let relay = self.relay()?;+ let token = relay.tokens.access_token().await?;+ match relay.client().await?.delete(&token, machine).await {+ Ok(()) | Err(cua_host::Error::NotFound(_)) => {}+ Err(e) => return Err(e.into()),+ }+ let _ = self.relay_machines().await;+ Ok(())+ }+/// Turns a Space a host provides off or on, on that host/// ([`HostSpacesServer::set_power`]).pub(crate) async fn power_on_host(diff --git a/libs/cua/crates/cua-spaces/src/share.rs b/libs/cua/crates/cua-spaces/src/share.rsindex e6772c2d52..6afa0347be 100644--- a/libs/cua/crates/cua-spaces/src/share.rs+++ b/libs/cua/crates/cua-spaces/src/share.rs@@ -523,12 +523,32 @@ impl Spaces {/// removed (and with it every share). A host (`relay:<id>`) is removed/// with `cua host remove` on that machine instead.pub async fn relay_unregister(&self, space: &str) -> Result<bool> {- let id = self.resolve(space)?;+ let id = match self.resolve(space) {+ // A bare relay machine id (`space-…`) is known once the+ // directory was listed.+ Err(Error::NotFound(_)) if self.relay_account().is_some() => {+ let _ = self.relay_machines().await;+ self.resolve(space)?+ }+ other => other?,+ };let canonical = id.to_string();- if matches!(id, SpaceId::Relay { .. }) {- return Err(Error::invalid(format!(- "{canonical} is a host; remove it with `cua host remove` on that machine"- )));+ if let SpaceId::Relay { machine_id } = &id {+ // A Space a host provides (or a stale entry of one) is your+ // account's registration, not a host: take it off the relay.+ let provided = self+ .relay_row(machine_id)+ .await+ .filter(|m| m.role == "owner" && m.host.as_deref().is_some_and(|h| !h.is_empty()));+ if provided.is_none() {+ return Err(Error::invalid(format!(+ "{canonical} is a host; remove it with `cua host remove` on that machine"+ )));+ }+ self.remove_relay_machine(machine_id).await?;+ let _ = self.inner.registry.remove(&canonical);+ self.audit_share("detach", &canonical, &format!("machine={machine_id}"));+ return Ok(true);}let Some(machine) = self.share_machine(&canonical, &id) else {return Ok(false);diff --git a/libs/cua/crates/cua-spaces/src/space.rs b/libs/cua/crates/cua-spaces/src/space.rsindex 6f49eef0f3..e714348ec9 100644--- a/libs/cua/crates/cua-spaces/src/space.rs+++ b/libs/cua/crates/cua-spaces/src/space.rs@@ -503,6 +503,11 @@ pub struct SpaceInfo {/// for other Spaces.#[serde(default, skip_serializing_if = "String::is_empty")]pub cloud_delete: String,+ /// A relay machine the relay says cannot be reached now: `offline`+ /// (its driver is not connected) or `not sharing` (its owner stopped+ /// sharing it). Empty when reachable, and for other Spaces.+ #[serde(default, skip_serializing_if = "String::is_empty")]+ pub status: String,}impl SpaceInfo {@@ -535,6 +540,7 @@ impl SpaceInfo {cloud: record.cloud.clone(),cloud_place: record.cloud_place.clone(),cloud_delete: record.cloud_delete.clone(),+ status: String::new(),})}}diff --git a/libs/cua/crates/cua-spaces/src/spaces.rs b/libs/cua/crates/cua-spaces/src/spaces.rsindex d7b6e4890a..d1beb43609 100644--- a/libs/cua/crates/cua-spaces/src/spaces.rs+++ b/libs/cua/crates/cua-spaces/src/spaces.rs@@ -527,6 +527,13 @@ pub(crate) fn relay_info(m: &crate::relay::RelayMachine) -> SpaceInfo {.cloned().unwrap_or_default(),cloud_delete: String::new(),+ status: if !m.online {+ "offline".into()+ } else if !m.sharing {+ "not sharing".into()+ } else {+ String::new()+ },}}@@ -993,6 +1000,7 @@ impl Spaces {cloud: String::new(),cloud_place: String::new(),cloud_delete: String::new(),+ status: String::new(),}))}@@ -1332,6 +1340,24 @@ impl Spaces {Err(cua_spacesd_client::Error::SpacesdNotAvailable { reason, .. }) => {let generic_ok = matches!(id, SpaceId::Local { .. } | SpaceId::Cloud { .. })|| !services.is_empty();+ if let SpaceId::Relay { machine_id } = &id+ && crate::host_spaces::is_stopped_sharing(&reason)+ {+ // Not a missing driver: its owner stopped sharing it.+ let named = name.filter(|n| !n.is_empty()).map(str::to_string);+ let label = named.or_else(|| {+ self.inner+ .relay_cache+ .lock()+ .expect("relay cache")+ .iter()+ .find(|m| &m.id == machine_id && !m.name.is_empty())+ .map(|m| m.name.clone())+ });+ return Err(crate::host_spaces::stopped_sharing(+ label.as_deref().unwrap_or(&id.to_string()),+ ));+ }if !generic_ok {return Err(Error::SpacesdNotAvailable {space: id.to_string(),@@ -2390,7 +2416,7 @@ impl Spaces {/// The relay directory row of `machine_id` (cached, else refreshed);/// `None` without a relay account or when the relay does not list it.- async fn relay_row(&self, machine_id: &str) -> Option<crate::relay::RelayMachine> {+ pub(crate) async fn relay_row(&self, machine_id: &str) -> Option<crate::relay::RelayMachine> {self.relay_account()?;let cached = self.innerdiff --git a/libs/cua/crates/cua-spaces/tests/host_spaces.rs b/libs/cua/crates/cua-spaces/tests/host_spaces.rsindex fd02b6348b..907b253348 100644--- a/libs/cua/crates/cua-spaces/tests/host_spaces.rs+++ b/libs/cua/crates/cua-spaces/tests/host_spaces.rs@@ -20,7 +20,7 @@ use cua_sandbox_core::{RuntimeError,};use cua_spaces::Spaces;-use cua_spaces::host_spaces::{HostCaller, HostSpacesServer};+use cua_spaces::host_spaces::{HostCaller, HostSpacesServer, to_status};use cua_spacesd_client::testing::{MockAuth, MockServer};use std::collections::BTreeMap;use std::sync::{Arc, Mutex};@@ -34,6 +34,8 @@ struct FakeRuntime {paused: Mutex<std::collections::BTreeSet<String>>,/// Starts never finish (a boot a cancel cuts off).hang: std::sync::atomic::AtomicBool,+ /// Starts fail with this (a container engine that does not answer).+ fail: Mutex<Option<String>>,}#[async_trait]@@ -42,6 +44,9 @@ impl LocalRuntime for FakeRuntime {"fake".into()}async fn start(&self, spec: &LocalStartSpec) -> Result<LocalInstance, RuntimeError> {+ if let Some(e) = self.fail.lock().unwrap().clone() {+ return Err(RuntimeError::Other(e));+ }self.started.lock().unwrap().push(spec.clone());self.running.lock().unwrap().insert(spec.name.clone(), true);if self.hang.load(std::sync::atomic::Ordering::SeqCst) {@@ -167,6 +172,7 @@ async fn runtime_fixture(running: Mutex::default(),paused: Mutex::default(),hang: Default::default(),+ fail: Mutex::default(),});let spaces = Spaces::builder().home(&home)@@ -362,6 +368,33 @@ async fn the_host_creates_attaches_lists_and_deletes_with_an_audit() {assert_eq!(actions[3].1, "<[email protected]> (bob)");}+/// An image whose cua-spacesd predates relay_attach: the create fails+/// saying the image is too old to be reached from other devices and needs+/// republishing, and leaves nothing behind.+#[tokio::test]+async fn an_image_too_old_for_the_relay_says_so_and_is_removed() {+ let f = fixture(HostProfile::Spare).await;+ f.env.state.unadvertise(&["relay_attach"]);+ let attach = f.register("ada-token", "space-ada00001").await;+ let e = f+ .create(&ada(), "linux", attach)+ .await+ .unwrap_err()+ .to_string();+ assert!(+ e.contains("too old to be reached from your other devices"),+ "{e}"+ );+ assert!(e.contains("needs republishing"), "{e}");+ assert!(e.contains("trycua/linux"), "names the image: {e}");+ assert_eq!(+ f.rt.deleted.lock().unwrap().len(),+ 1,+ "the Space is deleted"+ );+ assert!(f.server.get(&ada()).await.unwrap().spaces.is_empty());+}+#[tokio::test]async fn a_host_that_does_not_provide_spaces_refuses_and_says_how() {let f = fixture(HostProfile::Desktop).await;@@ -923,3 +956,274 @@ async fn an_offline_machine_set_up_for_spaces_is_listed_by_name() {let names: Vec<(&str, bool)> = hosts.iter().map(|h| (h.name.as_str(), h.online)).collect();assert_eq!(names, [("Studio", false)]);}++/// The host fixture's `HostSpacesServer` as the host's daemon serves it+/// (every call as ada, the owner: the fake relay does not assert callers).+struct HostSvc(Arc<HostSpacesServer>);++#[tonic::async_trait]+impl pb::host_spaces_service_server::HostSpacesService for HostSvc {+ async fn get_host_spaces(+ &self,+ _req: tonic::Request<pb::GetHostSpacesRequest>,+ ) -> Result<tonic::Response<pb::GetHostSpacesResponse>, tonic::Status> {+ let r = self.0.get(&ada()).await;+ r.map(tonic::Response::new).map_err(|e| to_status(&e))+ }+ async fn create_host_space(+ &self,+ req: tonic::Request<pb::CreateHostSpaceRequest>,+ ) -> Result<tonic::Response<pb::CreateHostSpaceResponse>, tonic::Status> {+ let r = self.0.create(&ada(), req.into_inner()).await;+ r.map(|s| tonic::Response::new(pb::CreateHostSpaceResponse { space: Some(s) }))+ .map_err(|e| to_status(&e))+ }+ async fn delete_host_space(+ &self,+ req: tonic::Request<pb::DeleteHostSpaceRequest>,+ ) -> Result<tonic::Response<pb::DeleteHostSpaceResponse>, tonic::Status> {+ let r = self.0.delete(&ada(), &req.into_inner().space).await;+ r.map(|message| tonic::Response::new(pb::DeleteHostSpaceResponse { message }))+ .map_err(|e| to_status(&e))+ }+ async fn cancel_host_space(+ &self,+ req: tonic::Request<pb::CancelHostSpaceRequest>,+ ) -> Result<tonic::Response<pb::CancelHostSpaceResponse>, tonic::Status> {+ let r = self.0.cancel(&ada(), &req.into_inner().space).await;+ r.map(|message| tonic::Response::new(pb::CancelHostSpaceResponse { message }))+ .map_err(|e| to_status(&e))+ }+ async fn set_host_space_power(+ &self,+ req: tonic::Request<pb::SetHostSpacePowerRequest>,+ ) -> Result<tonic::Response<pb::SetHostSpacePowerResponse>, tonic::Status> {+ let r = req.into_inner();+ let r = self.0.set_power(&ada(), &r.space, r.on).await;+ r.map(tonic::Response::new).map_err(|e| to_status(&e))+ }+ async fn delete_cloud_space(+ &self,+ req: tonic::Request<pb::DeleteCloudSpaceRequest>,+ ) -> Result<tonic::Response<pb::DeleteCloudSpaceResponse>, tonic::Status> {+ let r = self.0.delete_cloud(&ada(), &req.into_inner().space).await;+ r.map(|message| tonic::Response::new(pb::DeleteCloudSpaceResponse { message }))+ .map_err(|e| to_status(&e))+ }+}++/// The client half: the spare host is online on the fake relay (its driver+/// the mock spacesd, advertising host_spaces; its HostSpacesService the+/// fixture's server, over gRPC-Web), and `spaces` is another of ada's+/// devices, signed in to the relay. Returns the host's machine id.+async fn client_fixture(f: &Fixture) -> (String, Spaces, tempfile::TempDir) {+ let relay = cua_host::RelayClient::new(&f.relay.url).unwrap();+ let host = relay+ .machines("ada-token")+ .await+ .unwrap()+ .into_iter()+ .find(|m| m.name == "Mac mini (spare)")+ .expect("the host is on the relay")+ .id;+ f.relay.set_online(&host, true, "1.0.0");+ f.env.state.advertise(&["host_spaces"]);+ f.relay.tunnel(&host, &f.env.url());+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let addr = listener.local_addr().unwrap();+ let svc =+ pb::host_spaces_service_server::HostSpacesServiceServer::new(HostSvc(f.server.clone()));+ tokio::spawn(+ tonic::transport::Server::builder()+ .accept_http1(true)+ .layer(tonic_web::GrpcWebLayer::new())+ .add_service(svc)+ .serve_with_incoming(tokio_stream::wrappers::TcpListenerStream::new(listener)),+ );+ f.relay.tunnel_service(+ &host,+ "/cua.env.v1.HostSpacesService/",+ &format!("http://{addr}"),+ );+ let other = tempfile::tempdir().unwrap();+ let spaces = Spaces::builder()+ .home(other.path())+ .relay(cua_spaces::RelayAccount::new(+ &f.relay.url,+ Arc::new(StaticToken("ada-token".into())),+ ))+ .build();+ (host, spaces, other)+}++/// The relay machines of ada's account a host provides (its Spaces).+async fn provided_machines(f: &Fixture) -> Vec<String> {+ cua_host::RelayClient::new(&f.relay.url)+ .unwrap()+ .machines("ada-token")+ .await+ .unwrap()+ .into_iter()+ .filter(|m| m.host.is_some())+ .map(|m| m.id)+ .collect()+}++fn on_host(name: &str) -> cua_spaces::SpaceCreate {+ cua_spaces::SpaceCreate {+ image: Some("linux".into()),+ on: Some(cua_sandbox_core::placement::On::Host(name.into())),+ ..Default::default()+ }+}++/// A create the host fails before the Space exists (its container engine+/// does not answer) leaves no relay machine behind: the client removes the+/// one it registered, so no ghost Space lists forever.+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn a_create_the_host_fails_leaves_no_relay_space_behind() {+ let f = fixture(HostProfile::Spare).await;+ let (_host, spaces, _other) = client_fixture(&f).await;+ *f.rt.fail.lock().unwrap() = Some("the Docker engine did not answer ping".into());+ let e = spaces+ .create(on_host("Mac mini (spare)"))+ .await+ .unwrap_err()+ .to_string();+ assert!(e.contains("did not answer ping"), "{e}");+ assert!(provided_machines(&f).await.is_empty(), "no ghost Space");+ assert!(+ !spaces+ .list()+ .unwrap()+ .iter()+ .any(|s| s.id.starts_with("relay:space-")),+ "nothing lists"+ );+}++/// A Space's relay entry whose Space the host does not have (left by an+/// older client, or the host was set up again) deletes as a stale entry;+/// one whose host left the relay too. `relay-unregister` takes one off the+/// relay instead of calling it a host.+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn a_stale_relay_space_is_removed_by_delete_or_relay_unregister() {+ let f = fixture(HostProfile::Spare).await;+ let (host, spaces, _other) = client_fixture(&f).await;+ let relay = cua_host::RelayClient::new(&f.relay.url).unwrap();+ let register = |id: &'static str, host: String| {+ let relay = relay.clone();+ async move {+ relay+ .register(+ "ada-token",+ &cua_host::relay::RegisterRequest {+ id: id.into(),+ name: "dogfood-linux".into(),+ allow: vec![],+ host: Some(host),+ meta: Default::default(),+ },+ )+ .await+ .unwrap();+ }+ };++ // The host answers "not a Space this host provides".+ register("space-d8e2e32864eda9c7", host.clone()).await;+ let msg = spaces.delete("relay:space-d8e2e32864eda9c7").await.unwrap();+ assert!(msg.contains("stale entry"), "{msg}");+ assert!(msg.contains("Mac mini (spare)"), "names the host: {msg}");+ assert!(provided_machines(&f).await.is_empty());++ // By the bare machine id, `relay-unregister` removes it (not "a host").+ register("space-00000000000000a1", host.clone()).await;+ assert!(+ spaces+ .relay_unregister("space-00000000000000a1")+ .await+ .unwrap()+ );+ assert!(provided_machines(&f).await.is_empty());+ // A host itself is still refused, and says how.+ let e = spaces+ .relay_unregister(&format!("relay:{host}"))+ .await+ .unwrap_err()+ .to_string();+ assert!(e.contains("cua host remove"), "{e}");++ // Its host left the relay (removed, set up again as a new machine).+ register("space-00000000000000a2", host.clone()).await;+ relay.delete("ada-token", &host).await.unwrap();+ let msg = spaces.delete("relay:space-00000000000000a2").await.unwrap();+ assert!(msg.contains("stale entry"), "{msg}");+ assert!(msg.contains("no longer on the relay"), "{msg}");+ assert!(provided_machines(&f).await.is_empty());+}++/// A host that stopped sharing says so (and how to resume) instead of+/// "has no cua-spacesd", for a create on it and for any call to it; the+/// list marks it, and an offline machine, in text and JSON.+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn a_host_that_stopped_sharing_says_so_and_lists_its_state() {+ let f = fixture(HostProfile::Spare).await;+ let (host, spaces, _other) = client_fixture(&f).await;+ let relay = cua_host::RelayClient::new(&f.relay.url).unwrap();+ relay.stop_sharing("ada-token", &host).await.unwrap();++ let e = spaces+ .create(on_host("Mac mini (spare)"))+ .await+ .unwrap_err();+ let text = e.to_string();+ assert!(+ text.contains(+ "Mac mini (spare) stopped sharing: ask its owner to Resume sharing (or run `cua host start` there)"+ ),+ "{text}"+ );+ assert!(!text.contains("has no cua-spacesd"), "{text}");+ assert_eq!(e.tag(), "permission_denied");+ assert!(provided_machines(&f).await.is_empty(), "nothing registered");++ // Any other call to it, through the relay's refusal.+ let e = spaces+ .space(&format!("relay:{host}"))+ .await+ .unwrap_err()+ .to_string();+ assert!(e.contains("stopped sharing: ask its owner"), "{e}");+ assert!(!e.contains("has no cua-spacesd"), "{e}");++ let _ = spaces.relay_machines().await.unwrap();+ let row = spaces+ .list()+ .unwrap()+ .into_iter()+ .find(|s| s.id == format!("relay:{host}"))+ .unwrap();+ assert_eq!(row.status, "not sharing");+ assert_eq!(serde_json::to_value(&row).unwrap()["status"], "not sharing");+ f.relay.set_online(&host, false, "1.0.0");+ let _ = spaces.relay_machines().await.unwrap();+ let row = spaces+ .list()+ .unwrap()+ .into_iter()+ .find(|s| s.id == format!("relay:{host}"))+ .unwrap();+ assert_eq!(row.status, "offline");+ relay.start_sharing("ada-token", &host).await.unwrap();+ f.relay.set_online(&host, true, "1.0.0");+ let _ = spaces.relay_machines().await.unwrap();+ let row = spaces+ .list()+ .unwrap()+ .into_iter()+ .find(|s| s.id == format!("relay:{host}"))+ .unwrap();+ assert_eq!(row.status, "");+ assert!(serde_json::to_value(&row).unwrap().get("status").is_none());+}diff --git a/libs/cua/crates/cua-spacesd-client/src/testing.rs b/libs/cua/crates/cua-spacesd-client/src/testing.rsindex 050710eabe..60d20fdc0f 100644--- a/libs/cua/crates/cua-spacesd-client/src/testing.rs+++ b/libs/cua/crates/cua-spacesd-client/src/testing.rs@@ -284,6 +284,15 @@ impl MockState {.extend(names.iter().map(|n| n.to_string()));}+ /// Stop advertising features [`Self::advertise`] added (a driver that+ /// predates them).+ pub fn unadvertise(&self, names: &[&str]) {+ self.extra_features+ .lock()+ .unwrap()+ .retain(|f| !names.contains(&f.as_str()));+ }+/// Report `key` as this mock guest's sealed-delivery public key (S1).pub fn set_machine_seal_public_key(&self, key: [u8; 32]) {*self.machine_seal_public_key.lock().unwrap() = key.to_vec();diff --git a/libs/cua/crates/cua-vmm/src/lume/builtin.rs b/libs/cua/crates/cua-vmm/src/lume/builtin.rsindex d59769c960..9730b1c50f 100644--- a/libs/cua/crates/cua-vmm/src/lume/builtin.rs+++ b/libs/cua/crates/cua-vmm/src/lume/builtin.rs@@ -4,8 +4,13 @@//!//! * **Which Lume.** [`LumeSource`] (`cua config set runtime.lume`, the//! apps' Settings): `auto` (the default) uses a Lume already on this Mac-//! and the built-in one otherwise; `builtin` always the built-in one;-//! `system` only the one on this Mac, and never downloads anything.+//! when it is at least [`MIN_VERSION`] and the built-in one otherwise;+//! `builtin` always the built-in one; `system` only the one on this Mac+//! (whatever its version), and never downloads anything.+//! * **Old servers.** A `lume serve` already answering that is older than+//! [`MIN_VERSION`] is never stopped (it may be a user's LaunchAgent):+//! `auto` and `builtin` run a current Lume on the next free port instead+//! ([`super::LumeRuntime::ensure_serving`]).//! * **Pinned and verified.** [`VERSION`] from the trycua/cua release, its//! SHA-256 checked before anything is unpacked, then `codesign --verify`//! and the Developer ID team ([`TEAM_ID`]) checked before it is used. A@@ -40,7 +45,8 @@ pub const SETTING_ENV: &str = "CUA_RUNTIME_LUME";/// Which Lume macOS Spaces run on.#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]pub enum LumeSource {- /// This Mac's Lume when there is one, else the built-in one.+ /// This Mac's Lume when there is one at least [`MIN_VERSION`], else+ /// the built-in one.#[default]Auto,/// Always the built-in one.@@ -122,13 +128,200 @@ pub fn installed() -> Option<PathBuf> {const VERIFIED: &str = ".verified";/// The Lume to run for `source`: this Mac's own (`system`, or `auto` when-/// it has one), else the built-in one when installed.+/// it has one at least [`MIN_VERSION`]), else the built-in one when+/// installed.pub fn resolve(source: LumeSource) -> Option<PathBuf> {let system = || host::which("lume").filter(|p| !p.starts_with(root()));match source {LumeSource::System => system(),LumeSource::Builtin => installed(),- LumeSource::Auto => system().or_else(installed),+ LumeSource::Auto => system()+ .filter(|p| system_binary_usable(source, binary_version(p).as_deref()))+ .or_else(installed),+ }+}++/// The oldest Lume cua runs macOS Spaces on. Lume 0.6.0 is the first+/// release with what cua's client relies on (forced and bounded stop for+/// detached VMs, running without a VNC listener, GPU passthrough), and a+/// real 0.5.3 `lume serve` hung booting the macOS 26 image ("stopped while+/// booting") where 0.6.0 boots it. It is the pin today; it only moves when+/// cua starts needing something newer, not with every pin.+pub const MIN_VERSION: &str = "0.6.0";++/// The first `x.y.z` in `text` (`lume --version` prints `0.6.0`; a+/// `v0.6.0` or `lume 0.6.0-beta` is read the same way).+pub fn parse_version(text: &str) -> Option<(u64, u64, u64)> {+ text.split(|c: char| c.is_whitespace() || c == 'v' || c == '-' || c == '+')+ .find_map(|word| {+ let mut parts = word.split('.');+ let v = (+ parts.next()?.parse().ok()?,+ parts.next()?.parse().ok()?,+ parts.next()?.parse().ok()?,+ );+ parts.next().is_none().then_some(v)+ })+}++/// Whether `version` is at least [`MIN_VERSION`] (an unreadable one is not).+pub fn new_enough(version: &str) -> bool {+ match (parse_version(version), parse_version(MIN_VERSION)) {+ (Some(v), Some(min)) => v >= min,+ _ => false,+ }+}++/// The version `GET /lume/host/status` reports, when it means something:+/// every Lume up to 0.6.0 answered a fixed placeholder `1.0.0` there.+pub fn reported_version(status_version: Option<&str>) -> Option<String> {+ status_version+ .filter(|v| v.trim() != "1.0.0" && parse_version(v).is_some())+ .map(|v| v.trim().to_string())+}++/// What to do with a `lume serve` that already answers.+#[derive(Clone, Debug, PartialEq, Eq)]+pub enum ServerVerdict {+ /// New enough, or its version cannot be told (a remote `LUME_API`,+ /// another user's process): use it, as before.+ Use,+ /// Too old, but `runtime.lume` is `system`: use it and say so.+ UseOld(String),+ /// Too old: run a current Lume on another port instead. The old server+ /// is never stopped (it may be a user's own LaunchAgent).+ Avoid(String),+}++/// The verdict for a server of `version` under `source`.+pub fn judge_server(source: LumeSource, version: Option<&str>) -> ServerVerdict {+ match version {+ None => ServerVerdict::Use,+ Some(v) if new_enough(v) => ServerVerdict::Use,+ Some(v) if source == LumeSource::System => ServerVerdict::UseOld(v.to_string()),+ Some(v) => ServerVerdict::Avoid(v.to_string()),+ }+}++/// Whether this Mac's `lume` (of `version`, `None` when `--version` said+/// nothing) may run Spaces: always for `system`, else only when new enough.+pub fn system_binary_usable(source: LumeSource, version: Option<&str>) -> bool {+ source == LumeSource::System || version.is_some_and(new_enough)+}++/// The ports tried, in order, for a current Lume when the configured one+/// is taken by an old server: the next nine. Fixed, so every cua process+/// on this Mac finds the same one.+pub fn fallback_ports(port: u16) -> impl Iterator<Item = u16> {+ (1..=9u16).filter_map(move |d| port.checked_add(d))+}++/// `url` with its port replaced by `port`.+pub fn with_port(url: &str, port: u16) -> String {+ let url = url.trim_end_matches('/');+ match url.rsplit_once(':') {+ Some((head, p)) if !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit()) => {+ format!("{head}:{port}")+ }+ _ => format!("{url}:{port}"),+ }+}++/// Whether `url` is a server on this Mac.+pub fn is_loopback(url: &str) -> bool {+ let rest = url.split_once("://").map_or(url, |(_, r)| r);+ let host = rest.split('/').next().unwrap_or("");+ let host = match host.strip_prefix('[') {+ Some(v6) => v6.split(']').next().unwrap_or(""),+ None => host.rsplit_once(':').map_or(host, |(h, _)| h),+ };+ matches!(host, "127.0.0.1" | "localhost" | "::1")+}++/// `bin --version` (cached per binary and modification time; bounded to+/// five seconds).+pub fn binary_version(bin: &Path) -> Option<String> {+ use std::collections::HashMap;+ use std::sync::Mutex;+ /// Binary -> (its modification time, its version).+ type Seen = HashMap<PathBuf, (Option<std::time::SystemTime>, Option<String>)>;+ static SEEN: Mutex<Option<Seen>> = Mutex::new(None);+ let bin = std::fs::canonicalize(bin).unwrap_or_else(|_| bin.to_path_buf());+ let mtime = std::fs::metadata(&bin).and_then(|m| m.modified()).ok();+ if let Some((t, v)) = SEEN+ .lock()+ .unwrap_or_else(|e| e.into_inner())+ .get_or_insert_with(HashMap::new)+ .get(&bin)+ && *t == mtime+ {+ return v.clone();+ }+ let v = run_version(&bin);+ SEEN.lock()+ .unwrap_or_else(|e| e.into_inner())+ .get_or_insert_with(HashMap::new)+ .insert(bin, (mtime, v.clone()));+ v+}++fn run_version(bin: &Path) -> Option<String> {+ use std::io::Read as _;+ use std::process::{Command, Stdio};+ let mut child = Command::new(bin)+ .arg("--version")+ .stdin(Stdio::null())+ .stdout(Stdio::piped())+ .stderr(Stdio::null())+ .spawn()+ .ok()?;+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);+ loop {+ match child.try_wait() {+ Ok(Some(_)) => break,+ Ok(None) if std::time::Instant::now() < deadline => {+ std::thread::sleep(std::time::Duration::from_millis(25))+ }+ _ => {+ let _ = child.kill();+ let _ = child.wait();+ return None;+ }+ }+ }+ let mut out = String::new();+ child.stdout.take()?.read_to_string(&mut out).ok()?;+ parse_version(&out).map(|(a, b, c)| format!("{a}.{b}.{c}"))+}++/// The executable of this user's process listening on TCP `port` on this+/// Mac (`lsof`, then `proc_pidpath`); `None` when there is none or it+/// belongs to someone else.+pub fn serving_binary(port: u16) -> Option<PathBuf> {+ #[cfg(target_os = "macos")]+ {+ let out = std::process::Command::new("/usr/sbin/lsof")+ .args(["-nP", &format!("-iTCP:{port}"), "-sTCP:LISTEN", "-t"])+ .stdin(std::process::Stdio::null())+ .stderr(std::process::Stdio::null())+ .output()+ .ok()?;+ let pid: i32 = String::from_utf8_lossy(&out.stdout)+ .lines()+ .find_map(|l| l.trim().parse().ok())?;+ let mut buf = vec![0u8; libc::PROC_PIDPATHINFO_MAXSIZE as usize];+ // SAFETY: `buf` is writable for its full length, which is passed.+ let n = unsafe { libc::proc_pidpath(pid, buf.as_mut_ptr().cast(), buf.len() as u32) };+ if n <= 0 {+ return None;+ }+ buf.truncate(n as usize);+ Some(PathBuf::from(String::from_utf8_lossy(&buf).into_owned()))+ }+ #[cfg(not(target_os = "macos"))]+ {+ let _ = port;+ None}}@@ -307,6 +500,75 @@ mod tests {assert!(LumeSource::Auto.allows_builtin());}+ #[test]+ fn versions_parse_and_compare_against_the_minimum() {+ assert_eq!(parse_version("0.6.0\n"), Some((0, 6, 0)));+ assert_eq!(parse_version("lume v0.5.3"), Some((0, 5, 3)));+ assert_eq!(parse_version("0.7.1-beta.2"), Some((0, 7, 1)));+ assert_eq!(parse_version("Error: unknown option"), None);+ assert_eq!(parse_version("1.2"), None);+ assert!(!new_enough("0.5.3"));+ assert!(new_enough("0.6.0"));+ assert!(new_enough("0.10.0"), "numeric, not lexical");+ assert!(new_enough("1.0.0"));+ assert!(!new_enough("garbage"));+ assert!(new_enough(VERSION), "the pinned Lume is always new enough");+ }++ #[test]+ fn host_status_s_placeholder_version_says_nothing() {+ assert_eq!(reported_version(Some("1.0.0")), None);+ assert_eq!(reported_version(None), None);+ assert_eq!(reported_version(Some("nope")), None);+ assert_eq!(reported_version(Some("0.6.1")), Some("0.6.1".into()));+ }++ #[test]+ fn an_old_server_is_avoided_unless_system_is_chosen() {+ use ServerVerdict::*;+ for s in [LumeSource::Auto, LumeSource::Builtin] {+ assert_eq!(judge_server(s, Some("0.5.3")), Avoid("0.5.3".into()));+ assert_eq!(judge_server(s, Some("0.6.0")), Use);+ assert_eq!(judge_server(s, None), Use, "unknown: as before");+ }+ assert_eq!(+ judge_server(LumeSource::System, Some("0.5.3")),+ UseOld("0.5.3".into())+ );+ assert_eq!(judge_server(LumeSource::System, Some("0.6.0")), Use);+ }++ #[test]+ fn auto_uses_this_mac_s_lume_only_when_new_enough() {+ assert!(!system_binary_usable(LumeSource::Auto, Some("0.5.3")));+ assert!(!system_binary_usable(LumeSource::Auto, None));+ assert!(system_binary_usable(LumeSource::Auto, Some("0.6.0")));+ assert!(system_binary_usable(LumeSource::System, Some("0.5.3")));+ assert!(system_binary_usable(LumeSource::System, None));+ }++ #[test]+ fn fallback_ports_and_urls() {+ assert_eq!(+ fallback_ports(7777).collect::<Vec<_>>(),+ (7778..=7786).collect::<Vec<_>>()+ );+ assert_eq!(fallback_ports(u16::MAX).count(), 0);+ assert_eq!(+ with_port("http://127.0.0.1:7777", 7778),+ "http://127.0.0.1:7778"+ );+ assert_eq!(+ with_port("http://127.0.0.1:7777/", 7779),+ "http://127.0.0.1:7779"+ );+ assert_eq!(with_port("http://localhost", 7778), "http://localhost:7778");+ assert!(is_loopback("http://127.0.0.1:7777"));+ assert!(is_loopback("http://localhost:7777/"));+ assert!(is_loopback("http://[::1]:7777"));+ assert!(!is_loopback("http://10.0.0.5:7777"));+ }+#[test]fn only_cua_s_team_is_accepted() {assert!(team_matches(diff --git a/libs/cua/crates/cua-vmm/src/lume/client.rs b/libs/cua/crates/cua-vmm/src/lume/client.rsindex 714fedd85c..e55ec93542 100644--- a/libs/cua/crates/cua-vmm/src/lume/client.rs+++ b/libs/cua/crates/cua-vmm/src/lume/client.rs@@ -167,7 +167,9 @@ pub fn pull_body(reference: &str, name: &str) -> Value {#[derive(Clone)]pub struct LumeClient {http: reqwest::Client,- base: String,+ /// Shared by every clone, so moving to another `lume serve`+ /// ([`Self::set_base`]) moves them all.+ base: std::sync::Arc<std::sync::RwLock<String>>,}impl LumeClient {@@ -181,16 +183,25 @@ impl LumeClient {.connect_timeout(Duration::from_secs(3)).build().expect("reqwest client"),- base: base.into().trim_end_matches('/').to_string(),+ base: std::sync::Arc::new(std::sync::RwLock::new(+ base.into().trim_end_matches('/').to_string(),+ )),}}- pub fn base(&self) -> &str {- &self.base+ pub fn base(&self) -> String {+ self.base.read().unwrap_or_else(|e| e.into_inner()).clone()+ }++ /// Talks to the `lume serve` at `base` from now on (this client and+ /// every clone of it).+ pub fn set_base(&self, base: &str) {+ *self.base.write().unwrap_or_else(|e| e.into_inner()) =+ base.trim_end_matches('/').to_string();}fn url(&self, path: &str) -> String {- format!("{}{}", self.base, path)+ format!("{}{}", self.base(), path)}async fn check(resp: reqwest::Response) -> Result<reqwest::Response> {@@ -230,7 +241,7 @@ impl LumeClient {fn net_err(&self, e: reqwest::Error) -> VmmError {if e.is_connect() {VmmError::missing(- format!("lume serve at {}", self.base),+ format!("lume serve at {}", self.base()),"not reachable; start it with `lume serve` (cua starts it automatically when the binary is installed)",)} else {@@ -248,6 +259,22 @@ impl LumeClient {.is_ok()}+ /// The version the server reports in `GET /lume/host/status`, when it+ /// means something ([`super::builtin::reported_version`]).+ pub async fn reported_version(&self) -> Option<String> {+ let status: Value = self+ .http+ .get(self.url("/lume/host/status"))+ .timeout(Duration::from_secs(3))+ .send()+ .await+ .ok()?+ .json()+ .await+ .ok()?;+ super::builtin::reported_version(status.get("version").and_then(Value::as_str))+ }+/// `GET /lume/host/status`.pub async fn host_status(&self) -> Result<Value> {let r = selfdiff --git a/libs/cua/crates/cua-vmm/src/lume/mod.rs b/libs/cua/crates/cua-vmm/src/lume/mod.rsindex 662bc2cf65..eaf93935ed 100644--- a/libs/cua/crates/cua-vmm/src/lume/mod.rs+++ b/libs/cua/crates/cua-vmm/src/lume/mod.rs@@ -67,7 +67,9 @@ pub struct LumeConfig {impl Default for LumeConfig {fn default() -> Self {Self {- url: std::env::var("LUME_API").unwrap_or_else(|_| "http://127.0.0.1:7777".into()),+ url: serving_url(+ &std::env::var("LUME_API").unwrap_or_else(|_| "http://127.0.0.1:7777".into()),+ ),spawn_serve: true,allow_install: false,root: host::cua_home().join("vmm").join("lume"),@@ -84,6 +86,64 @@ pub struct LumeRuntime {client: LumeClient,/// The host preference GPU acceleration sets ([`gpu`]).gpu_pref: Arc<dyn gpu::GpuPreference>,+ /// The `lume serve` URL already checked ([`builtin::judge_server`]).+ accepted: std::sync::Mutex<Option<String>>,+ /// The version of a too-old Lume `runtime.lume = system` made cua use,+ /// named in a failed start.+ old_lume: std::sync::Mutex<Option<String>>,+}++/// Configured `lume serve` URL -> the one this process moved to because an+/// old Lume answers at the configured one ([`LumeRuntime::ensure_serving`]).+static MOVED: std::sync::Mutex<Vec<(String, String)>> = std::sync::Mutex::new(Vec::new());++/// The `lume serve` URL to use for `configured`: where this process moved+/// to, if it did.+pub fn serving_url(configured: &str) -> String {+ let configured = configured.trim_end_matches('/');+ MOVED+ .lock()+ .unwrap_or_else(|e| e.into_inner())+ .iter()+ .find(|(from, _)| from == configured)+ .map_or_else(|| configured.to_string(), |(_, to)| to.clone())+}++fn remember_move(from: &str, to: &str) {+ let from = from.trim_end_matches('/').to_string();+ let mut moved = MOVED.lock().unwrap_or_else(|e| e.into_inner());+ moved.retain(|(f, _)| *f != from);+ moved.push((from, to.trim_end_matches('/').to_string()));+}++/// The version of the `lume serve` at `client`: what it reports, else (on+/// this Mac) its executable's `--version`.+async fn server_version(client: &LumeClient) -> Option<String> {+ if let Some(v) = client.reported_version().await {+ return Some(v);+ }+ let url = client.base();+ if !builtin::is_loopback(&url) {+ return None;+ }+ let port = url_port(&url)?;+ tokio::task::spawn_blocking(move || {+ // Only a `lume` is asked for its version (never, say, a test's+ // own fake server process).+ builtin::serving_binary(port)+ .filter(|b| b.file_name().is_some_and(|n| n == "lume"))+ .and_then(|b| builtin::binary_version(&b))+ })+ .await+ .ok()+ .flatten()+}++fn url_port(url: &str) -> Option<u16> {+ url.trim_end_matches('/')+ .rsplit(':')+ .next()+ .and_then(|p| p.parse().ok())}/// The reference `lume pull` takes: `tag-ref@sha256:…` (how the daemon@@ -178,11 +238,13 @@ impl Drop for CloneGuard {impl LumeRuntime {pub fn new(cfg: LumeConfig) -> Self {- let client = LumeClient::new(cfg.url.clone());+ let client = LumeClient::new(serving_url(&cfg.url));Self {cfg,client,gpu_pref: Arc::new(gpu::Defaults),+ accepted: Default::default(),+ old_lume: Default::default(),}}@@ -226,21 +288,109 @@ impl LumeRuntime {&self.client}+ /// The port of the `lume serve` in use (moved off the configured one+ /// when an old Lume holds it).fn port(&self) -> u16 {- self.cfg- .url- .rsplit(':')- .next()- .and_then(|p| p.trim_end_matches('/').parse().ok())- .unwrap_or(7777)+ url_port(&self.client.base()).unwrap_or(7777)}- /// Make sure `lume serve` answers, starting (and, if allowed, installing)- /// it as needed. Never restarts or stops a server that is already running.+ /// Make sure a current `lume serve` answers, starting (and, if allowed,+ /// installing) it as needed. Never restarts or stops a server that is+ /// already running: when the one answering is older than+ /// [`builtin::MIN_VERSION`] (say a user's own LaunchAgent), `auto` and+ /// `builtin` run a current Lume on the next free port instead and use+ /// that from then on; `system` uses it and names it in a failed start.pub async fn ensure_serving(&self) -> Result<()> {if self.client.reachable().await {+ let url = self.client.base();+ if self+ .accepted+ .lock()+ .unwrap_or_else(|e| e.into_inner())+ .as_deref()+ == Some(url.as_str())+ {+ return Ok(());+ }+ let source = builtin::LumeSource::current();+ match builtin::judge_server(source, server_version(&self.client).await.as_deref()) {+ builtin::ServerVerdict::Use => {}+ builtin::ServerVerdict::UseOld(v) => {+ tracing::warn!(+ url = %url,+ version = %v,+ minimum = builtin::MIN_VERSION,+ "lume serve is older than cua needs; using it because runtime.lume is system"+ );+ *self.old_lume.lock().unwrap_or_else(|e| e.into_inner()) = Some(v);+ }+ builtin::ServerVerdict::Avoid(v) => return self.serve_elsewhere(&url, &v).await,+ }+ *self.accepted.lock().unwrap_or_else(|e| e.into_inner()) = Some(url);return Ok(());}+ self.spawn_serve().await+ }++ /// The `lume serve` at `old_url` is Lume `old` (too old): use a current+ /// one on the first of [`builtin::fallback_ports`] that has one or is+ /// free, starting it there. The old server keeps running untouched.+ async fn serve_elsewhere(&self, old_url: &str, old: &str) -> Result<()> {+ let too_old = format!(+ "lume serve at {old_url} is Lume {old}, and macOS Spaces need Lume {} or newer",+ builtin::MIN_VERSION+ );+ if !self.cfg.spawn_serve {+ return Err(VmmError::missing(+ too_old,+ "update it (or stop it and let cua run its built-in Lume)",+ ));+ }+ let port = url_port(old_url).unwrap_or(7777);+ for p in builtin::fallback_ports(port) {+ let url = builtin::with_port(old_url, p);+ let candidate = LumeClient::new(url.clone());+ if candidate.reachable().await {+ // Only a Lume known to be current (cua's own from an earlier+ // run); anything else on the port is left alone.+ if server_version(&candidate)+ .await+ .is_some_and(|v| builtin::new_enough(&v))+ {+ tracing::info!(%url, "using the current lume serve next to an old one");+ self.client.set_base(&url);+ remember_move(&self.cfg.url, &url);+ *self.accepted.lock().unwrap_or_else(|e| e.into_inner()) = Some(url);+ return Ok(());+ }+ continue;+ }+ if std::net::TcpListener::bind(("127.0.0.1", p)).is_err() {+ continue; // something else holds it+ }+ tracing::warn!(+ old = %old_url,+ version = %old,+ %url,+ "lume serve is older than cua needs; leaving it running and starting a current Lume on another port"+ );+ self.client.set_base(&url);+ remember_move(&self.cfg.url, &url);+ return self.spawn_serve().await;+ }+ Err(VmmError::missing(+ too_old,+ format!(+ "ports {}-{} are taken too; update or stop that Lume",+ port.saturating_add(1),+ port.saturating_add(9)+ ),+ ))+ }++ /// Starts `lume serve` on [`Self::port`] (installing Lume as allowed)+ /// and waits for it to answer.+ async fn spawn_serve(&self) -> Result<()> {if !cfg!(target_os = "macos") {return Err(VmmError::missing("Lume",@@ -249,7 +399,7 @@ impl LumeRuntime {}if !self.cfg.spawn_serve {return Err(VmmError::missing(- format!("lume serve at {}", self.cfg.url),+ format!("lume serve at {}", self.client.base()),"start it with `lume serve`",));}@@ -283,6 +433,17 @@ impl LumeRuntime {));}};+ if source == builtin::LumeSource::System+ && let Some(v) = builtin::binary_version(&bin).filter(|v| !builtin::new_enough(v))+ {+ tracing::warn!(+ bin = %bin.display(),+ version = %v,+ minimum = builtin::MIN_VERSION,+ "this Mac's Lume is older than cua needs; using it because runtime.lume is system"+ );+ *self.old_lume.lock().unwrap_or_else(|e| e.into_inner()) = Some(v);+ }std::fs::create_dir_all(&self.cfg.root)?;let log = std::fs::File::create(self.cfg.root.join("serve.log"))?;let mut cmd = std::process::Command::new(&bin);@@ -300,13 +461,14 @@ impl LumeRuntime {let deadline = tokio::time::Instant::now() + Duration::from_secs(30);while tokio::time::Instant::now() < deadline {if self.client.reachable().await {+ *self.accepted.lock().unwrap_or_else(|e| e.into_inner()) = Some(self.client.base());return Ok(());}tokio::time::sleep(Duration::from_millis(500)).await;}Err(VmmError::other(format!("started `lume serve` but {} did not answer within 30s (see {})",- self.cfg.url,+ self.client.base(),self.cfg.root.join("serve.log").display())))}@@ -980,17 +1142,10 @@ pub fn lume_installed_marker() -> PathBuf {/// Logs the Lume installer's LaunchAgent writes (`lume serve` as a daemon).pub const LUME_DAEMON_LOGS: [&str; 2] = ["/tmp/lume_daemon.log", "/tmp/lume_daemon.error.log"];-#[async_trait]-impl Runtime for LumeRuntime {- fn kind(&self) -> BackendKind {- BackendKind::Lume- }-- async fn ensure_base(&self, image: &ImageSource, base_name: &str) -> Result<CheckpointInfo> {- self.ensure_base_with(image, base_name, None).await- }-- async fn start(&self, spec: &StartSpec) -> Result<Instance> {+impl LumeRuntime {+ /// Starts `spec`; sets `created` once a new VM exists in Lume (a clone+ /// or a Linux VM shell), so a failure after that deletes it.+ async fn start_vm(&self, spec: &StartSpec, created: &mut bool) -> Result<Instance> {validate_name(&spec.name)?;crate::types::reject_sidecars(BackendKind::Lume, spec)?;crate::types::reject_gpu(@@ -1079,6 +1234,7 @@ impl Runtime for LumeRuntime {.clone_vm(&base, &spec.name).await.inspect_err(|_| made.done())?;+ *created = true;OwnedVms::default().mark(&spec.name, OwnedKind::Instance, Some(&base));OwnedVms::default().touch(&base);// A clone inherits the base's CPU, memory and disk: apply the@@ -1125,6 +1281,7 @@ impl Runtime for LumeRuntime {storage: None,}).await?;+ *created = true;OwnedVms::default().mark(&spec.name, OwnedKind::Instance, None);// Creation is asynchronous; wait until the VM shell exists.let deadline = tokio::time::Instant::now() + Duration::from_secs(120);@@ -1181,7 +1338,7 @@ impl Runtime for LumeRuntime {Ok(inst)}- async fn stop(&self, name: &str) -> Result<()> {+ async fn stop_vm(&self, name: &str) -> Result<()> {self.ensure_serving().await?;match self.client.get(name).await? {None => Err(VmmError::NotFound(name.into())),@@ -1190,6 +1347,72 @@ impl Runtime for LumeRuntime {}}+ /// Deletes `name`, which this start created and failed to bring up+ /// with `why`. Best effort: a failure to delete is logged.+ async fn discard_failed(&self, name: &str, why: &VmmError) {+ match Runtime::delete(self, name).await {+ Ok(()) | Err(VmmError::NotFound(_)) => {+ tracing::info!(vm = name, error = %why, "deleted a VM whose create failed")+ }+ Err(e) => {+ tracing::warn!(vm = name, error = %e, "could not delete a VM whose create failed")+ }+ }+ }++ /// `e`, naming the too-old Lume `runtime.lume = system` made cua use.+ fn name_old_lume(&self, e: VmmError) -> VmmError {+ let old = self+ .old_lume+ .lock()+ .unwrap_or_else(|e| e.into_inner())+ .clone();+ match (old, e) {+ (+ Some(v),+ e @ (VmmError::Lume { .. } | VmmError::Timeout { .. } | VmmError::Other(_)),+ ) => VmmError::other(format!(+ "{e}. This Mac's Lume is {v}, older than the {} macOS Spaces need: update it, \+ or choose Built-in for macOS VMs in Settings (`cua config set runtime.lume builtin`)",+ builtin::MIN_VERSION+ )),+ (_, e) => e,+ }+ }+}++#[async_trait]+impl Runtime for LumeRuntime {+ fn kind(&self) -> BackendKind {+ BackendKind::Lume+ }++ async fn ensure_base(&self, image: &ImageSource, base_name: &str) -> Result<CheckpointInfo> {+ self.ensure_base_with(image, base_name, None).await+ }++ async fn start(&self, spec: &StartSpec) -> Result<Instance> {+ let mut created = false;+ match self.start_vm(spec, &mut created).await {+ Ok(inst) => Ok(inst),+ Err(e) => {+ // A VM this start made and could not bring up (it stopped+ // while booting, never got an address, its services never+ // answered) is deleted again: left behind it holds tens of+ // GB and its name, so the next create would boot the+ // broken one instead of a new one.+ if created {+ self.discard_failed(&spec.name, &e).await;+ }+ Err(self.name_old_lume(e))+ }+ }+ }++ async fn stop(&self, name: &str) -> Result<()> {+ self.stop_vm(name).await+ }+/// Lume has no in-memory pause: suspending stops the VM (its disk and/// setup share stay) and [`Runtime::resume`] boots it again, so `cua sb/// suspend` / `resume` work for macOS Spaces as they do for the others.diff --git a/libs/cua/crates/cua-vmm/src/probe.rs b/libs/cua/crates/cua-vmm/src/probe.rsindex 58e21ae42f..d43afda678 100644--- a/libs/cua/crates/cua-vmm/src/probe.rs+++ b/libs/cua/crates/cua-vmm/src/probe.rs@@ -139,24 +139,33 @@ fn unreachable_error_for(exe: Option<&std::path::Path>,) -> VmmError {if cfg!(target_os = "macos") {+ // macOS asks once per boot, on this Mac's own screen, the first time+ // the app reaches the local network, and lists the app under Local+ // Network only after it has asked. Someone using this Mac from+ // another device may never see the prompt, so say all three ways.let bundle = exe.and_then(app_bundle);- let (who, allow) = match &bundle {- Some((name, path)) => (- format!("{name} ({})", path.display()),- format!("turn on {name} there"),+ let hint = match &bundle {+ Some((name, path)) => format!(+ "{name} ({}) cannot reach the VM at {addr} ({error}). macOS blocks {name}'s \+ local network connections until they are allowed: on this Mac's screen macOS \+ asks \"Allow \"{name}\" to find devices on local networks?\"; click Allow \+ there. If {name} is listed under System Settings > Privacy & Security > Local \+ Network, turn it on; if it isn't listed, quit and reopen {name} on this Mac \+ (macOS asks again). Then try again",+ path.display()),- None => (- "cua".to_string(),- "turn on the app that started cua (for example your terminal) there".to_string(),+ None => format!(+ "cua cannot reach the VM at {addr} ({error}). macOS blocks an app's local \+ network connections until they are allowed: on this Mac's screen macOS asks \+ whether the app that started cua (for example your terminal) may find devices \+ on local networks; click Allow there. If that app is listed under System \+ Settings > Privacy & Security > Local Network, turn it on; if it isn't \+ listed, quit and reopen it on this Mac (macOS asks again). Then try again"),};VmmError::Missing {what: "Local Network access".into(),- hint: format!(- "{who} cannot reach the VM at {addr} ({error}). macOS blocks an app's local \- network connections until they are allowed: open System Settings > Privacy & \- Security > Local Network, {allow}, then try again"- ),+ hint,}} else {VmmError::Missing {@@ -370,7 +379,19 @@ mod tests {"{text}");assert!(- text.contains("Privacy & Security > Local Network, turn on Cua Spaces there"),+ text.contains(+ "on this Mac's screen macOS asks \"Allow \"Cua Spaces\" to find devices on local networks?\"; click Allow there"+ ),+ "{text}"+ );+ assert!(+ text.contains(+ "If Cua Spaces is listed under System Settings > Privacy & Security > Local Network, turn it on"+ ),+ "{text}"+ );+ assert!(+ text.contains("if it isn't listed, quit and reopen Cua Spaces on this Mac (macOS asks again). Then try again"),"{text}");// Outside a bundle (a terminal's `cua`) it says what to allow.diff --git a/libs/cua/crates/cua-vmm/tests/lume_clone_resources.rs b/libs/cua/crates/cua-vmm/tests/lume_clone_resources.rsindex a160a68ebc..92fbe4324e 100644--- a/libs/cua/crates/cua-vmm/tests/lume_clone_resources.rs+++ b/libs/cua/crates/cua-vmm/tests/lume_clone_resources.rs@@ -27,10 +27,14 @@ use serde_json::json;const REF: &str = "ghcr.io/trycua/macos:26";async fn fake_runtime(fail_set: bool) -> (LumeRuntime, Arc<Mutex<FakeLume>>) {- let mut st = FakeLume {+ fake_runtime_with(FakeLume {fail_set,..Default::default()- };+ })+ .await+}++async fn fake_runtime_with(mut st: FakeLume) -> (LumeRuntime, Arc<Mutex<FakeLume>>) {let base = base_vm_name(REF);st.vms.insert(base.clone(),@@ -101,6 +105,52 @@ async fn a_refused_set_deletes_the_clone_and_never_boots() {assert!(!st.calls.iter().any(|(_, p, _)| p.ends_with("/run")));}+/// A clone that stops while booting is deleted again, so a failed create+/// leaves no tens-of-GB VM behind and the next create with the same name+/// clones afresh instead of booting the broken one.+#[tokio::test]+async fn a_clone_that_fails_to_boot_is_deleted() {+ let (rt, state) = fake_runtime_with(FakeLume {+ boot_fails: true,+ ..Default::default()+ })+ .await;+ let err = rt.start(&spec("cua-e2e-crash", REF)).await.unwrap_err();+ assert!(err.to_string().contains("stopped while booting"), "{err}");+ let st = state.lock().unwrap();+ assert!(+ !st.vms.contains_key("cua-e2e-crash"),+ "the failed clone is gone: {:#?}",+ st.calls+ );+ assert!(+ st.calls+ .iter()+ .any(|(m, p, _)| m == "DELETE" && p == "/lume/vms/cua-e2e-crash")+ );+ // The base it was cloned from stays.+ assert!(st.vms.contains_key(&base_vm_name(REF)));+}++/// A start that boots a VM that already existed never deletes it when the+/// boot fails (it holds someone's disk).+#[tokio::test]+async fn an_existing_vm_that_fails_to_boot_is_kept() {+ let mut st = FakeLume {+ boot_fails: true,+ ..Default::default()+ };+ st.vms.insert(+ "cua-e2e-kept".into(),+ json!({ "name": "cua-e2e-kept", "os": "macOS", "status": "stopped" }),+ );+ let (rt, state) = fake_runtime_with(st).await;+ rt.start(&spec("cua-e2e-kept", REF)).await.unwrap_err();+ let st = state.lock().unwrap();+ assert!(st.vms.contains_key("cua-e2e-kept"));+ assert!(!st.calls.iter().any(|(m, _, _)| m == "DELETE"));+}+/// Opt-in live check against the real `lume serve`; see the module docs.#[tokio::test]async fn live_clone_boots_with_the_requested_memory() {diff --git a/libs/cua/crates/cua-vmm/tests/support/fake_lume.rs b/libs/cua/crates/cua-vmm/tests/support/fake_lume.rsindex f40e7c8899..68f03b0dfa 100644--- a/libs/cua/crates/cua-vmm/tests/support/fake_lume.rs+++ b/libs/cua/crates/cua-vmm/tests/support/fake_lume.rs@@ -36,6 +36,9 @@ pub struct FakeLume {/// `POST /lume/vms/:name/run` never answers (a boot a cancelled create/// cut off).pub hang_run: bool,+ /// A booted VM stops on its own before it gets an address (the guest+ /// crashed: "stopped while booting").+ pub boot_fails: bool,}fn not_found(name: &str) -> (u16, Value) {@@ -61,8 +64,14 @@ fn handle(st: &mut FakeLume, method: &str, path: &str, body: Value) -> (u16, Valst.vms.insert(new, vm);(200, json!({ "message": "cloned" }))}- ("GET", _) => match st.vms.get(name) {- Some(vm) => (200, vm.clone()),+ ("GET", _) => match st.vms.get_mut(name) {+ Some(vm) => {+ let seen = vm.clone();+ if vm.get("crashing").is_some() {+ vm["status"] = json!("stopped");+ }+ (200, seen)+ }None => not_found(name),},("PATCH", _) => {@@ -91,7 +100,12 @@ fn handle(st: &mut FakeLume, method: &str, path: &str, body: Value) -> (u16, Valreturn not_found(name);};vm["status"] = json!("running");- vm["ipAddress"] = json!("192.0.2.10");+ if st.boot_fails {+ // Seen running once, then stopped, never with an address.+ vm["crashing"] = json!(true);+ } else {+ vm["ipAddress"] = json!("192.0.2.10");+ }(202, json!({ "message": "starting" }))}("POST", p) if p.ends_with("/stop") => {diff --git a/libs/cua/kotlin/src/main/kotlin/ai/cua/sdk/cua_sdk.kt b/libs/cua/kotlin/src/main/kotlin/ai/cua/sdk/cua_sdk.ktindex 3ab9b0d58b..a43c3c522f 100644--- a/libs/cua/kotlin/src/main/kotlin/ai/cua/sdk/cua_sdk.kt+++ b/libs/cua/kotlin/src/main/kotlin/ai/cua/sdk/cua_sdk.kt@@ -3036,7 +3036,7 @@ private fun uniffiCheckApiChecksums(lib: IntegrityCheckingUniffiLib) {if (lib.uniffi_cua_sdk_checksum_method_auth_status() != 29264.toShort()) {throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")}- if (lib.uniffi_cua_sdk_checksum_method_auth_devices() != 24953.toShort()) {+ if (lib.uniffi_cua_sdk_checksum_method_auth_devices() != 36673.toShort()) {throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")}if (lib.uniffi_cua_sdk_checksum_method_loginattempt_method() != 60787.toShort()) {@@ -3051,7 +3051,7 @@ private fun uniffiCheckApiChecksums(lib: IntegrityCheckingUniffiLib) {if (lib.uniffi_cua_sdk_checksum_method_loginattempt_user_code() != 37591.toShort()) {throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")}- if (lib.uniffi_cua_sdk_checksum_method_loginattempt_wait() != 2942.toShort()) {+ if (lib.uniffi_cua_sdk_checksum_method_loginattempt_wait() != 16950.toShort()) {throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")}if (lib.uniffi_cua_sdk_checksum_method_cua_agent_setup() != 50422.toShort()) {@@ -4077,7 +4077,7 @@ private fun uniffiCheckApiChecksums(lib: IntegrityCheckingUniffiLib) {if (lib.uniffi_cua_sdk_checksum_constructor_host_new() != 62533.toShort()) {throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")}- if (lib.uniffi_cua_sdk_checksum_constructor_relay_new() != 59964.toShort()) {+ if (lib.uniffi_cua_sdk_checksum_constructor_relay_new() != 19970.toShort()) {throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")}if (lib.uniffi_cua_sdk_checksum_constructor_presenceview_new() != 9981.toShort()) {@@ -6840,9 +6840,10 @@ public interface AuthInterface {fun `status`(): AuthStatus/**- * This device on `relay_url` (`None` = `CUA_RELAY_URL`, else+ * This device on `relay_url` (`None` = the relay `cua` uses:+ * `CUA_RELAY_URL`, else this machine's host setup, else* `https://relay.cua.ai`) as the signed-in account, shown as `name`- * (default: the host name).+ * (default: this computer's name).*/fun `devices`(`relayUrl`: kotlin.String?, `name`: kotlin.String?): Devices@@ -7042,9 +7043,10 @@ open class Auth: Disposable, AutoCloseable, AuthInterface/**- * This device on `relay_url` (`None` = `CUA_RELAY_URL`, else+ * This device on `relay_url` (`None` = the relay `cua` uses:+ * `CUA_RELAY_URL`, else this machine's host setup, else* `https://relay.cua.ai`) as the signed-in account, shown as `name`- * (default: the host name).+ * (default: this computer's name).*/@Throws(CuaException::class)override fun `devices`(`relayUrl`: kotlin.String?, `name`: kotlin.String?): Devices {return FfiConverterTypeDevices.lift(@@ -11308,10 +11310,11 @@ public interface LoginAttemptInterface {* Waits for the user, stores the session and returns who signed in.* Only the first call waits; later calls fail.*- * A device that already enrolled (it has a device key) then- * re-registers with the relay (`CUA_RELAY_URL`, else relay.cua.ai), so- * the fresh sign-in enrolls or re-verifies it without an approval.- * That step is best effort and never fails the sign-in.+ * This device then registers with the relay (the one `cua` uses:+ * `CUA_RELAY_URL`, else this machine's host setup, else relay.cua.ai),+ * creating its device key on first use, so the fresh sign-in enrolls+ * or re-verifies it without an approval. That step is best effort and+ * never fails the sign-in.*/suspend fun `wait`(): AuthIdentity@@ -11486,10 +11489,11 @@ open class LoginAttempt: Disposable, AutoCloseable, LoginAttemptInterface* Waits for the user, stores the session and returns who signed in.* Only the first call waits; later calls fail.*- * A device that already enrolled (it has a device key) then- * re-registers with the relay (`CUA_RELAY_URL`, else relay.cua.ai), so- * the fresh sign-in enrolls or re-verifies it without an approval.- * That step is best effort and never fails the sign-in.+ * This device then registers with the relay (the one `cua` uses:+ * `CUA_RELAY_URL`, else this machine's host setup, else relay.cua.ai),+ * creating its device key on first use, so the fresh sign-in enrolls+ * or re-verifies it without an approval. That step is best effort and+ * never fails the sign-in.*/@Throws(CuaException::class)@Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE")@@ -13472,8 +13476,9 @@ open class Relay: Disposable, AutoCloseable, RelayInterfacethis.cleanable = null}/**- * A relay (`None` = `CUA_RELAY_URL`, else `https://relay.cua.ai`) seen- * as the account behind `account_token` (a cua.ai access token).+ * A relay (`None` = the relay `cua` uses: `CUA_RELAY_URL`, else this+ * machine's host setup, else `https://relay.cua.ai`) seen as the+ * account behind `account_token` (a cua.ai access token).*/constructor(`relayUrl`: kotlin.String?, `accountToken`: kotlin.String) :this(UniffiWithHandle,diff --git a/libs/cua/python/src/cua/_native.py b/libs/cua/python/src/cua/_native.pyindex 82f959c6d4..8d0ab2bdfb 100644--- a/libs/cua/python/src/cua/_native.py+++ b/libs/cua/python/src/cua/_native.py@@ -659,7 +659,7 @@ def _uniffi_check_api_checksums(lib):raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")if lib.uniffi_cua_sdk_checksum_method_auth_begin_login() != 55109:raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")- if lib.uniffi_cua_sdk_checksum_method_auth_devices() != 24953:+ if lib.uniffi_cua_sdk_checksum_method_auth_devices() != 36673:raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")if lib.uniffi_cua_sdk_checksum_method_auth_logout() != 38806:raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")@@ -821,7 +821,7 @@ def _uniffi_check_api_checksums(lib):raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")if lib.uniffi_cua_sdk_checksum_method_loginattempt_user_code() != 37591:raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")- if lib.uniffi_cua_sdk_checksum_method_loginattempt_wait() != 2942:+ if lib.uniffi_cua_sdk_checksum_method_loginattempt_wait() != 16950:raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")if lib.uniffi_cua_sdk_checksum_method_mcpclient_call_tool() != 44958:raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")@@ -887,7 +887,7 @@ def _uniffi_check_api_checksums(lib):raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")if lib.uniffi_cua_sdk_checksum_method_presenceview_upsert() != 29196:raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")- if lib.uniffi_cua_sdk_checksum_constructor_relay_new() != 59964:+ if lib.uniffi_cua_sdk_checksum_constructor_relay_new() != 19970:raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")if lib.uniffi_cua_sdk_checksum_method_relay_connect() != 37946:raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")@@ -23971,10 +23971,11 @@ class LoginAttemptProtocol(typing.Protocol):Waits for the user, stores the session and returns who signed in.Only the first call waits; later calls fail.- A device that already enrolled (it has a device key) then- re-registers with the relay (`CUA_RELAY_URL`, else relay.cua.ai), so- the fresh sign-in enrolls or re-verifies it without an approval.- That step is best effort and never fails the sign-in.+ This device then registers with the relay (the one `cua` uses:+ `CUA_RELAY_URL`, else this machine's host setup, else relay.cua.ai),+ creating its device key on first use, so the fresh sign-in enrolls+ or re-verifies it without an approval. That step is best effort and+ never fails the sign-in."""raise NotImplementedError@@ -24077,10 +24078,11 @@ class LoginAttempt(LoginAttemptProtocol):Waits for the user, stores the session and returns who signed in.Only the first call waits; later calls fail.- A device that already enrolled (it has a device key) then- re-registers with the relay (`CUA_RELAY_URL`, else relay.cua.ai), so- the fresh sign-in enrolls or re-verifies it without an approval.- That step is best effort and never fails the sign-in.+ This device then registers with the relay (the one `cua` uses:+ `CUA_RELAY_URL`, else this machine's host setup, else relay.cua.ai),+ creating its device key on first use, so the fresh sign-in enrolls+ or re-verifies it without an approval. That step is best effort and+ never fails the sign-in."""_uniffi_lowered_args = (self._uniffi_clone_handle(),@@ -24459,9 +24461,10 @@ class AuthProtocol(typing.Protocol):raise NotImplementedErrordef devices(self, relay_url: typing.Optional[str],name: typing.Optional[str]) -> Devices:"""- This device on `relay_url` (`None` = `CUA_RELAY_URL`, else+ This device on `relay_url` (`None` = the relay `cua` uses:+ `CUA_RELAY_URL`, else this machine's host setup, else`https://relay.cua.ai`) as the signed-in account, shown as `name`- (default: the host name).+ (default: this computer's name)."""raise NotImplementedErrorasync def logout(self, ) -> bool:@@ -24554,9 +24557,10 @@ class Auth(AuthProtocol):)def devices(self, relay_url: typing.Optional[str],name: typing.Optional[str]) -> Devices:"""- This device on `relay_url` (`None` = `CUA_RELAY_URL`, else+ This device on `relay_url` (`None` = the relay `cua` uses:+ `CUA_RELAY_URL`, else this machine's host setup, else`https://relay.cua.ai`) as the signed-in account, shown as `name`- (default: the host name).+ (default: this computer's name)."""_UniffiFfiConverterOptionalString.check_lower(relay_url)@@ -36099,8 +36103,9 @@ class Relay(RelayProtocol):_handle: ctypes.c_uint64def __init__(self, relay_url: typing.Optional[str],account_token: str):"""- A relay (`None` = `CUA_RELAY_URL`, else `https://relay.cua.ai`) seen- as the account behind `account_token` (a cua.ai access token).+ A relay (`None` = the relay `cua` uses: `CUA_RELAY_URL`, else this+ machine's host setup, else `https://relay.cua.ai`) seen as the+ account behind `account_token` (a cua.ai access token)."""_UniffiFfiConverterOptionalString.check_lower(relay_url)diff --git a/libs/cua/swift/Sources/CuaSDK/CuaSDK.swift b/libs/cua/swift/Sources/CuaSDK/CuaSDK.swiftindex 9c879f7a44..c55b13794a 100644--- a/libs/cua/swift/Sources/CuaSDK/CuaSDK.swift+++ b/libs/cua/swift/Sources/CuaSDK/CuaSDK.swift@@ -2012,9 +2012,10 @@ public protocol AuthProtocol: AnyObject, Sendable {func status() throws -> AuthStatus/**- * This device on `relay_url` (`None` = `CUA_RELAY_URL`, else+ * This device on `relay_url` (`None` = the relay `cua` uses:+ * `CUA_RELAY_URL`, else this machine's host setup, else* `https://relay.cua.ai`) as the signed-in account, shown as `name`- * (default: the host name).+ * (default: this computer's name).*/func devices(relayUrl: String?, name: String?) throws -> Devices@@ -2150,9 +2151,10 @@ open func status()throws -> AuthStatus {}/**- * This device on `relay_url` (`None` = `CUA_RELAY_URL`, else+ * This device on `relay_url` (`None` = the relay `cua` uses:+ * `CUA_RELAY_URL`, else this machine's host setup, else* `https://relay.cua.ai`) as the signed-in account, shown as `name`- * (default: the host name).+ * (default: this computer's name).*/open func devices(relayUrl: String?, name: String?)throws -> Devices {return try FfiConverterTypeDevices_lift(try rustCallWithError(FfiConverterTypeCuaError_lift) {@@ -5010,10 +5012,11 @@ public protocol LoginAttemptProtocol: AnyObject, Sendable {* Waits for the user, stores the session and returns who signed in.* Only the first call waits; later calls fail.*- * A device that already enrolled (it has a device key) then- * re-registers with the relay (`CUA_RELAY_URL`, else relay.cua.ai), so- * the fresh sign-in enrolls or re-verifies it without an approval.- * That step is best effort and never fails the sign-in.+ * This device then registers with the relay (the one `cua` uses:+ * `CUA_RELAY_URL`, else this machine's host setup, else relay.cua.ai),+ * creating its device key on first use, so the fresh sign-in enrolls+ * or re-verifies it without an approval. That step is best effort and+ * never fails the sign-in.*/func wait() async throws -> AuthIdentity@@ -5122,10 +5125,11 @@ open func userCode() -> String? {* Waits for the user, stores the session and returns who signed in.* Only the first call waits; later calls fail.*- * A device that already enrolled (it has a device key) then- * re-registers with the relay (`CUA_RELAY_URL`, else relay.cua.ai), so- * the fresh sign-in enrolls or re-verifies it without an approval.- * That step is best effort and never fails the sign-in.+ * This device then registers with the relay (the one `cua` uses:+ * `CUA_RELAY_URL`, else this machine's host setup, else relay.cua.ai),+ * creating its device key on first use, so the fresh sign-in enrolls+ * or re-verifies it without an approval. That step is best effort and+ * never fails the sign-in.*/open func wait()async throws -> AuthIdentity {return@@ -6381,8 +6385,9 @@ open class Relay: RelayProtocol, @unchecked Sendable {return try! rustCall { uniffi_cua_sdk_fn_clone_relay(self.handle, $0) }}/**- * A relay (`None` = `CUA_RELAY_URL`, else `https://relay.cua.ai`) seen- * as the account behind `account_token` (a cua.ai access token).+ * A relay (`None` = the relay `cua` uses: `CUA_RELAY_URL`, else this+ * machine's host setup, else `https://relay.cua.ai`) seen as the+ * account behind `account_token` (a cua.ai access token).*/public convenience init(relayUrl: String?, accountToken: String)throws {let handle =@@ -40013,7 +40018,7 @@ private let initializationResult: InitializationResult = {if (uniffi_cua_sdk_checksum_method_auth_status() != 29264) {return InitializationResult.apiChecksumMismatch}- if (uniffi_cua_sdk_checksum_method_auth_devices() != 24953) {+ if (uniffi_cua_sdk_checksum_method_auth_devices() != 36673) {return InitializationResult.apiChecksumMismatch}if (uniffi_cua_sdk_checksum_method_loginattempt_method() != 60787) {@@ -40028,7 +40033,7 @@ private let initializationResult: InitializationResult = {if (uniffi_cua_sdk_checksum_method_loginattempt_user_code() != 37591) {return InitializationResult.apiChecksumMismatch}- if (uniffi_cua_sdk_checksum_method_loginattempt_wait() != 2942) {+ if (uniffi_cua_sdk_checksum_method_loginattempt_wait() != 16950) {return InitializationResult.apiChecksumMismatch}if (uniffi_cua_sdk_checksum_method_cua_agent_setup() != 50422) {@@ -41054,7 +41059,7 @@ private let initializationResult: InitializationResult = {if (uniffi_cua_sdk_checksum_constructor_host_new() != 62533) {return InitializationResult.apiChecksumMismatch}- if (uniffi_cua_sdk_checksum_constructor_relay_new() != 59964) {+ if (uniffi_cua_sdk_checksum_constructor_relay_new() != 19970) {return InitializationResult.apiChecksumMismatch}if (uniffi_cua_sdk_checksum_constructor_presenceview_new() != 9981) {diff --git a/libs/cua/typescript/src/native/cua_sdk.ts b/libs/cua/typescript/src/native/cua_sdk.tsindex 57723924db..864889afc2 100644--- a/libs/cua/typescript/src/native/cua_sdk.ts+++ b/libs/cua/typescript/src/native/cua_sdk.ts@@ -20588,10 +20588,11 @@ export interface LoginAttemptLike {* Waits for the user, stores the session and returns who signed in.* Only the first call waits; later calls fail.*- * A device that already enrolled (it has a device key) then- * re-registers with the relay (`CUA_RELAY_URL`, else relay.cua.ai), so- * the fresh sign-in enrolls or re-verifies it without an approval.- * That step is best effort and never fails the sign-in.+ * This device then registers with the relay (the one `cua` uses:+ * `CUA_RELAY_URL`, else this machine's host setup, else relay.cua.ai),+ * creating its device key on first use, so the fresh sign-in enrolls+ * or re-verifies it without an approval. That step is best effort and+ * never fails the sign-in.*/wait(asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<AuthIdentity>;}@@ -20703,10 +20704,11 @@ private constructor(pointer: UniffiHandle) {* Waits for the user, stores the session and returns who signed in.* Only the first call waits; later calls fail.*- * A device that already enrolled (it has a device key) then- * re-registers with the relay (`CUA_RELAY_URL`, else relay.cua.ai), so- * the fresh sign-in enrolls or re-verifies it without an approval.- * That step is best effort and never fails the sign-in.+ * This device then registers with the relay (the one `cua` uses:+ * `CUA_RELAY_URL`, else this machine's host setup, else relay.cua.ai),+ * creating its device key on first use, so the fresh sign-in enrolls+ * or re-verifies it without an approval. That step is best effort and+ * never fails the sign-in.*/async wait(asyncOpts_?: { signal: AbortSignal }): Promise<AuthIdentity> /*throws*/ {const __stack = uniffiIsDebug ? new Error().stack : undefined;@@ -21296,9 +21298,10 @@ export interface AuthLike {*/beginLogin(flow: string | undefined, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<LoginAttemptLike>;/**- * This device on `relay_url` (`None` = `CUA_RELAY_URL`, else+ * This device on `relay_url` (`None` = the relay `cua` uses:+ * `CUA_RELAY_URL`, else this machine's host setup, else* `https://relay.cua.ai`) as the signed-in account, shown as `name`- * (default: the host name).+ * (default: this computer's name).*/devices(relayUrl: string | undefined, name: string | undefined) /*throws*/: DevicesLike;/**@@ -21408,9 +21411,10 @@ private constructor(pointer: UniffiHandle) {}/**- * This device on `relay_url` (`None` = `CUA_RELAY_URL`, else+ * This device on `relay_url` (`None` = the relay `cua` uses:+ * `CUA_RELAY_URL`, else this machine's host setup, else* `https://relay.cua.ai`) as the signed-in account, shown as `name`- * (default: the host name).+ * (default: this computer's name).*/devices(relayUrl: string | undefined, name: string | undefined): DevicesLike /*throws*/ {return FfiConverterTypeDevices.lift(uniffiCaller.rustCallWithError(@@ -35918,8 +35922,9 @@ export class Relay extends UniffiAbstractObject implements RelayLike {readonly [destructorGuardSymbol]: UniffiGcObject;readonly [pointerLiteralSymbol]: UniffiHandle;/**- * A relay (`None` = `CUA_RELAY_URL`, else `https://relay.cua.ai`) seen- * as the account behind `account_token` (a cua.ai access token).+ * A relay (`None` = the relay `cua` uses: `CUA_RELAY_URL`, else this+ * machine's host setup, else `https://relay.cua.ai`) seen as the+ * account behind `account_token` (a cua.ai access token).*/constructor(relayUrl: string | undefined, accountToken: string) /*throws*/ {super();@@ -36887,7 +36892,7 @@ function uniffiEnsureInitialized() {if (nativeModule().uniffi_cua_sdk_checksum_method_auth_begin_login() !== 55109) {throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_auth_begin_login");}- if (nativeModule().uniffi_cua_sdk_checksum_method_auth_devices() !== 24953) {+ if (nativeModule().uniffi_cua_sdk_checksum_method_auth_devices() !== 36673) {throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_auth_devices");}if (nativeModule().uniffi_cua_sdk_checksum_method_auth_logout() !== 38806) {@@ -37130,7 +37135,7 @@ function uniffiEnsureInitialized() {if (nativeModule().uniffi_cua_sdk_checksum_method_loginattempt_user_code() !== 37591) {throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_loginattempt_user_code");}- if (nativeModule().uniffi_cua_sdk_checksum_method_loginattempt_wait() !== 2942) {+ if (nativeModule().uniffi_cua_sdk_checksum_method_loginattempt_wait() !== 16950) {throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_loginattempt_wait");}if (nativeModule().uniffi_cua_sdk_checksum_method_mcpclient_call_tool() !== 44958) {@@ -37229,7 +37234,7 @@ function uniffiEnsureInitialized() {if (nativeModule().uniffi_cua_sdk_checksum_method_presenceview_upsert() !== 29196) {throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_presenceview_upsert");}- if (nativeModule().uniffi_cua_sdk_checksum_constructor_relay_new() !== 59964) {+ if (nativeModule().uniffi_cua_sdk_checksum_constructor_relay_new() !== 19970) {throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_constructor_relay_new");}if (nativeModule().uniffi_cua_sdk_checksum_method_relay_connect() !== 37946) {diff --git a/libs/lume/src/Server/Handlers.swift b/libs/lume/src/Server/Handlers.swiftindex 6c65724baa..22e39f5425 100644--- a/libs/lume/src/Server/Handlers.swift+++ b/libs/lume/src/Server/Handlers.swift@@ -1033,7 +1033,7 @@ extension Server {vmCount: runningVMs.count,maxVMs: maxVMs,availableSlots: max(0, maxVMs - runningVMs.count),- version: "1.0.0" // Could be derived from build info+ version: Lume.Version.current)return try .json(response)