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
Windows: sign-in, Docker detection, Hello-less presence, Edge teleport, wording (CUA-1507 gaps) (#5111)
ddupontb6db8a141de8
diff --git a/apps/cua-spaces-desktop/scripts/smoke/windows-inside.py b/apps/cua-spaces-desktop/scripts/smoke/windows-inside.pyindex 9229c879b4..728954bbf2 100644--- a/apps/cua-spaces-desktop/scripts/smoke/windows-inside.py+++ b/apps/cua-spaces-desktop/scripts/smoke/windows-inside.py@@ -72,7 +72,9 @@ for installer in sorted(glob.glob(f"/dist/Cua-Spaces-Setup-{VERSION}*.exe")):check(f"[{arch}] GUI subsystem", pe.OPTIONAL_HEADER.Subsystem == 2)vi = version_info(pe)check(f"[{arch}] ProductName Cua Spaces", vi.get("ProductName") == "Cua Spaces", vi.get("ProductName"))- check(f"[{arch}] FileVersion {VERSION}", vi.get("FileVersion", "").startswith(VERSION), vi.get("FileVersion"))+ # FileVersion is numeric X.Y.Z.<build>: a prerelease suffix cannot ride in it.+ base = VERSION.split("-")[0]+ check(f"[{arch}] FileVersion {base}.<build>", vi.get("FileVersion", "").startswith(base + "."), vi.get("FileVersion"))check(f"[{arch}] CompanyName set", bool(vi.get("CompanyName")), vi.get("CompanyName"))icons = [e for e in pe.DIRECTORY_ENTRY_RESOURCE.entries if e.id == pefile.RESOURCE_TYPE["RT_GROUP_ICON"]]check(f"[{arch}] icon resource", bool(icons))@@ -83,8 +85,13 @@ for installer in sorted(glob.glob(f"/dist/Cua-Spaces-Setup-{VERSION}*.exe")):maps = glob.glob(os.path.join(res, "web", "**", "*.map"), recursive=True)check(f"[{arch}] no source maps in web/", not maps, f"{len(maps)} found")feed = open(os.path.join(res, "app-update.yml")).read()- check(f"[{arch}] update feed: GitHub placeholder, channel latest",- "provider: github" in feed and "repo: cua-spaces-releases" in feed and "channel: latest" in feed)+ # The build writes a generic feed at the repository's rolling+ # `cua-spaces-latest` release (electron-builder.config.cjs); a prerelease+ # version rides the `beta` channel, a stable one `latest`.+ channel = "beta" if "-" in VERSION else "latest"+ check(f"[{arch}] update feed: generic, cua-spaces-latest, channel {channel}",+ "provider: generic" in feed and "/releases/download/cua-spaces-latest" in feed and f"channel: {channel}" in feed,+ feed.replace("\n", " | "))files = asar_files(os.path.join(res, "app.asar"))for rel in ["package.json", "dist-electron/boot.cjs", "dist-electron/main.cjs", "dist-electron/preload.cjs"]:check(f"[{arch}] app.asar has {rel}", rel in files)diff --git a/apps/cua-spaces-desktop/src/menu.ts b/apps/cua-spaces-desktop/src/menu.tsindex 3ff837d588..981d3cddab 100644--- a/apps/cua-spaces-desktop/src/menu.ts+++ b/apps/cua-spaces-desktop/src/menu.ts@@ -31,8 +31,10 @@ export interface MenuActions {/** The menu for `platform`; `dev` (an unpackaged build) adds Reload and the developer tools. */export function menuTemplate(platform: NodeJS.Platform, actions: MenuActions, { dev = false, appName = "Cua Spaces" } = {}): MenuItemConstructorOptions[] {const mac = platform === "darwin";- const newSpace: MenuItemConstructorOptions = { label: "New Space", accelerator: "CmdOrCtrl+N", click: () => actions.newSpace() };- const settings: MenuItemConstructorOptions = { label: "Settings…", accelerator: "CmdOrCtrl+,", click: () => actions.settings() };+ // Spelled out per platform (not `CmdOrCtrl`): the Windows and Linux menus+ // drew the shortcut with no modifier ("+N") for the portable alias.+ const newSpace: MenuItemConstructorOptions = { label: "New Space", accelerator: mac ? "CmdOrCtrl+N" : "Ctrl+N", click: () => actions.newSpace() };+ const settings: MenuItemConstructorOptions = { label: "Settings…", accelerator: mac ? "CmdOrCtrl+," : "Ctrl+,", click: () => actions.settings() };const quit: MenuItemConstructorOptions = mac? { label: `Quit ${appName}`, accelerator: "Command+Q", click: () => app.quit() }: { label: "Exit", click: () => app.quit() };diff --git a/apps/cua-spaces-desktop/src/model/app-model.ts b/apps/cua-spaces-desktop/src/model/app-model.tsindex 8d0f2253d5..96d18b681c 100644--- a/apps/cua-spaces-desktop/src/model/app-model.ts+++ b/apps/cua-spaces-desktop/src/model/app-model.ts@@ -42,6 +42,7 @@ import { KeyvaultModel } from "./keyvault";import type { AccountRunning, TelemetryRunning } from "./services";import type { StartupModel } from "./startup";import { SpaceThumbnails } from "./thumbnails";+import { noLocalRuntimeReason } from "./local-runtime";import { TimeoutError, sleep, withTimeout } from "./time";/** What changed, for the page's events. */@@ -468,7 +469,7 @@ export class AppModel {defaultLocation: this.settings.defaultLocation,cloudAvailable: available,localAvailable: backends ? backends.length > 0 : true,- localReason: backends && backends.length === 0 ? "No local runtime found (Docker or Lume)." : undefined,+ localReason: backends && backends.length === 0 ? noLocalRuntimeReason(process.platform, runtimes?.details.get("container")) : undefined,localBackends: backends,localDetails: runtimes?.details,maxCpus: this.maxCpus,diff --git a/apps/cua-spaces-desktop/src/model/backend.ts b/apps/cua-spaces-desktop/src/model/backend.tsindex d166ce4bec..ce88cb7425 100644--- a/apps/cua-spaces-desktop/src/model/backend.ts+++ b/apps/cua-spaces-desktop/src/model/backend.ts@@ -367,8 +367,9 @@ export class LiveSpacesBackend implements SpacesBackend {this.native.configSet("runtime.lume", value);}+ /** The built-in Linux runtime (a VM with Docker and gVisor) runs on a Mac only: elsewhere there is no setting, so Settings has no Linux row. */async linuxSource(): Promise<string | null> {- return this.config("runtime.linux");+ return this.platform === "darwin" ? this.config("runtime.linux") : null;}async setLinuxSource(value: string): Promise<void> {diff --git a/apps/cua-spaces-desktop/src/model/local-runtime.test.ts b/apps/cua-spaces-desktop/src/model/local-runtime.test.tsnew file mode 100644index 0000000000..767326523e--- /dev/null+++ b/apps/cua-spaces-desktop/src/model/local-runtime.test.ts@@ -0,0 +1,28 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import { describe, expect, it } from "vitest";+import { noLocalRuntimeReason } from "./local-runtime";++describe("noLocalRuntimeReason", () => {+ it("keeps the Mac wording", () => {+ expect(noLocalRuntimeReason("darwin")).toContain("Lume");+ });+ it("never mentions Lume on Windows or Linux", () => {+ for (const p of ["win32", "linux"]) {+ expect(noLocalRuntimeReason(p)).not.toContain("Lume");+ expect(noLocalRuntimeReason(p, "container engine at x is not running")).not.toContain("Lume");+ }+ });+ it("tells Windows users to install Docker Desktop when there is no engine (WSL 2 only)", () => {+ const r = noLocalRuntimeReason("win32", "no Docker-API socket found");+ expect(r).toContain("Install it from https://docs.docker.com/desktop/setup/install/windows-install/");+ expect(r).toContain("WSL 2");+ });+ it("knows Docker Desktop is installed when its pipe is missing", () => {+ expect(noLocalRuntimeReason("win32", "container engine: Socket not found: //./pipe/dockerDesktopLinuxEngine")).toMatch(/isn't running/);+ });+ it("tells Windows users to start a stopped Docker Desktop", () => {+ expect(noLocalRuntimeReason("win32", "container engine at npipe://x is not running")).toMatch(/isn't running/);+ });+});diff --git a/apps/cua-spaces-desktop/src/model/local-runtime.ts b/apps/cua-spaces-desktop/src/model/local-runtime.tsnew file mode 100644index 0000000000..c036c4fdb6--- /dev/null+++ b/apps/cua-spaces-desktop/src/model/local-runtime.ts@@ -0,0 +1,25 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++/** Why New Space cannot run anything on this machine, in the words of its OS. */++const DOCKER_DESKTOP_URL = "https://docs.docker.com/desktop/setup/install/windows-install/";++/**+ * The line New Space shows when no local runtime is ready. `containerDetail`+ * is the runtime doctor's detail for the container engine, when it gave one+ * (for example "container engine at npipe://... is not running").+ */+export function noLocalRuntimeReason(platform: string, containerDetail?: string): string {+ if (platform === "darwin") return "No local runtime found (Docker or Lume).";+ const detail = (containerDetail ?? "").toLowerCase();+ const installedButStopped = /not running|did not answer|not listening|start |socket not found|pipe\/dockerdesktop/.test(detail);+ if (platform === "win32") {+ if (installedButStopped) {+ return "Docker Desktop isn't running. Start it and wait for “Engine running”, then try again.";+ }+ return `Cua runs local Spaces in Docker Desktop (WSL 2 alone isn't enough). Install it from ${DOCKER_DESKTOP_URL}, start it, then try again.`;+ }+ if (installedButStopped) return "Docker isn't running. Start it (for example `sudo systemctl start docker`), then try again.";+ return "No local runtime found. Install Docker Engine or Podman and start it, then try again.";+}diff --git a/apps/cua-spaces-desktop/test/menu.test.ts b/apps/cua-spaces-desktop/test/menu.test.tsindex be596323f0..263d6992b2 100644--- a/apps/cua-spaces-desktop/test/menu.test.ts+++ b/apps/cua-spaces-desktop/test/menu.test.ts@@ -89,7 +89,8 @@ describe("the Windows and Linux menu", () => {expect(names(t)).toEqual(["File", "editMenu", "View", "windowMenu", "help"]);const file = sub(t, "File");expect(names(file)).toEqual(["New Space", "---", "Settings…", "---", "Exit"]);- expect(file.find((i) => i.label === "Settings…")!.accelerator).toBe("CmdOrCtrl+,");+ expect(file.find((i) => i.label === "Settings…")!.accelerator).toBe("Ctrl+,");+ expect(file[0]!.accelerator).toBe("Ctrl+N");for (const i of file) (i.click as (() => void) | undefined)?.();expect(log).toEqual(["new", "settings"]);expect(names(sub(t, "View"))).toEqual(["togglefullscreen"]);diff --git a/apps/cua-spaces-desktop/test/spaces-model.test.ts b/apps/cua-spaces-desktop/test/spaces-model.test.tsindex 27c71f2cfb..3ac15d1ca5 100644--- a/apps/cua-spaces-desktop/test/spaces-model.test.ts+++ b/apps/cua-spaces-desktop/test/spaces-model.test.ts@@ -269,7 +269,10 @@ describe("LiveSpacesBackend's runtime settings", () => {// Windows and Linux: no Lume, so Settings shows no macOS VMs row.expect(await backend("linux").lumeSource()).toBeNull();expect(await backend("win32").lumeSource()).toBeNull();- expect(await backend("linux").linuxSource()).toBe("auto");+ // The built-in Linux runtime is a Mac thing too.+ expect(await backend("darwin").linuxSource()).toBe("auto");+ expect(await backend("linux").linuxSource()).toBeNull();+ expect(await backend("win32").linuxSource()).toBeNull();});});diff --git a/apps/cua-spaces-web/src/bridge/derive.ts b/apps/cua-spaces-web/src/bridge/derive.tsindex 33c54c8c1f..47682768e3 100644--- a/apps/cua-spaces-web/src/bridge/derive.ts+++ b/apps/cua-spaces-web/src/bridge/derive.ts@@ -36,6 +36,7 @@ import type { CreateAction, CreatesState, PendingCreate, Space, SpaceOs, SpaceRoimport type { RelayUsage, RelayUsageView } from "./ops/relay-usage";import type { SessionSnapshot, SettingsSnapshot } from "./protocol";import { notSharingOf, realLimits } from "./sharing";+import { hostOs, type HostOs } from "./host-os";/* ---- Spaces --------------------------------------------------------------- */@@ -591,12 +592,13 @@ export function keyvaultViews(overview: KeyvaultOverview,now: number,state: VaultState = INITIAL_VAULT_STATE,+ os: HostOs = hostOs(),): KeyvaultViews | null {if (core.status !== "ready") return null;return {- page: core.call<KvPage>("keyvault.page", { overview, now }),+ page: core.call<KvPage>("keyvault.page", { overview, now, hostOs: os }),sidebar: core.call<KvSidebar>("keyvault.sidebar", { overview, now }),- vault: core.call<VaultView>("keyvault.vaultView", { overview, state, now }),+ vault: core.call<VaultView>("keyvault.vaultView", { overview, state, now, hostOs: os }),};}diff --git a/apps/cua-spaces-web/src/components/teleport/teleport-dialog.tsx b/apps/cua-spaces-web/src/components/teleport/teleport-dialog.tsxindex 5f3e3ab94e..b3b8679514 100644--- a/apps/cua-spaces-web/src/components/teleport/teleport-dialog.tsx+++ b/apps/cua-spaces-web/src/components/teleport/teleport-dialog.tsx@@ -11,6 +11,7 @@ import { Button } from "@/components/ui/button";import { Checkbox } from "@/components/ui/checkbox";import { Dialog, DialogPopup, DialogTitle } from "@/components/ui/dialog";import { Input } from "@/components/ui/input";+import { leavesLine } from "@/lib/host-labels";import { Segmented } from "@/components/ui/segmented";import { TeleportGrid } from "./grid";@@ -205,7 +206,7 @@ function Running({ session: s }: { session: TeleportSession }) {function Footer({ session: s, teleport }: { session: TeleportSession; teleport: TeleportStore }) {const step = s.state.step;- const leaves = step === "consent" ? s.frame.review?.leavesText : null;+ const leaves = step === "consent" ? leavesLine(s.frame.review?.leavesText ?? "") : null;return (<div className="flex shrink-0 items-center gap-2 border-t bg-muted/60 px-5 py-3">{leaves ? (diff --git a/apps/cua-spaces-web/src/lib/host-labels.test.ts b/apps/cua-spaces-web/src/lib/host-labels.test.tsindex 83ce442974..2bddef2d2b 100644--- a/apps/cua-spaces-web/src/lib/host-labels.test.ts+++ b/apps/cua-spaces-web/src/lib/host-labels.test.ts@@ -3,7 +3,7 @@import { describe, expect, it } from "vitest";-import { creatingLine, globalShortcutLine, hostOs, keyvaultUnlockWay, osOfPlatform, showsMacShellSettings, thisComputerLabel, thisComputerText } from "./host-labels";+import { creatingLine, leavesLine, globalShortcutLine, hostOs, keyvaultUnlockWay, osOfPlatform, showsMacShellSettings, thisComputerLabel, thisComputerText } from "./host-labels";describe("host labels", () => {it("names the local machine after its system", () => {@@ -42,6 +42,13 @@ describe("host labels", () => {expect(creatingLine("This Mac can't reach its new VM", "linux")).toBe("This Mac can't reach its new VM");});+ it("names this computer in what leaves it on teleport", () => {+ expect(leavesLine("191 KB leaves this Mac", "darwin")).toBe("191 KB leaves this Mac");+ expect(leavesLine("191 KB leaves this Mac", "win32")).toBe("191 KB leaves this PC");+ expect(leavesLine("191 KB leaves this Mac", "linux")).toBe("191 KB leaves this computer");+ expect(leavesLine("3 saved items from the Keyvault", "win32")).toBe("3 saved items from the Keyvault");+ });+it("says what the global shortcut does, or why it does nothing", () => {expect(globalShortcutLine({ label: "\u2318\u21e7Space", registered: true })).toBe("Brings Cua Spaces to the front from any app.");expect(globalShortcutLine({ label: "\u2318\u21e7Space", registered: false })).toBe(diff --git a/apps/cua-spaces-web/src/lib/host-labels.ts b/apps/cua-spaces-web/src/lib/host-labels.tsindex 4574d9ad26..d9f9389369 100644--- a/apps/cua-spaces-web/src/lib/host-labels.ts+++ b/apps/cua-spaces-web/src/lib/host-labels.ts@@ -37,6 +37,13 @@ export function creatingLine(detail: string, platform?: string): string {return os === "macos" ? detail : detail.replace(/^This Mac(?= \u00b7 )/, THIS_MACHINE[os]);}+/** The core's "12 MB leaves this Mac" review line, naming this computer in+ * the words of its system ("leaves this PC"). */+export function leavesLine(text: string, platform?: string): string {+ const os = osOf(platform);+ return os === "macos" ? text : text.replace(/ leaves this Mac$/, ` leaves ${thisComputerText(platform)}`);+}+/** What keeps the Keyvault's key besides a passphrase: "Touch ID",* "Windows Hello", "the system keyring" (Linux). */export function keyvaultUnlockWay(platform?: string): string {diff --git a/apps/cua-spaces/src-tauri/Cargo.lock b/apps/cua-spaces/src-tauri/Cargo.lockindex 4f17a939fb..94539c9abe 100644--- a/apps/cua-spaces/src-tauri/Cargo.lock+++ b/apps/cua-spaces/src-tauri/Cargo.lock@@ -1502,6 +1502,7 @@ dependencies = ["async-trait","base64 0.22.1","core-foundation 0.10.1",+ "cua-home","cua-telemetry","hex","keyring",diff --git a/libs/cua-spacesd/tests/spaces-e2e/Cargo.lock b/libs/cua-spacesd/tests/spaces-e2e/Cargo.lockindex 0780ec00c5..55472fb276 100644--- a/libs/cua-spacesd/tests/spaces-e2e/Cargo.lock+++ b/libs/cua-spacesd/tests/spaces-e2e/Cargo.lock@@ -2313,6 +2313,7 @@ dependencies = ["async-trait","base64 0.22.1","core-foundation 0.10.1",+ "cua-home","cua-telemetry","hex","keyring 3.6.3",diff --git a/libs/cua/Cargo.lock b/libs/cua/Cargo.lockindex 65d0437fed..9dfde22e34 100644--- a/libs/cua/Cargo.lock+++ b/libs/cua/Cargo.lock@@ -2627,6 +2627,7 @@ dependencies = ["async-trait","base64 0.22.1","core-foundation 0.10.1",+ "cua-home","cua-telemetry","hex","keyring",@@ -3031,6 +3032,7 @@ dependencies = ["cua-chromium-storage","cua-daemon","cua-fleet",+ "cua-home","cua-host","cua-keyvault","cua-media-client",diff --git a/libs/cua/crates/cua-auth/src/chunked.rs b/libs/cua/crates/cua-auth/src/chunked.rsnew file mode 100644index 0000000000..94f9597722--- /dev/null+++ b/libs/cua/crates/cua-auth/src/chunked.rs@@ -0,0 +1,231 @@+//! A value of any size in a vault whose entries are small.+//!+//! Windows Credential Manager (`CredWrite`) refuses a blob over 2,560 bytes,+//! which is 1,280 UTF-16 characters. A Cua session (access, refresh and id+//! tokens) is about 3,800 characters, so it is split over several entries:+//! the main entry then holds a short header (`cua-chunked:1:<n>:<len>`) and+//! the pieces live in `<account>#0 .. <account>#<n-1>`. Every entry stays in+//! Credential Manager, which DPAPI-encrypts for the signed-in user; nothing+//! is ever written in plaintext to disk.+//!+//! The logic is generic over a [`Slots`] backend so it is tested on every+//! platform; only Windows plugs in the real one.++/// Most UTF-16 code units in one entry, well below the 1,280 the OS allows.+pub const CHUNK_UNITS: usize = 1000;+const PREFIX: &str = "cua-chunked:1:";++/// A set of named string slots.+pub trait Slots {+ type Err;+ fn read(&self, name: &str) -> Result<Option<String>, Self::Err>;+ fn write(&self, name: &str, value: &str) -> Result<(), Self::Err>;+ /// Deletes a slot; a missing one is not an error.+ fn remove(&self, name: &str) -> Result<(), Self::Err>;+}++fn chunk_name(account: &str, i: usize) -> String {+ format!("{account}#{i}")+}++/// `(pieces, total length in UTF-16 units)` of a header.+fn parse_header(s: &str) -> Option<(usize, usize)> {+ let rest = s.strip_prefix(PREFIX)?;+ let (n, len) = rest.split_once(':')?;+ Some((n.parse().ok()?, len.parse().ok()?))+}++/// Splits on char boundaries into pieces of at most [`CHUNK_UNITS`] units.+fn split(text: &str) -> Vec<String> {+ let mut out = vec![];+ let mut cur = String::new();+ let mut units = 0;+ for ch in text.chars() {+ let w = ch.len_utf16();+ if units + w > CHUNK_UNITS {+ out.push(std::mem::take(&mut cur));+ units = 0;+ }+ cur.push(ch);+ units += w;+ }+ if !cur.is_empty() {+ out.push(cur);+ }+ out+}++fn old_pieces<S: Slots>(s: &S, account: &str) -> usize {+ match s.read(account) {+ Ok(Some(h)) => parse_header(&h).map_or(0, |(n, _)| n),+ _ => 0,+ }+}++/// Stores `text` under `account`.+pub fn set<S: Slots>(s: &S, account: &str, text: &str) -> Result<(), S::Err> {+ let old = old_pieces(s, account);+ let new = if text.encode_utf16().count() <= CHUNK_UNITS {+ s.write(account, text)?;+ 0+ } else {+ let pieces = split(text);+ // Pieces first, header last: a failure midway leaves the previous+ // value readable.+ for (i, p) in pieces.iter().enumerate() {+ s.write(&chunk_name(account, i), p)?;+ }+ let header = format!("{PREFIX}{}:{}", pieces.len(), text.encode_utf16().count());+ s.write(account, &header)?;+ pieces.len()+ };+ for i in new..old {+ s.remove(&chunk_name(account, i))?;+ }+ Ok(())+}++/// Reads the value under `account`. A chunked value with a missing or+/// altered piece reads as absent (the caller signs in again).+pub fn get<S: Slots>(s: &S, account: &str) -> Result<Option<String>, S::Err> {+ let Some(main) = s.read(account)? else {+ return Ok(None);+ };+ if !main.starts_with(PREFIX) {+ return Ok(Some(main));+ }+ let Some((n, len)) = parse_header(&main) else {+ return Ok(None);+ };+ let mut out = String::new();+ for i in 0..n {+ match s.read(&chunk_name(account, i))? {+ Some(p) => out.push_str(&p),+ None => return Ok(None),+ }+ }+ Ok((out.encode_utf16().count() == len).then_some(out))+}++/// Deletes the value and its pieces; returns whether the main entry existed.+pub fn delete<S: Slots>(s: &S, account: &str) -> Result<bool, S::Err> {+ let existed = s.read(account)?.is_some();+ for i in 0..old_pieces(s, account) {+ s.remove(&chunk_name(account, i))?;+ }+ s.remove(account)?;+ Ok(existed)+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::cell::RefCell;+ use std::collections::HashMap;++ /// Enforces the Credential Manager limit.+ #[derive(Default)]+ struct Mem(RefCell<HashMap<String, String>>);+ impl Slots for Mem {+ type Err = String;+ fn read(&self, n: &str) -> Result<Option<String>, String> {+ Ok(self.0.borrow().get(n).cloned())+ }+ fn write(&self, n: &str, v: &str) -> Result<(), String> {+ if v.encode_utf16().count() * 2 > 2560 {+ return Err("longer than platform limit of 2560 chars".into());+ }+ self.0.borrow_mut().insert(n.into(), v.into());+ Ok(())+ }+ fn remove(&self, n: &str) -> Result<(), String> {+ self.0.borrow_mut().remove(n);+ Ok(())+ }+ }++ fn big(n: usize) -> String {+ (0..n).map(|i| char::from(b'a' + (i % 26) as u8)).collect()+ }++ #[test]+ fn small_values_are_stored_as_is() {+ let m = Mem::default();+ set(&m, "a", "{\"x\":1}").unwrap();+ assert_eq!(m.0.borrow().len(), 1);+ assert_eq!(get(&m, "a").unwrap().as_deref(), Some("{\"x\":1}"));+ }++ #[test]+ fn a_session_sized_value_round_trips() {+ let m = Mem::default();+ let v = big(3800);+ set(&m, "a", &v).unwrap();+ assert_eq!(get(&m, "a").unwrap(), Some(v));+ assert_eq!(m.0.borrow().len(), 5); // header + 4 pieces+ }++ #[test]+ fn multibyte_values_round_trip_within_the_limit() {+ let m = Mem::default();+ let v: String = "é😀".repeat(2000);+ set(&m, "a", &v).unwrap();+ assert_eq!(get(&m, "a").unwrap(), Some(v));+ }++ #[test]+ fn shrinking_removes_stale_pieces() {+ let m = Mem::default();+ set(&m, "a", &big(5000)).unwrap();+ set(&m, "a", &big(1500)).unwrap();+ assert_eq!(m.0.borrow().len(), 3);+ set(&m, "a", "tiny").unwrap();+ assert_eq!(m.0.borrow().len(), 1);+ assert_eq!(get(&m, "a").unwrap().as_deref(), Some("tiny"));+ }++ #[test]+ fn delete_removes_everything() {+ let m = Mem::default();+ set(&m, "a", &big(4000)).unwrap();+ assert!(delete(&m, "a").unwrap());+ assert!(m.0.borrow().is_empty());+ assert!(!delete(&m, "a").unwrap());+ assert_eq!(get(&m, "a").unwrap(), None);+ }++ #[test]+ fn a_missing_or_altered_piece_reads_as_absent() {+ let m = Mem::default();+ set(&m, "a", &big(4000)).unwrap();+ m.0.borrow_mut().remove("a#2");+ assert_eq!(get(&m, "a").unwrap(), None);+ set(&m, "a", &big(4000)).unwrap();+ m.0.borrow_mut().insert("a#1".into(), "short".into());+ assert_eq!(get(&m, "a").unwrap(), None);+ }++ #[test]+ fn a_failed_write_keeps_the_previous_value() {+ struct Fail(Mem);+ impl Slots for Fail {+ type Err = String;+ fn read(&self, n: &str) -> Result<Option<String>, String> {+ self.0.read(n)+ }+ fn write(&self, n: &str, v: &str) -> Result<(), String> {+ if n == "a#2" {+ return Err("boom".into());+ }+ self.0.write(n, v)+ }+ fn remove(&self, n: &str) -> Result<(), String> {+ self.0.remove(n)+ }+ }+ let f = Fail(Mem::default());+ set(&f, "a", "old").unwrap();+ assert!(set(&f, "a", &big(4000)).is_err());+ assert_eq!(get(&f, "a").unwrap().as_deref(), Some("old"));+ }+}diff --git a/libs/cua/crates/cua-auth/src/lib.rs b/libs/cua/crates/cua-auth/src/lib.rsindex 93f454f7b0..0f032f7109 100644--- a/libs/cua/crates/cua-auth/src/lib.rs+++ b/libs/cua/crates/cua-auth/src/lib.rs@@ -85,6 +85,8 @@ pub enum Error {/// Result alias.pub type Result<T, E = Error> = std::result::Result<T, E>;+#[allow(dead_code)]+mod chunked;#[cfg(target_os = "macos")]mod macos_keychain;@@ -1076,14 +1078,14 @@ fn quiet() -> Option<macos_keychain::Quiet> {}#[cfg(any(target_os = "macos", target_os = "windows"))]-fn vault_get(entry: &keyring::Entry) -> keyring::Result<String> {+fn vault_get(entry: &VaultEntry) -> keyring::Result<String> {#[cfg(target_os = "macos")]let _quiet = quiet();entry.get_password()}#[cfg(any(target_os = "macos", target_os = "windows"))]-fn vault_delete(entry: &keyring::Entry) -> keyring::Result<()> {+fn vault_delete(entry: &VaultEntry) -> keyring::Result<()> {#[cfg(target_os = "macos")]let _quiet = quiet();entry.delete_credential()@@ -1131,12 +1133,72 @@ fn vault_set(account: &str, text: &str) -> Result<()> {#[cfg(target_os = "windows")]fn vault_set(account: &str, text: &str) -> Result<()> {- keyring::Entry::new(keyring_service(), account)+ VaultEntry::new(keyring_service(), account).map_err(store_err)?.set_password(text).map_err(store_err)}+/// macOS stores each item whole.+#[cfg(target_os = "macos")]+type VaultEntry = keyring::Entry;++/// Windows Credential Manager refuses an entry over 2,560 bytes, which a+/// session exceeds, so a long value is chunked over several entries (see+/// [`chunked`]); the surface matches `keyring::Entry`.+#[cfg(target_os = "windows")]+struct VaultEntry {+ service: String,+ account: String,+}++#[cfg(target_os = "windows")]+struct WinSlots<'a>(&'a str);++#[cfg(target_os = "windows")]+impl chunked::Slots for WinSlots<'_> {+ type Err = keyring::Error;+ fn read(&self, name: &str) -> keyring::Result<Option<String>> {+ match keyring::Entry::new(self.0, name)?.get_password() {+ Ok(s) => Ok(Some(s)),+ Err(keyring::Error::NoEntry) => Ok(None),+ Err(e) => Err(e),+ }+ }+ fn write(&self, name: &str, value: &str) -> keyring::Result<()> {+ keyring::Entry::new(self.0, name)?.set_password(value)+ }+ fn remove(&self, name: &str) -> keyring::Result<()> {+ match keyring::Entry::new(self.0, name)?.delete_credential() {+ Ok(()) | Err(keyring::Error::NoEntry) => Ok(()),+ Err(e) => Err(e),+ }+ }+}++#[cfg(target_os = "windows")]+impl VaultEntry {+ fn new(service: &str, account: &str) -> keyring::Result<Self> {+ Ok(Self {+ service: service.into(),+ account: account.into(),+ })+ }+ fn get_password(&self) -> keyring::Result<String> {+ chunked::get(&WinSlots(&self.service), &self.account)?.ok_or(keyring::Error::NoEntry)+ }+ fn set_password(&self, text: &str) -> keyring::Result<()> {+ chunked::set(&WinSlots(&self.service), &self.account, text)+ }+ fn delete_credential(&self) -> keyring::Result<()> {+ if chunked::delete(&WinSlots(&self.service), &self.account)? {+ Ok(())+ } else {+ Err(keyring::Error::NoEntry)+ }+ }+}+/// Whether a keychain error is macOS refusing to show a prompt/// (`errSecInteractionNotAllowed`).#[cfg(target_os = "macos")]@@ -1150,8 +1212,8 @@ fn interaction_not_allowed(e: &keyring::Error) -> bool {}#[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)+fn keyring_entry() -> Result<VaultEntry> {+ VaultEntry::new(keyring_service(), KEYRING_ACCOUNT).map_err(store_err)}/// Whether a file store at `path` reads missing secrets from the OS@@ -1186,8 +1248,8 @@ fn decode_secret(name: &str, text: &str) -> Result<Vec<u8>> {}#[cfg(any(target_os = "macos", target_os = "windows"))]-fn secret_entry(name: &str) -> Result<keyring::Entry> {- keyring::Entry::new(keyring_service(), &format!("{KEYRING_ACCOUNT}.{name}")).map_err(store_err)+fn secret_entry(name: &str) -> Result<VaultEntry> {+ VaultEntry::new(keyring_service(), &format!("{KEYRING_ACCOUNT}.{name}")).map_err(store_err)}/// Writes a file readable only by the owner (0600 on Unix), atomically.diff --git a/libs/cua/crates/cua-keyvault/Cargo.toml b/libs/cua/crates/cua-keyvault/Cargo.tomlindex 1350ec5319..426e4b8a05 100644--- a/libs/cua/crates/cua-keyvault/Cargo.toml+++ b/libs/cua/crates/cua-keyvault/Cargo.toml@@ -27,6 +27,7 @@ serde_json.workspace = truebase64.workspace = truehex.workspace = truethiserror.workspace = true+cua-home.workspace = truetracing.workspace = true# Teleport and consent counts (cua-telemetry; nothing from the vault).cua-telemetry.workspace = truediff --git a/libs/cua/crates/cua-keyvault/src/ipc.rs b/libs/cua/crates/cua-keyvault/src/ipc.rsindex 2ea77f6df7..1fd6f75b41 100644--- a/libs/cua/crates/cua-keyvault/src/ipc.rs+++ b/libs/cua/crates/cua-keyvault/src/ipc.rs@@ -1392,6 +1392,38 @@ mod tests {));}+ #[test]+ fn the_default_socket_follows_cua_env() {+ let d = tempfile::tempdir().unwrap();+ let h = d.path().to_str().unwrap();+ temp_env(+ &[+ ("CUA_HOME", None),+ ("HOME", Some(h)),+ ("USERPROFILE", Some(h)),+ ("CUA_ENV", Some("staging")),+ ],+ || {+ let sock = crate::default_socket().unwrap();+ assert_eq!(sock, d.path().join(".cua/envs/staging/keyvault.sock"));+ },+ );+ temp_env(+ &[+ ("CUA_HOME", None),+ ("HOME", Some(h)),+ ("USERPROFILE", Some(h)),+ ("CUA_ENV", None),+ ],+ || {+ assert_eq!(+ crate::default_socket().unwrap(),+ d.path().join(".cua/keyvault.sock")+ )+ },+ );+ }+#[test]fn cua_home_override_outside_the_real_home_is_untrusted() {// No override -> trusted (~/.cua).diff --git a/libs/cua/crates/cua-keyvault/src/lib.rs b/libs/cua/crates/cua-keyvault/src/lib.rsindex 23d5da50ac..88346ab281 100644--- a/libs/cua/crates/cua-keyvault/src/lib.rs+++ b/libs/cua/crates/cua-keyvault/src/lib.rs@@ -197,7 +197,15 @@ fn cua_home() -> Option<std::path::PathBuf> {}return Some(h.into());}- home_dir().map(|h| std::path::PathBuf::from(h).join(".cua"))+ // Like `cua_home::cua_home()`: another `CUA_ENV` has its own home+ // (`~/.cua/envs/staging`), where its daemon serves the Keyvault.+ home_dir().map(|h| {+ let base = std::path::PathBuf::from(h).join(".cua");+ match cua_home::env::CuaEnv::current().home_subdir() {+ Some(sub) => base.join(sub),+ None => base,+ }+ })}/// Whether `$CUA_HOME`, if set, resolves within the user's real home. Adiff --git a/libs/cua/crates/cua-keyvault/src/winpipe.rs b/libs/cua/crates/cua-keyvault/src/winpipe.rsindex 7fc2b6d0ab..5e0b1e4c4a 100644--- a/libs/cua/crates/cua-keyvault/src/winpipe.rs+++ b/libs/cua/crates/cua-keyvault/src/winpipe.rs@@ -35,9 +35,15 @@ use crate::{Error, Result};/// `ERROR_PIPE_BUSY`: every instance is serving someone; try again shortly.const ERROR_PIPE_BUSY: i32 = 231;+/// The path as both ends hash it: lower case, with `/` and `\` the same+/// (`envs/staging\keyvault.sock` is `envs\staging\keyvault.sock`).+fn normalize(path: &Path) -> String {+ path.to_string_lossy().to_lowercase().replace('/', "\\")+}+/// The pipe that stands for the socket at `path`.pub fn pipe_name(path: &Path) -> String {- let digest = crate::crypto::sha256(path.to_string_lossy().to_lowercase().as_bytes());+ let digest = crate::crypto::sha256(normalize(path).as_bytes());format!(r"\\.\pipe\cua-keyvault-{}", &hex::encode(digest)[..16])}@@ -150,6 +156,15 @@ mod tests {assert_ne!(a, pipe_name(Path::new(r"C:\Users\bob\.cua\keyvault.sock")));}+ #[test]+ fn mixed_separators_name_the_same_pipe() {+ // The daemon joined `envs/staging` onto the home (CUA-1528).+ assert_eq!(+ pipe_name(Path::new(r"C:\Users\ada\.cua\envs/staging\keyvault.sock")),+ pipe_name(Path::new(r"C:\Users\ada\.cua\envs\staging\keyvault.sock"))+ );+ }+#[test]fn the_access_list_is_this_account_only() {let sid = current_user_sid().unwrap();diff --git a/libs/cua/crates/cua-spaces-app-core/src/dispatch.rs b/libs/cua/crates/cua-spaces-app-core/src/dispatch.rsindex 2d509351ce..659dff6692 100644--- a/libs/cua/crates/cua-spaces-app-core/src/dispatch.rs+++ b/libs/cua/crates/cua-spaces-app-core/src/dispatch.rs@@ -590,7 +590,13 @@ pub fn call_value(method: &str, args: Value) -> Result<Value, CoreError> {"keyvault.pendingSummary" => out(kv::pending_summary(&a.get("pending")?)),"keyvault.pendingRows" => out(kv::pending_rows(&a.get("overview")?)),"keyvault.accessRows" => out(kv::access_rows(&a.get("overview")?, a.get("now")?)),- "keyvault.page" => out(kv::page(&a.get("overview")?, a.get("now")?)),+ // `hostOs`: the shell's system, for its words (macOS when absent).+ "keyvault.page" => out(kv::page_on(+ &a.get("overview")?,+ a.get("now")?,+ a.get::<Option<SpaceOs>>("hostOs")?+ .unwrap_or(SpaceOs::Macos),+ )),"keyvault.sidebar" => out(browse::sidebar(&a.get("overview")?, a.get("now")?)),"keyvault.list" => out(browse::list(&a.get("overview")?,@@ -602,10 +608,12 @@ pub fn call_value(method: &str, args: Value) -> Result<Value, CoreError> {&a.get("state")?,&a.get("action")?,)),- "keyvault.vaultView" => out(vault::view(+ "keyvault.vaultView" => out(vault::view_on(&a.get("overview")?,&a.get("state")?,a.get("now")?,+ a.get::<Option<SpaceOs>>("hostOs")?+ .unwrap_or(SpaceOs::Macos),)),"keyvault.vaultSource" => out(vault::vault_source(&a.get("overview")?,@@ -635,10 +643,15 @@ pub fn call_value(method: &str, args: Value) -> Result<Value, CoreError> {"keyvault.deleteConfirm" => {out(vault::delete_confirm(a.get("count")?, a.get("liveCopies")?))}- "keyvault.labels" => out(kv::labels()),+ "keyvault.labels" => out(kv::labels_on(+ a.get::<Option<SpaceOs>>("hostOs")?+ .unwrap_or(SpaceOs::Macos),+ )),"keyvault.recoveryKeyText" => out(kv::recovery_key_text(&a.get::<String>("key")?)),- "keyvault.credentialForm" => out(crate::keyvault::credential::credential_form(+ "keyvault.credentialForm" => out(crate::keyvault::credential::credential_form_on(&a.get("overview")?,+ a.get::<Option<SpaceOs>>("hostOs")?+ .unwrap_or(SpaceOs::Macos),)),"keyvault.passphraseCheck" => out(crate::keyvault::credential::passphrase_check(a.get("mode")?,@@ -1133,6 +1146,23 @@ mod tests {assert_eq!(lede(json!("windows")), "Cua Spaces is in your system tray.");}+ /// `keyvault.labels` says what confirms in the shell's system's words+ /// (`hostOs`), and in a Mac's when it names none.+ #[test]+ fn keyvault_words_follow_the_hosts_system() {+ let note = |args: Value| {+ call_value("keyvault.labels", args).unwrap()["confirmNote"]+ .as_str()+ .unwrap()+ .to_string()+ };+ assert_eq!(note(json!({})), "Touch ID confirms in the Cua daemon.");+ assert_eq!(+ note(json!({ "hostOs": "windows" })),+ "Windows Hello or your password confirms in the Cua daemon."+ );+ }+/// `agentKeys.view` and `agentKeys.form` say where keys stay in the shell's/// system's words (`hostOs`), and in a Mac's when it names none.#[test]diff --git a/libs/cua/crates/cua-spaces-app-core/src/keyvault/credential.rs b/libs/cua/crates/cua-spaces-app-core/src/keyvault/credential.rsindex 10189b6134..a6b41ea921 100644--- a/libs/cua/crates/cua-spaces-app-core/src/keyvault/credential.rs+++ b/libs/cua/crates/cua-spaces-app-core/src/keyvault/credential.rs@@ -75,7 +75,7 @@ pub fn passphrase_only(s: &super::wire::KvStatus) -> bool {/// Mac, Windows Hello, the desktop's password prompt (polkit) on Linux.pub fn presence_word(os: SpaceOs) -> &'static str {match os {- SpaceOs::Windows => "Windows Hello",+ SpaceOs::Windows => "Windows Hello or your password",SpaceOs::Linux => "your password",SpaceOs::Macos | SpaceOs::Unknown => "Touch ID",}@@ -85,7 +85,7 @@ pub fn presence_word(os: SpaceOs) -> &'static str {fn setup_help(os: SpaceOs) -> &'static str {match os {SpaceOs::Windows => {- "Windows Hello confirms. The vault key stays in Windows Credential Manager."+ "Windows Hello or your password confirms. The vault key stays in Windows Credential Manager."}SpaceOs::Linux => {"Your password confirms (polkit). The vault key stays in the system keyring."@@ -350,7 +350,7 @@ mod tests {assert_eq!(help(SpaceOs::Windows),(- "Windows Hello confirms. The vault key stays in Windows Credential Manager.".into(),+ "Windows Hello or your password confirms. The vault key stays in Windows Credential Manager.".into(),"Unlocks with Windows Credential Manager.".into()));diff --git a/libs/cua/crates/cua-spaces-app-core/src/keyvault/vault.rs b/libs/cua/crates/cua-spaces-app-core/src/keyvault/vault.rsindex 584968d04a..33e68f6b56 100644--- a/libs/cua/crates/cua-spaces-app-core/src/keyvault/vault.rs+++ b/libs/cua/crates/cua-spaces-app-core/src/keyvault/vault.rs@@ -1423,7 +1423,7 @@ mod tests {let note = |os| view_on(&o, &st(), NOW, os).hidden_note.unwrap();assert_eq!(note(crate::model::SpaceOs::Windows),- "Names are hidden. Confirm with Windows Hello to see what is saved."+ "Names are hidden. Confirm with Windows Hello or your password to see what is saved.");assert_eq!(note(crate::model::SpaceOs::Linux),diff --git a/libs/cua/crates/cua-spaces-app-core/src/keyvault/view.rs b/libs/cua/crates/cua-spaces-app-core/src/keyvault/view.rsindex 27e91b3188..e31a9d44ab 100644--- a/libs/cua/crates/cua-spaces-app-core/src/keyvault/view.rs+++ b/libs/cua/crates/cua-spaces-app-core/src/keyvault/view.rs@@ -1024,11 +1024,11 @@ mod host_words_tests {let win = page_on(&locked(), 0, SpaceOs::Windows);assert_eq!(win.labels.confirm_note,- "Windows Hello confirms in the Cua daemon."+ "Windows Hello or your password confirms in the Cua daemon.");assert_eq!(win.kill_switch_help,- "Turning it back on asks for Windows Hello"+ "Turning it back on asks for Windows Hello or your password");assert!(win.protection.iter().any(|f| f.value == "Windows sign-in"));assert_eq!(diff --git a/libs/cua/crates/cua-spaces-ext/src/daemon/keyvault.rs b/libs/cua/crates/cua-spaces-ext/src/daemon/keyvault.rsindex 9d6ba5dc12..8f97063a63 100644--- a/libs/cua/crates/cua-spaces-ext/src/daemon/keyvault.rs+++ b/libs/cua/crates/cua-spaces-ext/src/daemon/keyvault.rs@@ -571,8 +571,14 @@ impl Backend for DaemonBackend {let source = spec.profile.clone().unwrap_or_else(|| "default".into());let mut out: Vec<Captured> = Vec::new();let mut display = self.app_display(&spec.app);+ // Items carry the provider's id (`chrome` for a Microsoft Edge capture):+ // the Space imports them through that provider.+ let provider_id = self+ .sessions+ .provider_id(&spec.app)+ .unwrap_or_else(|| spec.app.clone());let keep = |out: &mut Vec<Captured>, display: &str, scope: &str, n: record::NewRecord| {- let (meta, payload) = n.into_item(&spec.app, display, &source, scope);+ let (meta, payload) = n.into_item(&provider_id, display, &source, scope);out.push(Captured { meta, payload });};// Sites named one by one (the MCP import path): their cookies, and@@ -604,7 +610,7 @@ impl Backend for DaemonBackend {if spec.whole_app {let (scope, name, entries) = self.export_entries(&spec.app, spec.paths.as_deref())?;display = name;- let exported = record::codec_for(&spec.app).export(+ let exported = record::codec_for(&provider_id).export(entries,&ExportOptions {opted_in: spec.paths.clone().unwrap_or_default(),diff --git a/libs/cua/crates/cua-spaces-ext/src/teleport.rs b/libs/cua/crates/cua-spaces-ext/src/teleport.rsindex 417fcefff2..353d642f86 100644--- a/libs/cua/crates/cua-spaces-ext/src/teleport.rs+++ b/libs/cua/crates/cua-spaces-ext/src/teleport.rs@@ -476,9 +476,13 @@ impl AppSessions {self.providers().join(", ")))})?;+ // Keep the variant the caller named (Microsoft Edge is a Chromium+ // variant of the Chrome provider): its own profile is the source.let app_id = provider.app_ids()- .first()+ .iter()+ .find(|id| id.eq_ignore_ascii_case(app))+ .or_else(|| provider.app_ids().first()).map(|s| s.to_string()).unwrap_or_else(|| app.to_string());let app_ref = AppRef {@@ -497,13 +501,25 @@ impl AppSessions {self.resolve(app).map(|_| ())}+ /// The provider id `app` resolves to (`chrome` for Microsoft Edge), or+ /// `None` when no provider handles it.+ pub fn provider_id(&self, app: &str) -> Option<String> {+ self.resolve(app).ok().map(|(p, _)| p.id().to_string())+ }+/// The manifest for `app` on this host.pub fn manifest(&self, app: &str, scope: TeleportScope) -> Result<TeleportManifest> {let (provider, app_ref) = self.resolve(app)?;let m = provider.manifest(&app_ref, None, scope.transfer()).map_err(|e| Error::TeleportRefused(format!("{app}: {e}")))?;- Ok(TeleportManifest::from_transfer(provider.id(), scope, m))+ let mut tm = TeleportManifest::from_transfer(provider.id(), scope, m);+ // Microsoft Edge goes through the Chrome provider but keeps its own+ // name, so the approval, the capture and the export read Edge's profile.+ if cua_teleport::layout::chrome::is_edge(app) {+ tm.app = app.to_ascii_lowercase();+ }+ Ok(tm)}/// Writes the approved items as a session bundle (through the provider's@@ -702,7 +718,12 @@ impl SpaceTeleport for Space {self.id())));}- self.require(&format!("teleport.{}", approval.app))?;+ self.require(&format!(+ "teleport.{}",+ sessions+ .provider_id(&approval.app)+ .unwrap_or_else(|| approval.app.clone())+ ))?;// Local, read-only pre-check: a clear "no such provider" error// before the network round trip, not a second capture path.sessions.resolve_checked(&approval.app)?;diff --git a/libs/cua/crates/cua-spaces-ext/src/teleport_app.rs b/libs/cua/crates/cua-spaces-ext/src/teleport_app.rsindex 72a27110ea..2ed3ebbc40 100644--- a/libs/cua/crates/cua-spaces-ext/src/teleport_app.rs+++ b/libs/cua/crates/cua-spaces-ext/src/teleport_app.rs@@ -165,7 +165,12 @@ impl SpaceAppTeleport for Space {};let manifest = match (options.moves, &entry.provider_id) {(MoveKind::AppWithState, Some(provider)) => {- let provider = provider.clone();+ // Microsoft Edge reads its own profile through the Chrome provider.+ let provider = if cua_teleport::layout::chrome::is_edge(&entry.id) {+ entry.id.clone()+ } else {+ provider.clone()+ };let scope = options.scope;Some(tokio::task::spawn_blocking(move || {@@ -304,7 +309,11 @@ impl SpaceAppTeleport for Space {cua_teleport::TransferScope::FullProfile => TeleportScope::Full,};let s2 = sessions.clone();- let pid = provider_id.clone();+ let pid = if cua_teleport::layout::chrome::is_edge(&plan.app.id) {+ plan.app.id.clone()+ } else {+ provider_id.clone()+ };let manifest = tokio::task::spawn_blocking(move || s2.manifest(&pid, scope)).await.map_err(|e| Error::Transfer(e.to_string()))??;diff --git a/libs/cua/crates/cua-spaces-ffi/Cargo.toml b/libs/cua/crates/cua-spaces-ffi/Cargo.tomlindex e5c5676031..4590369e7e 100644--- a/libs/cua/crates/cua-spaces-ffi/Cargo.toml+++ b/libs/cua/crates/cua-spaces-ffi/Cargo.toml@@ -20,6 +20,7 @@ cua-spaces-ext.workspace = truecua-spaces = { path = "../cua-spaces" }cua-teleport.workspace = truecua-keyvault.workspace = true+cua-home.workspace = truecua-host.workspace = truecua-spacesd-client.workspace = truecua-telemetry.workspace = truediff --git a/libs/cua/crates/cua-spaces-ffi/src/app_core.rs b/libs/cua/crates/cua-spaces-ffi/src/app_core.rsindex ffff3e2ac9..8ace26fa18 100644--- a/libs/cua/crates/cua-spaces-ffi/src/app_core.rs+++ b/libs/cua/crates/cua-spaces-ffi/src/app_core.rs@@ -1737,11 +1737,21 @@ fn default_cua_home(var: impl Fn(&str) -> Option<std::ffi::OsString>) -> PathBufif let Some(h) = set("CUA_HOME") {return PathBuf::from(h);}- set("HOME")+ let base = set("HOME").or_else(|| set("USERPROFILE")).map(PathBuf::from).unwrap_or_default()- .join(".cua")+ .join(".cua");+ // A non-production `CUA_ENV` has its own home, where its daemon serves+ // the Keyvault (`~/.cua/envs/staging`).+ let env = var("CUA_ENV").and_then(|v| v.into_string().ok());+ match cua_home::env::CuaEnv::try_from_value(env.as_deref())+ .unwrap_or_default()+ .home_subdir()+ {+ Some(sub) => base.join(sub),+ None => base,+ }}#[uniffi::export]@@ -2739,6 +2749,25 @@ mod keyvault_home_tests {PathBuf::from(r"C:\Users\ada").join(".cua"));}++ /// Under `CUA_ENV=staging` the daemon (and so its Keyvault) lives in+ /// `~/.cua/envs/staging`; the client must look there, not in the prod+ /// home (CUA-1528).+ #[test]+ fn the_keyvault_follows_cua_env() {+ assert_eq!(+ home(&[("HOME", "/home/ada"), ("CUA_ENV", "staging")]),+ PathBuf::from("/home/ada/.cua").join("envs/staging")+ );+ assert_eq!(+ home(&[("HOME", "/home/ada"), ("CUA_ENV", "prod")]),+ PathBuf::from("/home/ada/.cua")+ );+ assert_eq!(+ home(&[("CUA_HOME", "/srv/cua"), ("CUA_ENV", "staging")]),+ PathBuf::from("/srv/cua")+ );+ }}#[cfg(test)]diff --git a/libs/cua/crates/cua-spaces-ffi/src/presence.rs b/libs/cua/crates/cua-spaces-ffi/src/presence.rsindex d5184957db..f27b0e7ca0 100644--- a/libs/cua/crates/cua-spaces-ffi/src/presence.rs+++ b/libs/cua/crates/cua-spaces-ffi/src/presence.rs@@ -5,7 +5,8 @@//! make (approving a device for the account), the system's own prompt the//! daemon's Keyvault asks for too: on macOS LocalAuthentication (Touch ID,//! an Apple Watch or the login password, as the SwiftUI app's-//! `LivePresence`), on Windows Windows Hello (face, fingerprint or PIN), on+//! `LivePresence`), on Windows Windows Hello (face, fingerprint or PIN) or, where that is not set up,+//! the account password in Windows' own credential prompt, on//! Linux polkit's `ai.cua.spaces.devices` (the user's password or//! fingerprint through the session's agent). The Electron app calls it from//! its main process, so the prompt is for Cua Spaces.@@ -40,7 +41,7 @@ fn presence_error(e: AuthError) -> CuaError {CuaError::PermissionDenied("Touch ID and the login password are not available".into())}AuthError::Unavailable if cfg!(target_os = "windows") => CuaError::Unsupported(- "Windows Hello is not set up (a PIN, fingerprint or face in Settings, Accounts, Sign-in options)".into(),+ "Windows could not confirm it is you: set up Windows Hello, or give this account a password (Settings, Accounts, Sign-in options)".into(),),AuthError::Unavailable if cfg!(target_os = "linux") => CuaError::Unsupported("polkit cannot ask (no authentication agent in this session, or the ai.cua.spaces.devices action is not installed)".into(),diff --git a/libs/cua/crates/cua-spaces-ffi/src/teleport.rs b/libs/cua/crates/cua-spaces-ffi/src/teleport.rsindex aae08f1ee8..9c7ed85cdf 100644--- a/libs/cua/crates/cua-spaces-ffi/src/teleport.rs+++ b/libs/cua/crates/cua-spaces-ffi/src/teleport.rs@@ -294,8 +294,14 @@ impl Teleport {}}let paths: Vec<String> = selected.iter().map(|i| i.rel_path.clone()).collect();+ // A Chromium variant (Microsoft Edge) is captured from its own profile.+ let capture_app = if cua_teleport::layout::chrome::is_edge(&app_ref.app_id) {+ app_ref.app_id.clone()+ } else {+ manifest.provider_id.clone()+ };let spec = cua_keyvault::broker::ImportSpec {- app: manifest.provider_id.clone(),+ app: capture_app,profile: None,sites: vec![],whole_app: true,diff --git a/libs/cua/crates/cua-teleport-bundle/src/layout.rs b/libs/cua/crates/cua-teleport-bundle/src/layout.rsindex 34acc3ff75..ef1280f8c2 100644--- a/libs/cua/crates/cua-teleport-bundle/src/layout.rs+++ b/libs/cua/crates/cua-teleport-bundle/src/layout.rs@@ -75,8 +75,42 @@ pub mod chrome {// these an obviously-teleportable window reads as unsupported."Google Chrome","Google Chrome Canary",+ // Microsoft Edge (Chromium): the default browser on Windows. Same+ // profile layout and cookie store as Chrome, in its own user-data dir.+ "edge",+ "msedge",+ "microsoft-edge",+ "microsoft-edge-stable",+ "com.microsoft.edgemac",+ "Microsoft Edge",];+ /// The subset of [`APP_IDS`] that names Microsoft Edge.+ pub const EDGE_APP_IDS: &[&str] = &[+ "edge",+ "msedge",+ "microsoft-edge",+ "microsoft-edge-stable",+ "com.microsoft.edgemac",+ "Microsoft Edge",+ ];++ /// Whether `app_id` names Microsoft Edge (case-insensitive).+ pub fn is_edge(app_id: &str) -> bool {+ EDGE_APP_IDS.iter().any(|e| e.eq_ignore_ascii_case(app_id))+ }++ /// Edge's user-data dir on `platform`, relative to that platform's home.+ /// Only the *source* side reads it; the bundle stays in the canonical+ /// Chrome layout and the receiver opens it in the Space's Chrome.+ pub fn edge_user_data_dir_for(platform: Platform) -> &'static str {+ match platform {+ Platform::MacOS => "Library/Application Support/Microsoft Edge",+ Platform::Linux => ".config/microsoft-edge",+ Platform::Windows => "AppData/Local/Microsoft/Edge/User Data",+ }+ }+/// Curated files copied for a full-profile transfer, with sensitivity flags./// Caches, GPU, and code-cache directories are intentionally excluded.pub const PROFILE_FILES: &[(&str, bool)] = &[diff --git a/libs/cua/crates/cua-teleport/Cargo.toml b/libs/cua/crates/cua-teleport/Cargo.tomlindex a1117ba5e5..c0adf84a97 100644--- a/libs/cua/crates/cua-teleport/Cargo.toml+++ b/libs/cua/crates/cua-teleport/Cargo.toml@@ -64,7 +64,19 @@ objc2-app-kit = { version = "0.3", default-features = false, features = ["std",# Windows Hello (`UserConsentVerifier`) as the gate on sensitive exports and# on what the Keyvault lets through.[target.'cfg(target_os = "windows")'.dependencies]-windows = { version = "0.58", features = ["Foundation", "Security_Credentials_UI", "Win32_Foundation", "Win32_System_WinRT", "Win32_UI_WindowsAndMessaging"] }+windows = { version = "0.58", features = [+ "Foundation",+ "Security_Credentials_UI",+ "Win32_Foundation",+ "Win32_Graphics_Gdi",+ "Win32_Security",+ "Win32_Security_Authentication_Identity",+ "Win32_Security_Credentials",+ "Win32_System_Com",+ "Win32_System_Threading",+ "Win32_System_WinRT",+ "Win32_UI_WindowsAndMessaging",+] }[dev-dependencies]cua-spacesd-client = { workspace = true, features = ["testing"] }diff --git a/libs/cua/crates/cua-teleport/src/biometric.rs b/libs/cua/crates/cua-teleport/src/biometric.rsindex 6530ccd844..3fa6cc4132 100644--- a/libs/cua/crates/cua-teleport/src/biometric.rs+++ b/libs/cua/crates/cua-teleport/src/biometric.rs@@ -21,8 +21,14 @@//! `LAPolicyDeviceOwnerAuthentication` — Touch ID with a device-passcode//! fallback, the robust choice for an unsigned CLI.//! - **Windows**: Windows Hello (`UserConsentVerifier`): the face, fingerprint-//! or PIN the user set up, shown over the foreground window. No Hello set up-//! (or a policy that turns it off) is [`AuthError::Unavailable`].+//! or PIN the user set up, shown over the foreground window. Where Hello is+//! not set up (VMs, Server, many managed PCs) or a policy turns it off, the+//! fallback is Windows' own credential prompt+//! (`CredUIPromptForWindowsCredentials`, as UAC asks): the user types their+//! account password, which `LogonUserW` verifies, and the logon must be for+//! the very account this process runs as (compared by SID). An account with+//! no password, or a prompt that cannot be shown, is+//! [`AuthError::Unavailable`].//! - **Linux**: polkit. `pkcheck` asks the desktop's authentication agent to//! confirm the user ([`POLKIT_ACTION`], `auth_self`: their own password or//! fingerprint, every time). No polkit, no agent or no installed action is@@ -56,8 +62,7 @@ pub const ALLOW_UNVERIFIED_ENV: &str = "CUA_ENV_ALLOW_UNVERIFIED_SENSITIVE_EXPOR#[cfg(target_os = "macos")]const UNAVAILABLE_HELP: &str = "this Mac needs Touch ID or a login password";#[cfg(target_os = "windows")]-const UNAVAILABLE_HELP: &str =- "Windows Hello needs a PIN, fingerprint or face set up in Settings, Accounts, Sign-in options";+const UNAVAILABLE_HELP: &str = "Cua asks for Windows Hello, or your Windows account password when Hello is not set up; this account has neither (set a password in Settings, Accounts, Sign-in options)";#[cfg(target_os = "linux")]const UNAVAILABLE_HELP: &str = "polkit needs an authentication agent in the session and the ai.cua.spaces.keyvault action installed (the Cua .deb installs it)";#[cfg(not(any(target_os = "macos", target_os = "windows", target_os = "linux")))]@@ -84,10 +89,7 @@ impl std::fmt::Display for AuthError {fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {match self {Self::Denied => write!(f, "biometric authorization was denied"),- Self::Unavailable => write!(- f,- "user confirmation is unavailable: {UNAVAILABLE_HELP} (set {ALLOW_UNVERIFIED_ENV}=1 to proceed without it)"- ),+ Self::Unavailable => write!(f, "user confirmation is unavailable: {UNAVAILABLE_HELP}"),Self::Cancelled => write!(f, "biometric authorization was cancelled"),Self::Failed(detail) => write!(f, "the confirmation prompt failed: {detail}"),}@@ -168,7 +170,7 @@ fn authorize_platform(reason: &str) -> Result<(), AuthError> {#[cfg(any(target_os = "windows", target_os = "linux"))]fn authorize_platform(reason: &str) -> Result<(), AuthError> {#[cfg(target_os = "windows")]- let asked = hello::authorize(reason);+ let asked = windows_authorize(reason);#[cfg(target_os = "linux")]let asked = polkit::authorize(POLKIT_ACTION, reason);match asked {@@ -318,7 +320,7 @@ pub fn confirm_user(polkit_action: &str, reason: &str) -> Result<(), AuthError>#[cfg(target_os = "windows")]{let _ = polkit_action;- hello::authorize(reason)+ windows_authorize(reason)}#[cfg(target_os = "linux")]{@@ -331,6 +333,64 @@ pub fn confirm_user(polkit_action: &str, reason: &str) -> Result<(), AuthError>}}+/// Windows: Hello when it is set up, else the account password prompt. A+/// Hello prompt the user answered, either way, is final: a refusal or a+/// cancel never falls through to the password prompt.+#[cfg(target_os = "windows")]+fn windows_authorize(reason: &str) -> Result<(), AuthError> {+ match hello::authorize(reason) {+ Err(AuthError::Unavailable) => password::authorize(reason),+ other => other,+ }+}++/// How many wrong passwords one confirmation allows before it is refused.+/// Each wrong one also counts toward the account's lockout policy, as at the+/// sign-in screen.+#[cfg_attr(not(target_os = "windows"), allow(dead_code))]+const PASSWORD_ATTEMPTS: u32 = 3;++/// The pieces of the name a credential prompt returned: `DOMAIN\user`,+/// `user@domain` (a UPN, passed whole with no domain) or a bare `user`.+/// Returns (user, domain); an absent domain is `.`, this computer's own+/// accounts.+#[cfg_attr(not(target_os = "windows"), allow(dead_code))]+fn split_account(name: &str) -> (String, Option<String>) {+ if let Some((domain, user)) = name.split_once('\\') {+ let domain = if domain.is_empty() { "." } else { domain };+ return (user.to_string(), Some(domain.to_string()));+ }+ if name.contains('@') {+ return (name.to_string(), None);+ }+ (name.to_string(), Some(".".to_string()))+}++/// The password prompt's outcome for one typed credential, decided from what+/// the system said about it. Pure so every branch is testable off Windows:+/// `password_empty` (a blank password proves nothing), `logon_ok`+/// (`LogonUserW` accepted it), `same_account` (the logon token's SID is this+/// process's own).+#[cfg_attr(not(target_os = "windows"), allow(dead_code))]+fn password_verdict(password_empty: bool, logon_ok: bool, same_account: bool) -> PasswordVerdict {+ if password_empty || !logon_ok {+ PasswordVerdict::Retry+ } else if !same_account {+ // Right password, another account: never confirms this user.+ PasswordVerdict::Refuse+ } else {+ PasswordVerdict::Confirmed+ }+}++#[cfg_attr(not(target_os = "windows"), allow(dead_code))]+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum PasswordVerdict {+ Confirmed,+ Retry,+ Refuse,+}+/// `UserConsentVerificationResult`'s values, as the system numbers them.#[cfg_attr(not(target_os = "windows"), allow(dead_code))]fn hello_result(value: i32) -> Result<(), AuthError> {@@ -431,6 +491,309 @@ mod hello {}}+#[cfg(target_os = "windows")]+mod password {+ //! The fallback where Windows Hello is not set up: Windows' own+ //! credential prompt, the one UAC uses (`CredUIPromptForWindowsCredentials`),+ //! then `LogonUserW` to check what was typed. The prompt shows this+ //! user's name already filled in. The logon must produce a token for the+ //! SID this process runs as, so another account's password (an+ //! administrator's, say) never confirms this user. The password lives in+ //! buffers that are overwritten before they are freed, and is never+ //! logged or returned.++ use std::ffi::c_void;++ use windows::Win32::Foundation::{+ CloseHandle, ERROR_CANCELLED, ERROR_LOGON_FAILURE, ERROR_SUCCESS, HANDLE,+ };+ use windows::Win32::Security::Authentication::Identity::{GetUserNameExW, NameSamCompatible};+ use windows::Win32::Security::Credentials::{+ CREDUI_INFOW, CREDUIWIN_GENERIC, CredPackAuthenticationBufferW,+ CredUIPromptForWindowsCredentialsW, CredUnPackAuthenticationBufferW,+ };+ use windows::Win32::Security::{+ EqualSid, GetTokenInformation, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,+ LogonUserW, PSID, TOKEN_QUERY, TOKEN_USER, TokenUser,+ };+ use windows::Win32::System::Com::CoTaskMemFree;+ use windows::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken};+ use windows::Win32::UI::WindowsAndMessaging::GetForegroundWindow;+ use windows::core::{HSTRING, PCWSTR, PWSTR};++ use super::{AuthError, PASSWORD_ATTEMPTS, PasswordVerdict, password_verdict, split_account};++ /// Overwrites `len` bytes in a way the optimizer may not drop.+ fn wipe(ptr: *mut u8, len: usize) {+ for i in 0..len {+ // SAFETY: the caller passes a live allocation of `len` bytes.+ unsafe { std::ptr::write_volatile(ptr.add(i), 0) };+ }+ std::sync::atomic::compiler_fence(std::sync::atomic::Ordering::SeqCst);+ }++ /// A UTF-16 buffer overwritten with zeros when dropped.+ struct Secret(Vec<u16>);++ impl Drop for Secret {+ fn drop(&mut self) {+ wipe(self.0.as_mut_ptr().cast(), self.0.len() * 2);+ }+ }++ /// A prompt result the system allocated, wiped and freed on drop.+ struct AuthBuffer(*mut c_void, u32);++ impl Drop for AuthBuffer {+ fn drop(&mut self) {+ if !self.0.is_null() {+ wipe(self.0.cast(), self.1 as usize);+ // SAFETY: the prompt allocated it with CoTaskMemAlloc.+ unsafe { CoTaskMemFree(Some(self.0)) };+ }+ }+ }++ /// A kernel handle closed on drop.+ struct Handle(HANDLE);++ impl Drop for Handle {+ fn drop(&mut self) {+ // SAFETY: the handle came from a call that opened it.+ unsafe {+ let _ = CloseHandle(self.0);+ }+ }+ }++ /// A token's TOKEN_USER, with the SID it points to, in one allocation.+ struct TokenUserBuf(Vec<u64>);++ impl TokenUserBuf {+ fn of(token: HANDLE) -> Option<Self> {+ let mut need = 0u32;+ // SAFETY: a null buffer asks for the size.+ unsafe {+ let _ = GetTokenInformation(token, TokenUser, None, 0, &mut need);+ }+ if need == 0 {+ return None;+ }+ // u64 elements keep the buffer aligned for TOKEN_USER.+ let mut buf = vec![0u64; (need as usize).div_ceil(8)];+ // SAFETY: `buf` is at least `need` bytes.+ unsafe {+ GetTokenInformation(+ token,+ TokenUser,+ Some(buf.as_mut_ptr().cast()),+ need,+ &mut need,+ )+ }+ .ok()?;+ Some(Self(buf))+ }++ fn sid(&self) -> PSID {+ // SAFETY: the buffer holds a TOKEN_USER written by the system.+ unsafe { (*(self.0.as_ptr() as *const TOKEN_USER)).User.Sid }+ }+ }++ fn wide_nul(s: &str) -> Vec<u16> {+ s.encode_utf16().chain(std::iter::once(0)).collect()+ }++ /// `DOMAIN\user` of the account this process runs as.+ fn current_account() -> Option<String> {+ let mut len = 0u32;+ // SAFETY: a null buffer asks for the size (the call reports failure).+ unsafe {+ let _ = GetUserNameExW(NameSamCompatible, PWSTR::null(), &mut len);+ }+ if len == 0 {+ return None;+ }+ let mut buf = vec![0u16; len as usize + 1];+ let mut cap = buf.len() as u32;+ // SAFETY: `buf` holds `cap` UTF-16 units.+ let ok = unsafe { GetUserNameExW(NameSamCompatible, PWSTR(buf.as_mut_ptr()), &mut cap) };+ (ok.as_bool() || cap > 0).then(|| String::from_utf16_lossy(&buf[..cap as usize]))+ }++ fn own_token_user() -> Option<TokenUserBuf> {+ let mut token = HANDLE::default();+ // SAFETY: the pseudo-handle of this process and an out handle.+ unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) }.ok()?;+ let token = Handle(token);+ TokenUserBuf::of(token.0)+ }++ /// The packed credential with this user's name filled in, an empty+ /// password, to start the prompt on the right account.+ fn prefilled(account: &str) -> Option<Vec<u8>> {+ let user = wide_nul(account);+ let empty = [0u16];+ let mut size = 0u32;+ // SAFETY: a null buffer asks for the size.+ unsafe {+ let _ = CredPackAuthenticationBufferW(+ Default::default(),+ PCWSTR(user.as_ptr()),+ PCWSTR(empty.as_ptr()),+ None,+ &mut size,+ );+ }+ if size == 0 {+ return None;+ }+ let mut out = vec![0u8; size as usize];+ // SAFETY: `out` is `size` bytes.+ unsafe {+ CredPackAuthenticationBufferW(+ Default::default(),+ PCWSTR(user.as_ptr()),+ PCWSTR(empty.as_ptr()),+ Some(out.as_mut_ptr()),+ &mut size,+ )+ }+ .ok()?;+ Some(out)+ }++ enum Typed {+ Credential(Secret, String),+ Cancelled,+ }++ /// Shows the prompt once. `auth_error` names why the last try failed.+ fn prompt(reason: &str, input: &[u8], auth_error: u32) -> Result<Typed, AuthError> {+ let caption = HSTRING::from("Cua Spaces");+ let message = HSTRING::from(reason);+ let info = CREDUI_INFOW {+ cbSize: std::mem::size_of::<CREDUI_INFOW>() as u32,+ // SAFETY: no arguments; a null window is allowed.+ hwndParent: unsafe { GetForegroundWindow() },+ pszMessageText: PCWSTR(message.as_ptr()),+ pszCaptionText: PCWSTR(caption.as_ptr()),+ hbmBanner: Default::default(),+ };+ let mut package = 0u32;+ let mut out: *mut c_void = std::ptr::null_mut();+ let mut out_len = 0u32;+ // SAFETY: every pointer is to a live local; `input` is a packed buffer.+ let rc = unsafe {+ CredUIPromptForWindowsCredentialsW(+ Some(&info),+ auth_error,+ &mut package,+ Some(input.as_ptr().cast()),+ input.len() as u32,+ &mut out,+ &mut out_len,+ None,+ CREDUIWIN_GENERIC,+ )+ };+ let buffer = AuthBuffer(out, out_len);+ if rc == ERROR_CANCELLED.0 {+ return Ok(Typed::Cancelled);+ }+ if rc != ERROR_SUCCESS.0 {+ return Err(AuthError::Failed(format!(+ "the Windows credential prompt failed ({rc})"+ )));+ }+ let (mut user, mut domain) = (vec![0u16; 513], vec![0u16; 257]);+ let mut pass = Secret(vec![0u16; 513]);+ let (mut ul, mut dl, mut pl) =+ (user.len() as u32, domain.len() as u32, pass.0.len() as u32);+ // SAFETY: each buffer is as long as the length given beside it.+ let unpacked = unsafe {+ CredUnPackAuthenticationBufferW(+ Default::default(),+ buffer.0,+ buffer.1,+ PWSTR(user.as_mut_ptr()),+ &mut ul,+ PWSTR(domain.as_mut_ptr()),+ Some(&mut dl),+ PWSTR(pass.0.as_mut_ptr()),+ &mut pl,+ )+ };+ unpacked.map_err(|_| AuthError::Failed("the typed credential could not be read".into()))?;+ let name =+ String::from_utf16_lossy(&user[..(ul as usize).saturating_sub(1).min(user.len())]);+ pass.0.truncate((pl as usize).saturating_sub(1));+ Ok(Typed::Credential(pass, name))+ }++ /// Whether `LogonUserW` takes this password, and for which SID.+ fn logon(name: &str, password: &Secret, mine: &TokenUserBuf) -> (bool, bool) {+ let (user, domain) = split_account(name);+ let user = wide_nul(&user);+ let domain = domain.map(|d| wide_nul(&d));+ let mut pw = password.0.clone();+ pw.push(0);+ let pw = Secret(pw);+ let mut token = HANDLE::default();+ // SAFETY: NUL-terminated strings that outlive the call, and an out handle.+ let ok = unsafe {+ LogonUserW(+ PCWSTR(user.as_ptr()),+ domain+ .as_ref()+ .map_or(PCWSTR::null(), |d| PCWSTR(d.as_ptr())),+ PCWSTR(pw.0.as_ptr()),+ LOGON32_LOGON_INTERACTIVE,+ LOGON32_PROVIDER_DEFAULT,+ &mut token,+ )+ };+ if ok.is_err() {+ return (false, false);+ }+ let token = Handle(token);+ let same = TokenUserBuf::of(token.0)+ // SAFETY: both SIDs live in their buffers.+ .is_some_and(|theirs| unsafe { EqualSid(mine.sid(), theirs.sid()) }.is_ok());+ (true, same)+ }++ pub(super) fn authorize(reason: &str) -> Result<(), AuthError> {+ let (Some(account), Some(mine)) = (current_account(), own_token_user()) else {+ return Err(AuthError::Unavailable);+ };+ let Some(input) = prefilled(&account) else {+ return Err(AuthError::Unavailable);+ };+ let mut auth_error = 0u32;+ for _ in 0..PASSWORD_ATTEMPTS {+ let (password, name) = match prompt(reason, &input, auth_error)? {+ Typed::Cancelled => return Err(AuthError::Cancelled),+ Typed::Credential(p, n) => (p, n),+ };+ let empty = password.0.is_empty();+ let (logon_ok, same) = if empty {+ (false, false)+ } else {+ logon(&name, &password, &mine)+ };+ drop(password);+ match password_verdict(empty, logon_ok, same) {+ PasswordVerdict::Confirmed => return Ok(()),+ PasswordVerdict::Refuse => return Err(AuthError::Denied),+ PasswordVerdict::Retry => auth_error = ERROR_LOGON_FAILURE.0,+ }+ }+ Err(AuthError::Denied)+ }+}+#[cfg(target_os = "linux")]mod polkit {//! polkit through `pkcheck`, which asks the session's authentication agent.@@ -573,6 +936,48 @@ mod tests {assert_eq!(non_macos_decision(true, "reason"), Ok(()));}+ #[test]+ fn typed_names_split_into_user_and_domain() {+ assert_eq!(+ split_account("WIN\\alice"),+ ("alice".into(), Some("WIN".into()))+ );+ assert_eq!(+ split_account(".\\alice"),+ ("alice".into(), Some(".".into()))+ );+ assert_eq!(split_account("\\alice"), ("alice".into(), Some(".".into())));+ // A UPN goes whole, with no domain.+ assert_eq!(+ split_account("[email protected]"),+ ("[email protected]".into(), None)+ );+ assert_eq!(split_account("alice"), ("alice".into(), Some(".".into())));+ }++ #[test]+ fn only_the_right_password_for_this_account_confirms() {+ use PasswordVerdict::*;+ // Blank proves nothing, even if the system would accept it.+ assert_eq!(password_verdict(true, true, true), Retry);+ // Wrong password.+ assert_eq!(password_verdict(false, false, false), Retry);+ assert_eq!(password_verdict(false, false, true), Retry);+ // Right password for another account (an administrator's): refused.+ assert_eq!(password_verdict(false, true, false), Refuse);+ assert_eq!(password_verdict(false, true, true), Confirmed);+ const { assert!(PASSWORD_ATTEMPTS <= 3) };+ }++ #[test]+ fn the_unavailable_message_does_not_advertise_the_override() {+ let m = AuthError::Unavailable.to_string();+ assert!(+ !m.contains(ALLOW_UNVERIFIED_ENV) && !m.contains("CUA_ENV"),+ "{m}"+ );+ }+#[test]fn windows_hello_results_map_to_the_gate() {assert_eq!(hello_result(0), Ok(()));diff --git a/libs/cua/crates/cua-teleport/src/providers/chrome.rs b/libs/cua/crates/cua-teleport/src/providers/chrome.rsindex 76127c1f82..d6027050a3 100644--- a/libs/cua/crates/cua-teleport/src/providers/chrome.rs+++ b/libs/cua/crates/cua-teleport/src/providers/chrome.rs@@ -22,7 +22,7 @@ use crate::host::{EffectKind, HostCommand};use crate::host::{HostEffects, default_host};use crate::layout::chrome::{APP_IDS as CHROME_APP_IDS, PROFILE_DIRS, PROFILE_FILES, SESSION_FILES, TABS_JSON,- dest_rel_path, user_data_dir_for,+ dest_rel_path, edge_user_data_dir_for, is_edge, user_data_dir_for,};use crate::providers::util::{add_dir_recursive, add_file_best_effort, dir_len, file_len};use crate::{@@ -111,11 +111,17 @@ impl ChromeProvider {/// (what `--profile` sets), then `Default` — the/// profile a plain `Chrome` launch uses, which is the right default because/// asking to teleport "my Chrome" means the one the user is signed in to.+ #[cfg(test)]fn source_profile_dir(&self, platform: Platform) -> Option<PathBuf> {+ self.source_profile_dir_for(platform, false)+ }++ /// [`Self::source_profile_dir`] for Microsoft Edge when `edge`.+ fn source_profile_dir_for(&self, platform: Platform, edge: bool) -> Option<PathBuf> {if let Some(dir) = &self.profile_dir_override {return Some(dir.clone());}- let root = self.user_data_dir(platform)?;+ let root = self.user_data_dir_for_browser(platform, edge)?;Some(match &self.profile_selector {Some(value) => Self::resolve_profile(&root, value),None => root.join("Default"),@@ -123,8 +129,13 @@ impl ChromeProvider {}/// The platform's Chrome user-data dir — the parent of every profile.- fn user_data_dir(&self, platform: Platform) -> Option<PathBuf> {- Some(self.host.home_dir()?.join(user_data_dir_for(platform)))+ fn user_data_dir_for_browser(&self, platform: Platform, edge: bool) -> Option<PathBuf> {+ let rel = if edge {+ edge_user_data_dir_for(platform)+ } else {+ user_data_dir_for(platform)+ };+ Some(self.host.home_dir()?.join(rel))}/// Interpret a profile selector: a path (absolute, or containing a@@ -146,15 +157,20 @@ impl ChromeProvider {/// `source_profile_dir`, but failing loudly: a selector that names no/// profile on disk would otherwise capture an empty bundle and look like a/// successful teleport, so name the profiles that do exist instead.+ #[cfg(test)]fn resolved_profile_dir(&self, platform: Platform) -> Result<PathBuf> {+ self.resolved_profile_dir_for(platform, false)+ }++ fn resolved_profile_dir_for(&self, platform: Platform, edge: bool) -> Result<PathBuf> {let dir = self- .source_profile_dir(platform)+ .source_profile_dir_for(platform, edge).ok_or_else(|| TeleportError::Provider("could not resolve home directory".into()))?;// Only an explicit selection is validated; a missing `Default` is left// to the existing per-item best-effort handling (Chrome may simply not// be installed, which is not an argument error).if self.profile_dir_override.is_none() && self.profile_selector.is_some() && !dir.is_dir() {- let available = self.available_profiles(platform);+ let available = self.available_profiles_for(platform, edge);let available = if available.is_empty() {"none found".to_string()} else {@@ -172,7 +188,11 @@ impl ChromeProvider {/// callers offering a picker. A directory is a profile if it holds/// `Preferences`, which every real profile has and no sibling cache dir does.pub fn available_profiles(&self, platform: Platform) -> Vec<String> {- let Some(root) = self.user_data_dir(platform) else {+ self.available_profiles_for(platform, false)+ }++ fn available_profiles_for(&self, platform: Platform, edge: bool) -> Vec<String> {+ let Some(root) = self.user_data_dir_for_browser(platform, edge) else {return Vec::new();};let Ok(entries) = std::fs::read_dir(&root) else {@@ -607,7 +627,7 @@ impl ExportProvider for ChromeProvider {_window: Option<&WindowRef>,scope: TransferScope,) -> Result<TransferManifest> {- let profile_dir = self.resolved_profile_dir(app.platform)?;+ let profile_dir = self.resolved_profile_dir_for(app.platform, is_edge(&app.app_id))?;let profile = profile_name(&profile_dir);let mut items = Vec::new();@@ -692,7 +712,7 @@ impl ExportProvider for ChromeProvider {include: Option<&HashSet<String>>,out: &mut dyn Write,) -> Result<()> {- let profile_dir = self.resolved_profile_dir(app.platform)?;+ let profile_dir = self.resolved_profile_dir_for(app.platform, is_edge(&app.app_id))?;let profile = profile_name(&profile_dir);let mut writer = BundleWriter::with_limit(@@ -758,6 +778,11 @@ impl ExportProvider for ChromeProvider {if *name == "Cookies" {let cookies = crate::browser_cookies::ChromeCookies::new(self.host.clone()).with_platform(app.platform)+ .with_browser(if is_edge(&app.app_id) {+ "edge"+ } else {+ "chrome"+ }).with_profile_dir(profile_dir.clone()).read(&[])?;if !cookies.is_empty() {@@ -1620,6 +1645,41 @@ mod profile_selection_tests {assert!(provider.resolved_profile_dir(Platform::MacOS).is_ok());}+ #[test]+ fn microsoft_edge_is_a_chromium_variant_with_its_own_user_data_dir() {+ let provider = ChromeProvider::new();+ for id in ["edge", "msedge", "Microsoft Edge", "com.microsoft.edgemac"] {+ assert!(+ provider.matches(&AppRef {+ app_id: id.into(),+ display_name: "Microsoft Edge".into(),+ platform: Platform::Windows,+ }),+ "{id}"+ );+ assert!(is_edge(id), "{id}");+ }+ assert!(!is_edge("chrome"));+ let home = tempfile::tempdir().unwrap();+ let provider = ChromeProvider::new().with_host(Arc::new(+ crate::host::FakeHost::new().with_home(home.path()),+ ));+ let win = provider+ .source_profile_dir_for(Platform::Windows, true)+ .unwrap();+ assert!(+ win.ends_with("AppData/Local/Microsoft/Edge/User Data/Default"),+ "{win:?}"+ );+ let chrome = provider+ .source_profile_dir_for(Platform::Windows, false)+ .unwrap();+ assert!(+ chrome.ends_with("AppData/Local/Google/Chrome/User Data/Default"),+ "{chrome:?}"+ );+ }+#[test]fn available_profiles_lists_default_first() {// Exercised via resolve_profile's sibling sorting contract: a realdiff --git a/libs/cua/crates/cua-teleport/src/ux/catalog.rs b/libs/cua/crates/cua-teleport/src/ux/catalog.rsindex 7afbed7d0d..62ff992cfe 100644--- a/libs/cua/crates/cua-teleport/src/ux/catalog.rs+++ b/libs/cua/crates/cua-teleport/src/ux/catalog.rs@@ -598,6 +598,27 @@ mod tests {}}+ #[test]+ fn edge_on_windows_teleports_through_the_chrome_provider() {+ let edge = HostApp {+ name: "Microsoft Edge".into(),+ app_id: None,+ path: r"C:\\ProgramData\\Start Menu\\Microsoft Edge.lnk".into(),+ version: None,+ icon: None,+ platform: Platform::Windows,+ };+ let e = classify(+ &edge,+ &providers(),+ Platform::Windows,+ &TargetHint::default(),+ );+ assert_eq!(e.id, "edge");+ assert_eq!(e.provider_id.as_deref(), Some("chrome"));+ assert_eq!(e.capability, Capability::Full);+ }+#[test]fn the_target_table_parses_and_names_real_installables_and_providers() {let ids = crate::layout::PROVIDER_IDS;diff --git a/libs/cua/crates/cua-teleport/src/ux/targets.json b/libs/cua/crates/cua-teleport/src/ux/targets.jsonindex 7c01a82c9d..ab468b6c94 100644--- a/libs/cua/crates/cua-teleport/src/ux/targets.json+++ b/libs/cua/crates/cua-teleport/src/ux/targets.json@@ -30,6 +30,14 @@"launch": { "bin": "google-chrome" },"opens_files": true},+ "edge": {+ "name": "Microsoft Edge",+ "match": ["edge", "msedge", "microsoft-edge", "microsoft-edge-stable", "com.microsoft.edgemac", "Microsoft Edge"],+ "provider": "chrome",+ "image": true,+ "launch": { "bin": "google-chrome" },+ "opens_files": true+ },"claude-code": {"name": "Claude Code","match": ["claude-code", "claude", "Claude Code"],diff --git a/libs/cua/crates/cua-vmm/src/container/engine.rs b/libs/cua/crates/cua-vmm/src/container/engine.rsindex 6b143ef7af..c604b9bd13 100644--- a/libs/cua/crates/cua-vmm/src/container/engine.rs+++ b/libs/cua/crates/cua-vmm/src/container/engine.rs@@ -130,6 +130,23 @@ fn well_known_sockets() -> Vec<PathBuf> {#[cfg(windows)]const WINDOWS_ENGINE_PIPE: &str = r"\\.\pipe\docker_engine";+/// Docker Desktop's own Linux-engine pipe: present as soon as Docker Desktop+/// has started, even when the CLI's `docker_engine` proxy pipe or the docker+/// context file is not there yet (or was written after this process started).+#[cfg(windows)]+const WINDOWS_DESKTOP_LINUX_PIPE: &str = r"\\.\pipe\dockerDesktopLinuxEngine";++/// Whether a named pipe exists. A pipe whose listening instance is taken at+/// this instant answers ERROR_PIPE_BUSY (231) to a probe: busy is there,+/// where `Path::exists` says no (CUA-1523).+#[cfg(windows)]+fn pipe_exists(path: &str) -> bool {+ match std::fs::metadata(path) {+ Ok(_) => true,+ Err(e) => e.raw_os_error() == Some(231),+ }+}+/// How to get a container engine on this host, for "no engine found".pub fn install_hint() -> &'static str {match std::env::consts::OS {@@ -271,13 +288,21 @@ pub fn discover() -> Option<EngineEndpoint> {}}#[cfg(windows)]- if Path::new(WINDOWS_ENGINE_PIPE).exists() {+ if pipe_exists(WINDOWS_ENGINE_PIPE) {return Some(EngineEndpoint {uri: "npipe:////./pipe/docker_engine".into(),source: "socket".into(),kind: EngineKind::DockerDesktop,});}+ #[cfg(windows)]+ if pipe_exists(WINDOWS_DESKTOP_LINUX_PIPE) {+ return Some(EngineEndpoint {+ uri: "npipe:////./pipe/dockerDesktopLinuxEngine".into(),+ source: "socket".into(),+ kind: EngineKind::DockerDesktop,+ });+ }well_known_sockets().into_iter().find(|p| p.exists())diff --git a/libs/cua/crates/cua-vmm/src/container/mod.rs b/libs/cua/crates/cua-vmm/src/container/mod.rsindex 45e51a3b53..b93b8aa7eb 100644--- a/libs/cua/crates/cua-vmm/src/container/mod.rs+++ b/libs/cua/crates/cua-vmm/src/container/mod.rs@@ -204,7 +204,7 @@ impl ContainerRuntime {}_ => {}}- let docker = connect_uri(&endpoint.uri)?;+ let docker = connect_uri(&endpoint.uri).await?;docker.ping().await.map_err(|e| match check {// Something accepts on the socket but does not speak the// Docker API as expected: an engine error, not a stopped one.@@ -332,12 +332,17 @@ impl ContainerRuntime {// dockerd restarts; wait for it to come back with runsc registered.let deadline = tokio::time::Instant::now() + Duration::from_secs(300);while tokio::time::Instant::now() < deadline {- if let Ok(rts) = connect_uri(&self.endpoint.uri)?.info().await.map(|i| {- i.runtimes- .unwrap_or_default()- .into_keys()- .collect::<Vec<_>>()- }) && rts.iter().any(|r| r == "runsc")+ if let Ok(rts) = connect_uri(&self.endpoint.uri)+ .await?+ .info()+ .await+ .map(|i| {+ i.runtimes+ .unwrap_or_default()+ .into_keys()+ .collect::<Vec<_>>()+ })+ && rts.iter().any(|r| r == "runsc"){return Ok(());}@@ -782,18 +787,42 @@ fn registry_credentials(_reference: &str) -> Option<bollard::auth::DockerCredent})}-fn connect_uri(uri: &str) -> Result<Docker> {+fn connect_uri_once(uri: &str) -> std::result::Result<Docker, bollard::errors::Error> {let v = bollard::API_DEFAULT_VERSION;- let r = if uri.starts_with("unix://") || uri.starts_with("npipe://") || uri.starts_with('/') {+ if uri.starts_with("unix://") || uri.starts_with("npipe://") || uri.starts_with('/') {Docker::connect_with_socket(uri, 120, v)- } else if uri.starts_with("tcp://") || uri.starts_with("http://") {- Docker::connect_with_http(uri, 120, v)} else {+ Docker::connect_with_http(uri, 120, v)+ }+}++async fn connect_uri(uri: &str) -> Result<Docker> {+ if !(uri.starts_with("unix://")+ || uri.starts_with("npipe://")+ || uri.starts_with('/')+ || uri.starts_with("tcp://")+ || uri.starts_with("http://"))+ {return Err(VmmError::invalid(format!("unsupported engine endpoint '{uri}'")));- };- r.map_err(engine_err)+ }+ // Docker Desktop's pipe has one listening instance at a time: a client+ // that opens it in the same instant as another gets ERROR_PIPE_BUSY, which+ // bollard reports as "Socket not found" (CUA-1523). The pipe is there:+ // ask again a moment later.+ let mut tries = 0;+ loop {+ match connect_uri_once(uri) {+ Err(bollard::errors::Error::SocketNotFoundError(_))+ if cfg!(windows) && uri.starts_with("npipe://") && tries < 40 =>+ {+ tries += 1;+ tokio::time::sleep(std::time::Duration::from_millis(50)).await;+ }+ r => return r.map_err(engine_err),+ }+ }}#[async_trait]diff --git a/samples/openkoalabot-example-tauri/src-tauri/Cargo.lock b/samples/openkoalabot-example-tauri/src-tauri/Cargo.lockindex d6eea4abaf..ec562e52e8 100644--- a/samples/openkoalabot-example-tauri/src-tauri/Cargo.lock+++ b/samples/openkoalabot-example-tauri/src-tauri/Cargo.lock@@ -1492,6 +1492,7 @@ dependencies = ["async-trait","base64 0.22.1","core-foundation 0.10.1",+ "cua-home","cua-telemetry","hex","keyring",