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(cua-driver): harden consented existing-profile attachment (#3211)
Francesco Bonacci3f791b2cfec2
diff --git a/.github/workflows/e2e-rust-standalone-browsers.yml b/.github/workflows/e2e-rust-standalone-browsers.ymlindex 22e78f5f67..4ea0f11fee 100644--- a/.github/workflows/e2e-rust-standalone-browsers.yml+++ b/.github/workflows/e2e-rust-standalone-browsers.yml@@ -79,6 +79,16 @@ jobs:libxdo-dev libwebkit2gtk-4.1-dev libayatana-appindicator3-dev \librsvg2-dev ffmpeggoogle-chrome --version+ chrome_payload="$(readlink -f "$(command -v google-chrome)")"+ if [[ "$chrome_payload" != /opt/google/chrome/google-chrome ]]; then+ echo "Hosted Chrome did not resolve to the supported system package payload: $chrome_payload" >&2+ exit 1+ fi+ # Pid-free isolated launch accepts only a root-owned installation+ # whose complete path is not group- or world-writable. Normalize the+ # disposable hosted image to that same production trust contract.+ sudo chown root:root /opt /opt/google /opt/google/chrome "$chrome_payload"+ sudo chmod go-w /opt /opt/google /opt/google/chrome "$chrome_payload"- name: Build source driver on Windowsif: runner.os == 'Windows'shell: pwshdiff --git a/docs/content/docs/how-to-guides/driver/drive-a-web-page.mdx b/docs/content/docs/how-to-guides/driver/drive-a-web-page.mdxindex c42d6df99d..15499d2411 100644--- a/docs/content/docs/how-to-guides/driver/drive-a-web-page.mdx+++ b/docs/content/docs/how-to-guides/driver/drive-a-web-page.mdx@@ -28,9 +28,12 @@ binding.</Callout>First use `list_apps` and `list_windows` as usual, then call-`get_browser_state` with the selected native `(pid, window_id)`. If that browser-already exposes an owned loopback DevTools endpoint, the driver binds it without-changing the browser.+`get_browser_state` with the selected native `(pid, window_id)`. Driver-owned+profiles and supported embedded applications can bind through an exact owned+endpoint. A standalone Chrome or Edge profile still requires explicit+existing-profile approval, even when the browser already exposes a loopback+DevTools endpoint. In that case, `get_browser_state` returns+`browser_consent_required` with `next_action: browser_prepare`.Do not pass remote-debugging flags or a user-data directory through`launch_app`. Cua Driver rejects those flags because they could expose a@@ -142,6 +145,12 @@ browser_prepare({})```+On Chrome 144 and later, the approved preparation flow can attach through the+running profile's agent auto-connect endpoint. It does not restart Chrome, so+the profile keeps its current tabs, extensions, cookies, and sign-in state.+The endpoint proves which browser owns the connection; it does not replace the+existing-profile authorization.+> **Warning:** Unrestricted mode has no runtime Cua approval prompts and makes> no prompt-injection safety claim. Prefer `isolated_new`, or a bounded> existing-profile manifest when authentication is required. Use unrestricteddiff --git a/docs/content/docs/reference/cua-driver/browser-profile-attachment.mdx b/docs/content/docs/reference/cua-driver/browser-profile-attachment.mdxindex 9e96c6c92f..cef7b77dd2 100644--- a/docs/content/docs/reference/cua-driver/browser-profile-attachment.mdx+++ b/docs/content/docs/reference/cua-driver/browser-profile-attachment.mdx@@ -94,6 +94,41 @@ or the setup page's sole bounded pixel checkbox when web AX became unavailable,was proven off during cleanup. A false value means cleanup could not prove thestate; callers must not infer that remote debugging is disabled.+## Chrome 144+ auto-connect++Chrome 144 and later can publish an agent auto-connect endpoint for its running+profile after remote debugging is enabled. Cua Driver reads the endpoint from+that browser process's `DevToolsActivePort` file, proves that the live loopback+listener belongs to the approved process, and connects without restarting the+browser. The profile keeps its current tabs, extensions, cookies, and sign-in+state. See Chrome's+[agent auto-connect guide](https://developer.chrome.com/docs/devtools/agents/use-cases/auto-connect).++Endpoint discovery is provenance rather than authorization. A+`DevToolsActivePort` file, custom user-data path, or process-owned socket never+grants access to a standalone profile. The caller must complete+`browser_prepare` for the exact PID, window, and session first.++After binding, `get_browser_state` reports the non-sensitive connection class:++| Field | Existing-profile value | Meaning |+| ----------------------- | ---------------------------- | -------------------------------------------------------------- |+| `endpoint_transport` | `dev_tools_active_port` | Chrome published the endpoint through its auto-connect bridge. |+| `endpoint_access_class` | `existing_profile_approved` | A live existing-profile grant authorizes this connection. |++The result never exposes the port, WebSocket path, or profile path. Cua Driver+also rejects CDP commands that add persistent scripts, intercept requests, or+override browser identity on this connection.++Ending the Cua session revokes its in-memory grant and closes its socket. It+does not close Chrome or disable Chrome's remote-debugging preference. Disable+that setting in Chrome when the profile should stop accepting local DevTools+connections.++This attachment route does not promise fewer CAPTCHAs or bypass site checks.+Sites can still use network reputation, account history, browser state, and+interaction patterns.+## Grant lifetimeThe grant is scoped to the runtime instance, public session, transport session,@@ -177,8 +212,10 @@ The setup adapters currently recognize the products' English accessibilitylabels. Other UI locales fail closed without toggling an unrecognized control.Safari, Firefox, Brave, Vivaldi, Opera, Arc, and Electron do not have anexisting-profile setup descriptor and return a structured refusal. An already-available endpoint may still use the ordinary exact browser binding route when-the platform independently proves it.+available endpoint does not bypass existing-profile authorization for a+standalone consumer browser. Driver-owned profiles and supported embedded+applications can still use their ordinary exact binding routes when the+platform independently proves the endpoint.See [Drive a web page](/how-to-guides/driver/drive-a-web-page) for the taskworkflow and [Browser targeting and background delivery](/concepts/browser-targeting-and-background-delivery)diff --git a/libs/cua-driver/docs/browser-existing-profile-attachment-plan.md b/libs/cua-driver/docs/browser-existing-profile-attachment-plan.mdindex 56b6561913..6b35309723 100644--- a/libs/cua-driver/docs/browser-existing-profile-attachment-plan.md+++ b/libs/cua-driver/docs/browser-existing-profile-attachment-plan.md@@ -9,6 +9,13 @@- **Scope:** First-class, user-approved attachment to an existing Chromium profile, followed by bounded autonomous reconnection- **Delivery:** Draft PR [#2261](https://github.com/trycua/cua/pull/2261) on `codex/browser-existing-profile-reconnect-plan`; canonical replay is complete and the PR remains draft for review+The implementation now treats endpoint transport and profile-access authority+as separate proofs. Standalone consumer browsers require a live+existing-profile grant even when the OS proves that the browser owns a+loopback DevTools listener. Grant-owned connections also use a fixed CDP+method policy. Chrome 144+ `DevToolsActivePort` discovery is an internal+transport for the same public `existing_profile` strategy.+## Implementation outcome- Chrome and Edge use exact AX setup and consent adapters on macOS and exactdiff --git a/libs/cua-driver/docs/browser-tool-implementation-plan.md b/libs/cua-driver/docs/browser-tool-implementation-plan.mdindex 3e89fb4694..02ba4e3bfb 100644--- a/libs/cua-driver/docs/browser-tool-implementation-plan.md+++ b/libs/cua-driver/docs/browser-tool-implementation-plan.md@@ -7,6 +7,9 @@- **Implementation branch:** `codex/browser-tool-v1` (local only)- **Companion audit:** [Agentic Web Browsing with Cua Driver](agentic-web-browsing-audit.md)- **Architecture verdict:** Accept with major changes+- **Current authority rule:** Endpoint ownership identifies the browser+ process. A standalone consumer profile also requires an existing-profile+ grant before any endpoint discovery or connection.The accepted roadmap now covers the five typed tools, strict endpoint ownership,session capabilities, exact-or-refused Chromium mutation, standalone Chromium@@ -29,7 +32,7 @@ start_sessionlist_appslist_windowsget_browser_state-browser_prepare # only when get_browser_state reports requires_setup+browser_prepare # when get_browser_state reports requires_setup or consent_requiredget_browser_statebrowser_navigate / browser_click / browser_typeget_browser_state # verifydiff --git a/libs/cua-driver/rust/Skills/cua-driver/BROWSER.md b/libs/cua-driver/rust/Skills/cua-driver/BROWSER.mdindex 47599485da..918e92794f 100644--- a/libs/cua-driver/rust/Skills/cua-driver/BROWSER.md+++ b/libs/cua-driver/rust/Skills/cua-driver/BROWSER.md@@ -95,11 +95,13 @@ geometry, a moved tab, process restart, endpoint-owner mismatch, or any otherambiguity must be re-bound or refused. Do not pick another window because itstitle looks close.-## 2. Prepare only when the bind requests setup+## 2. Prepare only when the bind requests approval or setup`get_browser_state` is strictly read-only. It never launches a browser,changes a profile, enables remote debugging, or accepts a consent prompt. If-it returns `browser_requires_setup`, choose one explicit preparation flow.+it returns `browser_requires_setup` or `browser_consent_required`, choose one+explicit preparation flow. A standalone consumer browser cannot bind through+a DevTools listener merely because the listener belongs to that process.### Driver-owned isolated profile@@ -176,12 +178,39 @@ transition on that same control. Unsupported appearance, scale, zoom,window-size, or toolbar geometry refuses without a click; the fallback does notauthorize generic pixel interaction.+Chrome 144 and later can expose its agent auto-connect bridge from the running+profile. After approval, Cua reads the exact port and browser WebSocket path+from that process's `DevToolsActivePort` file, cross-checks the loopback socket+owner, and connects without restarting Chrome. Cookies, extensions, tabs, and+other browser state remain in the original profile. A custom user-data path is+discovery evidence only and never grants profile access. See Chrome's+[agent auto-connect guide](https://developer.chrome.com/docs/devtools/agents/use-cases/auto-connect).++The bind result reports `endpoint_transport` and `endpoint_access_class`+without exposing a port, WebSocket path, or profile path. Existing-profile+sockets enforce a fixed CDP method policy. The policy permits the commands+used internally by typed browser tools and refuses caller-directed raw target access,+`Runtime.enable`, persistent page scripts, request interception, and browser+identity overrides.+The grant lives only in the runtime, is scoped and expiring, and is discardedwhen the runtime shuts down. A bounded reconnect can reuse it only while the sameprocess/profile proof remains valid. After preparation or reconnect, discardall previous target, tab, and ref values, list windows again when the pidchanged, and bind again.+Chrome's remote-debugging setting can remain enabled after the Cua session+ends or Chrome restarts. Session cleanup revokes the in-memory grant and closes+the Cua socket, but it leaves Chrome running and does not change browser+preferences. The user can disable the setting from Chrome's fixed+remote-debugging page.++On the attached path tested during development, `navigator.webdriver` remained+`false`. Treat that as an observation, since browser releases may change it.+Websites also use network reputation, account history, session behavior,+browser state, and interaction signals. Existing-profile attachment cannot+promise fewer CAPTCHAs or bypass a site's checks.+Never:- pass remote-debugging flags through `launch_app` for a personal profile;@@ -444,7 +473,9 @@ result from the current host, process, window, session, and tab.- `browser_consent_required`: restart standard mode with the trusted launchgrant, use a capability manifest that admits the exact resource while theselected profile remains independently binding, or let the embedding host- decide the attested request. Do not automate a generic approval dialog.+ decide the attested request. When detail contains+ `next_action: browser_prepare`, run that explicit operation for the exact pid+ and window. Do not automate a generic approval dialog.- `browser_binding_ambiguous` or heuristic binding: resolve the native-windowambiguity and bind again; do not mutate.- `browser_ref_stale`: snapshot again and use a new ref.diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/cdp_ws.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/cdp_ws.rsindex a4cd46055f..08580616fb 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/cdp_ws.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/cdp_ws.rs@@ -30,6 +30,56 @@ type WsStream = WebSocketStream<MaybeTlsStream<TcpStream>>;const CALL_TIMEOUT: Duration = Duration::from_secs(20);const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);+/// Connection-scoped command policy. Grant-owned personal-profile sockets+/// always use the reviewed set below; callers cannot opt out or relax it.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum CdpMethodPolicy {+ Unrestricted,+ ExistingProfile,+}++const EXISTING_PROFILE_METHODS: &[&str] = &[+ "Accessibility.getFullAXTree",+ "Browser.getWindowBounds",+ "Browser.getWindowForTarget",+ "Browser.setDownloadBehavior",+ "DOM.describeNode",+ "DOM.focus",+ "DOM.getBoxModel",+ "DOM.getDocument",+ "DOM.resolveNode",+ "DOM.scrollIntoViewIfNeeded",+ "DOM.setFileInputFiles",+ "DOMSnapshot.captureSnapshot",+ "Emulation.setFocusEmulationEnabled",+ "Input.dispatchKeyEvent",+ "Input.dispatchMouseEvent",+ "Input.insertText",+ "Page.bringToFront",+ "Page.captureScreenshot",+ "Page.enable",+ "Page.getFrameTree",+ "Page.getLayoutMetrics",+ "Page.handleJavaScriptDialog",+ "Page.navigate",+ "Runtime.callFunctionOn",+ "Runtime.evaluate",+ "Target.activateTarget",+ "Target.attachToTarget",+ "Target.detachFromTarget",+ "Target.getTargets",+ "Target.setAutoAttach",+];++impl CdpMethodPolicy {+ fn allows(self, method: &str) -> bool {+ match self {+ Self::Unrestricted => true,+ Self::ExistingProfile => EXISTING_PROFILE_METHODS.binary_search(&method).is_ok(),+ }+ }+}+/// Validate that `url` is a plain-`ws` loopback WebSocket URL./// Anything else — `wss`, remote hosts, hostnames that merely *resolve*/// to loopback — is rejected; the endpoint contract is a literal@@ -192,6 +242,7 @@ pub struct CdpConnection {writer: Mutex<SplitSink<WsStream, Message>>,demux: Arc<Demux>,next_id: AtomicU64,+ existing_profile_policy: AtomicBool,reader: tokio::task::JoinHandle<()>,}@@ -223,10 +274,25 @@ impl CdpConnection {writer: Mutex::new(write),demux,next_id: AtomicU64::new(1),+ existing_profile_policy: AtomicBool::new(false),reader,})}+ pub fn method_policy(&self) -> CdpMethodPolicy {+ if self.existing_profile_policy.load(Ordering::SeqCst) {+ CdpMethodPolicy::ExistingProfile+ } else {+ CdpMethodPolicy::Unrestricted+ }+ }++ /// Monotonic restriction: once a socket is claimed for a personal+ /// profile it can never return to the unrestricted command surface.+ pub fn restrict_to_existing_profile(&self) {+ self.existing_profile_policy.store(true, Ordering::SeqCst);+ }+/// Whether the reader observed the socket close. A closed connection/// never recovers; the pool redials.pub fn is_closed(&self) -> bool {@@ -290,6 +356,12 @@ impl CdpConnection {method: &str,params: Value,) -> anyhow::Result<Value> {+ let policy = self.method_policy();+ if !policy.allows(method) {+ anyhow::bail!(+ "existing-profile CDP policy refused method {method}; the reviewed personal-profile command set cannot be bypassed"+ );+ }if self.is_closed() {anyhow::bail!("CDP socket closed before {method}");}@@ -421,6 +493,7 @@ impl CdpPool {Some(_) => anyhow::bail!("the approved browser socket closed before it was claimed"),None => Arc::new(CdpConnection::connect(ws_url).await?),};+ conn.restrict_to_existing_profile();conns.insert(ws_url.to_owned(),PoolEntry {@@ -481,6 +554,7 @@ impl CdpPool {// hold the pool mutex across that wait: grant revocation must remain// able to remove the old generation when consent is refused.let conn = Arc::new(CdpConnection::connect(ws_url).await?);+ conn.restrict_to_existing_profile();let mut conns = self.conns.lock().await;if let Some(entry) = conns.get(ws_url) {if entry@@ -620,6 +694,11 @@ mod tests {let initial = pool.get(&url).await.unwrap();let claimed = pool.claim_existing(&url, 1).await.unwrap();assert!(Arc::ptr_eq(&initial, &claimed), "claim must not redial");+ assert_eq!(+ claimed.method_policy(),+ CdpMethodPolicy::ExistingProfile,+ "claiming a personal-profile socket must restrict it in place"+ );assert!(pool.get(&url).await.is_err(), "legacy access must refuse");assert!(pool.get_existing(&url, 2).await.is_err());let reused = pool.get_existing(&url, 1).await.unwrap();@@ -631,6 +710,45 @@ mod tests {);}+ #[tokio::test]+ async fn existing_profile_policy_rejects_fingerprint_and_interception_methods() {+ let seen = StdArc::new(StdMutex::new(Vec::<String>::new()));+ let server_seen = seen.clone();+ let server = MockCdpServer::start(StdArc::new(move |call| {+ server_seen.lock().unwrap().push(call.method.clone());+ MockReply::ok(json!({}))+ }))+ .await;+ let conn = CdpConnection::connect(&server.ws_url()).await.unwrap();+ conn.restrict_to_existing_profile();++ for method in [+ "Runtime.enable",+ "Target.setDiscoverTargets",+ "Page.addScriptToEvaluateOnNewDocument",+ "Network.enable",+ "Fetch.enable",+ "Emulation.setUserAgentOverride",+ "Emulation.setDeviceMetricsOverride",+ "Emulation.setTimezoneOverride",+ ] {+ let error = conn.call(None, method, json!({})).await.unwrap_err();+ assert!(+ error.to_string().contains("policy refused"),+ "{method}: {error}"+ );+ }+ assert!(+ seen.lock().unwrap().is_empty(),+ "refused methods must not reach the browser socket"+ );++ conn.call(None, "Target.getTargets", json!({}))+ .await+ .expect("reviewed method remains available");+ assert_eq!(&*seen.lock().unwrap(), &["Target.getTargets"]);+ }+#[tokio::test]async fn dropping_a_pool_releases_its_claim_marker() {let server = MockCdpServer::start(StdArc::new(|_| MockReply::ok(json!({})))).await;diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/engine.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/engine.rsindex 2b599b5a68..93a08d35b9 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/engine.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/engine.rs@@ -57,8 +57,8 @@ use super::store::{SnapshotRecord, TabRecord, TargetRecord,};use super::types::{- BindingQuality, BrowserClassification, BrowserEngineFamily, NativeWindowInfo, OwnedEndpoint,- Rect,+ BindingQuality, BrowserClassification, BrowserEngineFamily, BrowserProcessRole,+ EndpointAccessClass, NativeWindowInfo, OwnedEndpoint, Rect,};/// Bounds tolerance (device pixels) for native ↔ CDP window correlation.@@ -172,6 +172,39 @@ pub(super) fn unsupported_engine_refusal(}))}+fn endpoint_access_class(+ has_existing_profile_grant: bool,+ driver_owned: bool,+ process_role: BrowserProcessRole,+) -> Result<EndpointAccessClass, BrowserRefusal> {+ if has_existing_profile_grant {+ return Ok(EndpointAccessClass::ExistingProfileApproved);+ }+ if driver_owned {+ return Ok(EndpointAccessClass::DriverOwned);+ }+ match process_role {+ BrowserProcessRole::EmbeddedApplication => Ok(EndpointAccessClass::EmbeddedApplication),+ BrowserProcessRole::StandaloneConsumer => Err(refuse(+ BrowserRefusalCode::BrowserConsentRequired,+ "this standalone browser profile requires explicit existing-profile approval before Cua can inspect its DevTools endpoint",+ )+ .with_detail(json!({+ "reason": "consumer_profile_endpoint_requires_grant",+ "supported_strategies": ["existing_profile"],+ "next_action": "browser_prepare",+ }))),+ BrowserProcessRole::Helper => Err(refuse(+ BrowserRefusalCode::BrowserWrongTargetRefused,+ "the requested pid is a browser renderer, GPU, or utility helper; select the exact top-level browser process instead",+ )),+ BrowserProcessRole::Unknown => Err(refuse(+ BrowserRefusalCode::BrowserRouteUnavailable,+ "the browser process role is ambiguous, so endpoint access cannot be authorized",+ )),+ }+}+/// Everything revalidation proves before a mutation proceeds. The/// `record`/`tab` evidence rides along for future callers even though/// the v1 tools only need the attached connection.@@ -879,11 +912,7 @@ impl BrowserEngine {return self.connect(&record.ws_url).await;}let (conn, grant) = self- .connect_existing_profile(- session,- record.grant_transport_session.as_deref(),- record.pid,- )+ .connect_existing_profile(session, record.transport_session.as_deref(), record.pid).await?;if grant.generation != record.generation {return Err(refuse(@@ -1129,11 +1158,17 @@ impl BrowserEngine {return Err(unsupported_engine_refusal(&class, "bind_native_window"));}- let native = self.native_window_checked(pid, window_id).await?;- let fingerprint = self.platform.process_fingerprint(pid).await?;let mut grant = self.existing_profile_grant(session, transport_session, pid).await?;+ let driver_owned = self.is_driver_owned_pid_for_session(session, pid)+ || transport_session+ .is_some_and(|owner| self.is_driver_owned_pid_for_session(owner, pid));+ let access_class =+ endpoint_access_class(grant.is_some(), driver_owned, class.process_role)?;++ let native = self.native_window_checked(pid, window_id).await?;+ let fingerprint = self.platform.process_fingerprint(pid).await?;let endpoint = if let Some(live_grant) = &grant {self.existing_profile_endpoint(pid, &live_grant.endpoint_ws_url).await?@@ -1240,8 +1275,13 @@ impl BrowserEngine {window_id,ws_url: endpoint.ws_url.clone(),endpoint_owner_pid: endpoint.ownership.owner_pid,+ endpoint_transport: endpoint.transport,+ endpoint_access_class: access_class,generation: grant.as_ref().map_or(0, |grant| grant.generation),- grant_transport_session: grant.as_ref().map(|grant| grant.transport_session.clone()),+ transport_session: grant+ .as_ref()+ .map(|grant| grant.transport_session.clone())+ .or_else(|| transport_session.map(str::to_owned)),fingerprint,native_title: native.title.clone(),native_bounds: native.bounds,@@ -1316,11 +1356,7 @@ impl BrowserEngine {}if record.generation > 0 {let grant = self- .existing_profile_grant(- session,- record.grant_transport_session.as_deref(),- record.pid,- )+ .existing_profile_grant(session, record.transport_session.as_deref(), record.pid).await?.ok_or_else(|| {refuse(@@ -1336,6 +1372,44 @@ impl BrowserEngine {}}+ match record.endpoint_access_class {+ EndpointAccessClass::DriverOwned => {+ let lifecycle_is_live = self.is_driver_owned_pid_for_session(session, record.pid)+ || record.transport_session.as_deref().is_some_and(|owner| {+ self.is_driver_owned_pid_for_session(owner, record.pid)+ });+ if !lifecycle_is_live {+ return Err(refuse(+ BrowserRefusalCode::BrowserConsentRequired,+ "the driver-owned browser lifecycle ended; prepare and bind it again",+ ));+ }+ }+ EndpointAccessClass::ExistingProfileApproved => {+ if record.generation == 0 {+ return Err(refuse(+ BrowserRefusalCode::BrowserBindingStale,+ "the approved existing-profile binding has no live connection generation",+ ));+ }+ }+ EndpointAccessClass::EmbeddedApplication => {+ let classification = self.platform.classify_browser(record.pid).await?;+ if classification.process_role != BrowserProcessRole::EmbeddedApplication {+ return Err(refuse(+ BrowserRefusalCode::BrowserBindingStale,+ "the process is no longer proven to be the approved embedded browser host",+ ));+ }+ }+ EndpointAccessClass::ExternalConsumerBrowser => {+ return Err(refuse(+ BrowserRefusalCode::BrowserConsentRequired,+ "a standalone consumer browser cannot use the generation-zero endpoint route",+ ));+ }+ }+// 1. Process fingerprint — pid reuse / restart detection.let fp_now = self.platform.process_fingerprint(record.pid).await?;if !record.fingerprint.matches(&fp_now) {@@ -1368,6 +1442,12 @@ impl BrowserEngine {get_browser_state",));}+ if endpoint.transport != record.endpoint_transport {+ return Err(refuse(+ BrowserRefusalCode::BrowserBindingStale,+ "the DevTools endpoint transport changed since binding; prepare and bind again",+ ));+ }// 4. CDP target still a page in the bound CDP window, with either// matching geometry or the same singleton cardinality proof.@@ -2727,6 +2807,42 @@ fn collect_interactive(mod tests {use super::*;+ #[test]+ fn endpoint_access_policy_requires_grants_for_standalone_consumers() {+ assert_eq!(+ endpoint_access_class(true, false, BrowserProcessRole::StandaloneConsumer).unwrap(),+ EndpointAccessClass::ExistingProfileApproved+ );+ assert_eq!(+ endpoint_access_class(false, true, BrowserProcessRole::StandaloneConsumer).unwrap(),+ EndpointAccessClass::DriverOwned+ );+ assert_eq!(+ endpoint_access_class(false, false, BrowserProcessRole::EmbeddedApplication).unwrap(),+ EndpointAccessClass::EmbeddedApplication+ );++ let consumer = endpoint_access_class(false, false, BrowserProcessRole::StandaloneConsumer)+ .unwrap_err();+ assert_eq!(consumer.code, BrowserRefusalCode::BrowserConsentRequired);+ assert_eq!(+ consumer.detail.unwrap()["reason"],+ "consumer_profile_endpoint_requires_grant"+ );+ assert_eq!(+ endpoint_access_class(false, false, BrowserProcessRole::Helper)+ .unwrap_err()+ .code,+ BrowserRefusalCode::BrowserWrongTargetRefused+ );+ assert_eq!(+ endpoint_access_class(false, false, BrowserProcessRole::Unknown)+ .unwrap_err()+ .code,+ BrowserRefusalCode::BrowserRouteUnavailable+ );+ }+#[test]fn viewport_point_maps_below_browser_chrome_in_live_native_bounds() {let point = viewport_point_to_screen(diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/prepare.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/prepare.rsindex 07702a0f97..adb4135293 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/prepare.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/prepare.rs@@ -559,6 +559,7 @@ async fn wait_for_spawned_endpoint(return Ok(OwnedEndpoint {ws_url: format!("ws://127.0.0.1:{port}{path}"),http_port: Some(port),+ transport: super::types::EndpointTransport::SpawnedExact,ownership: EndpointOwnershipProof {method: EndpointOwnershipMethod::SpawnedByDriver,owner_pid: i64::from(child.id()),@@ -606,6 +607,7 @@ async fn attest_spawned_endpoint(return Ok(OwnedEndpoint {ws_url: live.ws_url,http_port: live.http_port,+ transport: super::types::EndpointTransport::SpawnedExact,ownership: EndpointOwnershipProof {method: EndpointOwnershipMethod::SpawnedByDriver,// The platform already proved the exact listener is indiff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/store.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/store.rsindex ebbb3accf6..68f2099f61 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/store.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/store.rs@@ -24,7 +24,9 @@ use uuid::Uuid;use super::refusal::{BrowserRefusal, BrowserRefusalCode};use super::semantic::SemanticDocument;-use super::types::{BindingQuality, ProcessFingerprint, Rect};+use super::types::{+ BindingQuality, EndpointAccessClass, EndpointTransport, ProcessFingerprint, Rect,+};/// Browser action kinds proven for one semantic page ref.#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]@@ -210,11 +212,15 @@ pub struct TargetRecord {pub window_id: u64,pub ws_url: String,pub endpoint_owner_pid: i64,+ pub endpoint_transport: EndpointTransport,+ pub endpoint_access_class: EndpointAccessClass,/// CDP connection generation that minted this capability. Zero denotes/// the legacy/non-grant route.pub generation: u64,- /// Internal transport owner for a grant-backed existing-profile route.- pub grant_transport_session: Option<String>,+ /// Internal transport owner that proved an existing-profile grant or a+ /// driver-owned browser lifecycle. The public session remains the target+ /// namespace and is checked independently.+ pub transport_session: Option<String>,pub fingerprint: ProcessFingerprint,pub native_title: String,pub native_bounds: Rect,@@ -468,8 +474,10 @@ mod tests {window_id: 7,ws_url: "ws://127.0.0.1:9222/devtools/browser/x".into(),endpoint_owner_pid: 42,+ endpoint_transport: EndpointTransport::LegacyJsonVersion,+ endpoint_access_class: EndpointAccessClass::EmbeddedApplication,generation: 0,- grant_transport_session: None,+ transport_session: None,fingerprint: ProcessFingerprint {pid: 42,start_time: Some(1),diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/tools.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/tools.rsindex a5da89a19a..f16fb1793c 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/tools.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/tools.rs@@ -560,6 +560,8 @@ impl Tool for GetBrowserStateTool {"target_id": target_id,"binding_quality": quality,"binding_route": binding_route,+ "endpoint_transport": record.endpoint_transport,+ "endpoint_access_class": record.endpoint_access_class,"mutation_allowed": record.quality == BindingQuality::Exact,"native_title": record.native_title,"tabs": tabs,@@ -2504,6 +2506,7 @@ mod tests {product_kind: BrowserProduct::GoogleChrome,product: Some("MockChrome".into()),channel: Some("stable".into()),+ process_role: crate::browser::types::BrowserProcessRole::StandaloneConsumer,supports_cdp: true,},3 => BrowserClassification {@@ -2512,6 +2515,7 @@ mod tests {product_kind: BrowserProduct::Safari,product: Some("MockSafari".into()),channel: None,+ process_role: crate::browser::types::BrowserProcessRole::StandaloneConsumer,supports_cdp: false,},4 => BrowserClassification {@@ -2520,6 +2524,7 @@ mod tests {product_kind: BrowserProduct::Firefox,product: Some("MockFirefox".into()),channel: None,+ process_role: crate::browser::types::BrowserProcessRole::StandaloneConsumer,supports_cdp: false,},_ => BrowserClassification {@@ -2528,6 +2533,7 @@ mod tests {product_kind: BrowserProduct::Other,product: None,channel: None,+ process_role: crate::browser::types::BrowserProcessRole::Unknown,supports_cdp: false,},})@@ -2825,14 +2831,19 @@ mod tests {}#[tokio::test]- async fn missing_endpoint_refuses_requires_setup_without_preparing() {+ async fn standalone_consumer_refuses_existing_profile_approval_without_preparing() {let tool = GetBrowserStateTool::new(engine());let result = tool.invoke(json!({ "pid": 1, "window_id": 7, "_session_id": "run-1" })).await;let s = structured(&result);assert_eq!(s["status"], "refused");- assert_eq!(s["refusal"]["code"], "browser_requires_setup");+ assert_eq!(s["refusal"]["code"], "browser_consent_required");+ assert_eq!(+ s["refusal"]["detail"]["reason"],+ "consumer_profile_endpoint_requires_grant"+ );+ assert_eq!(s["refusal"]["detail"]["next_action"], "browser_prepare");}#[tokio::test]@@ -3003,8 +3014,11 @@ mod tests {window_id: 7,ws_url: "ws://127.0.0.1:9222/devtools/browser/x".into(),endpoint_owner_pid: 1,+ endpoint_transport: crate::browser::types::EndpointTransport::LegacyJsonVersion,+ endpoint_access_class:+ crate::browser::types::EndpointAccessClass::EmbeddedApplication,generation: 0,- grant_transport_session: None,+ transport_session: None,fingerprint: ProcessFingerprint {pid: 1,start_time: Some(1),@@ -3061,8 +3075,11 @@ mod tests {window_id: 7,ws_url: "ws://127.0.0.1:9222/devtools/browser/x".into(),endpoint_owner_pid: 1,+ endpoint_transport: crate::browser::types::EndpointTransport::LegacyJsonVersion,+ endpoint_access_class:+ crate::browser::types::EndpointAccessClass::EmbeddedApplication,generation: 0,- grant_transport_session: None,+ transport_session: None,fingerprint: ProcessFingerprint {pid: 1,start_time: Some(999),@@ -3104,8 +3121,11 @@ mod tests {window_id: 7,ws_url: "ws://127.0.0.1:9222/devtools/browser/x".into(),endpoint_owner_pid: 1,+ endpoint_transport: crate::browser::types::EndpointTransport::LegacyJsonVersion,+ endpoint_access_class:+ crate::browser::types::EndpointAccessClass::EmbeddedApplication,generation: 0,- grant_transport_session: None,+ transport_session: None,fingerprint: ProcessFingerprint {pid: 1,start_time: Some(1),diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/types.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/types.rsindex 08929029ba..51d2256664 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/types.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/types.rs@@ -85,10 +85,25 @@ pub struct BrowserClassification {pub product: Option<String>,/// Release channel when known, e.g. "stable", "canary".pub channel: Option<String>,+ /// Process role proven by the platform adapter. Product identity alone is+ /// not enough to distinguish a personal standalone browser from an+ /// embedded Chromium host or a renderer/utility helper.+ #[serde(default)]+ pub process_role: BrowserProcessRole,/// Whether this browser can expose a DevTools (CDP) endpoint at all.pub supports_cdp: bool,}+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]+#[serde(rename_all = "snake_case")]+pub enum BrowserProcessRole {+ StandaloneConsumer,+ EmbeddedApplication,+ Helper,+ #[default]+ Unknown,+}+/// How a platform adapter proved that a native window belongs to a pid.#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]@@ -144,6 +159,28 @@ pub enum EndpointOwnershipMethod {PlatformAttested,}+/// How the platform located an endpoint. This is provenance, not authority:+/// a path or socket owned by Chrome still requires an existing-profile grant.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]+#[serde(rename_all = "snake_case")]+pub enum EndpointTransport {+ SpawnedExact,+ DevToolsActivePort,+ #[default]+ LegacyJsonVersion,+ EmbeddedDescendant,+}++/// Core's authorization verdict for a bound endpoint.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum EndpointAccessClass {+ DriverOwned,+ ExistingProfileApproved,+ EmbeddedApplication,+ ExternalConsumerBrowser,+}+/// Explicit proof of DevTools-endpoint ownership.#[derive(Debug, Clone, Serialize, Deserialize)]pub struct EndpointOwnershipProof {@@ -171,6 +208,8 @@ pub struct OwnedEndpoint {/// `ws://127.0.0.1:9222/devtools/browser/<uuid>`.pub ws_url: String,pub http_port: Option<u16>,+ #[serde(default)]+ pub transport: EndpointTransport,pub ownership: EndpointOwnershipProof,}@@ -308,4 +347,18 @@ mod tests {43);}++ #[test]+ fn endpoint_transport_and_access_class_have_stable_public_names() {+ assert_eq!(+ serde_json::to_value(EndpointTransport::DevToolsActivePort)+ .expect("serialize endpoint transport"),+ "dev_tools_active_port"+ );+ assert_eq!(+ serde_json::to_value(EndpointAccessClass::ExistingProfileApproved)+ .expect("serialize endpoint access class"),+ "existing_profile_approved"+ );+ }}diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/v2_tests.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/v2_tests.rsindex 032d2b6cbd..2b82930cdc 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/v2_tests.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/v2_tests.rs@@ -32,9 +32,9 @@ use super::tools::{BrowserTypeTool, GetBrowserStateTool,};use super::types::{- BrowserClassification, BrowserEngineFamily, BrowserProduct, EndpointOwnershipMethod,- EndpointOwnershipProof, NativeOwnershipMethod, NativeOwnershipProof, NativeWindowInfo,- OwnedEndpoint, ProcessFingerprint, Rect,+ BrowserClassification, BrowserEngineFamily, BrowserProcessRole, BrowserProduct,+ EndpointOwnershipMethod, EndpointOwnershipProof, EndpointTransport, NativeOwnershipMethod,+ NativeOwnershipProof, NativeWindowInfo, OwnedEndpoint, ProcessFingerprint, Rect,};// ── Scripted Chromium fixture ────────────────────────────────────────────────@@ -663,6 +663,8 @@ struct FixturePlatform {ws_url: String,trusted_input_limited: bool,managed_endpoint_visible: bool,+ process_role: BrowserProcessRole,+ managed_discovery_invoked: Arc<AtomicBool>,existing_endpoint_visible: Arc<AtomicBool>,setup_invoked: Arc<AtomicBool>,setup_aborted: Arc<AtomicBool>,@@ -683,6 +685,9 @@ impl BrowserPlatform for FixturePlatform {product_kind: BrowserProduct::GoogleChrome,product: Some("MockChrome".into()),channel: Some("stable".into()),+ // The mock endpoint is an explicit in-process harness, not a+ // personal standalone browser profile.+ process_role: self.process_role,supports_cdp: true,})}@@ -718,6 +723,7 @@ impl BrowserPlatform for FixturePlatform {&self,pid: i64,) -> Result<Option<OwnedEndpoint>, BrowserRefusal> {+ self.managed_discovery_invoked.store(true, Ordering::SeqCst);if !self.managed_endpoint_visible {return Ok(None);}@@ -734,6 +740,7 @@ impl BrowserPlatform for FixturePlatform {Ok(Some(OwnedEndpoint {ws_url: self.ws_url.clone(),http_port: None,+ transport: EndpointTransport::LegacyJsonVersion,ownership: EndpointOwnershipProof {method: EndpointOwnershipMethod::ListeningSocketPid,owner_pid: pid,@@ -754,6 +761,7 @@ impl BrowserPlatform for FixturePlatform {Ok(Some(OwnedEndpoint {ws_url: self.ws_url.clone(),http_port: None,+ transport: EndpointTransport::LegacyJsonVersion,ownership: EndpointOwnershipProof {method: EndpointOwnershipMethod::ListeningSocketPid,owner_pid: pid,@@ -779,6 +787,7 @@ impl BrowserPlatform for FixturePlatform {endpoint: Some(OwnedEndpoint {ws_url: self.ws_url.clone(),http_port: None,+ transport: EndpointTransport::DevToolsActivePort,ownership: EndpointOwnershipProof {method: EndpointOwnershipMethod::ListeningSocketPid,owner_pid: 1,@@ -869,6 +878,8 @@ async fn fixture_with_platform(ws_url: server.ws_url(),trusted_input_limited,managed_endpoint_visible: true,+ process_role: BrowserProcessRole::EmbeddedApplication,+ managed_discovery_invoked: Arc::new(AtomicBool::new(false)),existing_endpoint_visible: Arc::new(AtomicBool::new(true)),setup_invoked: setup_invoked.clone(),setup_aborted: Arc::new(AtomicBool::new(false)),@@ -920,6 +931,8 @@ async fn protected_existing_profile_fixture() -> (Fixture, Arc<FixtureProtectedPws_url: server.ws_url(),trusted_input_limited: false,managed_endpoint_visible: false,+ process_role: BrowserProcessRole::StandaloneConsumer,+ managed_discovery_invoked: Arc::new(AtomicBool::new(false)),existing_endpoint_visible: Arc::new(AtomicBool::new(true)),setup_invoked: setup_invoked.clone(),setup_aborted: Arc::new(AtomicBool::new(false)),@@ -947,6 +960,8 @@ async fn existing_profile_setup_fixture() -> (Fixture, Arc<AtomicBool>) {ws_url: server.ws_url(),trusted_input_limited: false,managed_endpoint_visible: false,+ process_role: BrowserProcessRole::StandaloneConsumer,+ managed_discovery_invoked: Arc::new(AtomicBool::new(false)),existing_endpoint_visible: Arc::new(AtomicBool::new(false)),setup_invoked: setup_invoked.clone(),setup_aborted: Arc::new(AtomicBool::new(false)),@@ -989,6 +1004,48 @@ async fn bind(f: &Fixture) -> (String, String) {(target_id, tab_id)}+#[tokio::test]+async fn standalone_consumer_bind_without_grant_refuses_before_endpoint_discovery() {+ let state = Arc::new(StdMutex::new(FixtureState::default()));+ let server = MockCdpServer::start(fixture_handler(state)).await;+ let managed_discovery_invoked = Arc::new(AtomicBool::new(false));+ let setup_invoked = Arc::new(AtomicBool::new(false));+ let engine = BrowserEngine::new(Arc::new(FixturePlatform {+ ws_url: server.ws_url(),+ trusted_input_limited: false,+ managed_endpoint_visible: true,+ process_role: BrowserProcessRole::StandaloneConsumer,+ managed_discovery_invoked: managed_discovery_invoked.clone(),+ existing_endpoint_visible: Arc::new(AtomicBool::new(true)),+ setup_invoked: setup_invoked.clone(),+ setup_aborted: Arc::new(AtomicBool::new(false)),+ stall_consent: false,+ }));++ let result = GetBrowserStateTool::new(engine)+ .invoke(json!({ "pid": 1, "window_id": 7, "session": SESSION }))+ .await;+ let refusal = structured(&result);+ assert_eq!(refusal["status"], "refused");+ assert_eq!(refusal["refusal"]["code"], "browser_consent_required");+ assert_eq!(+ refusal["refusal"]["detail"]["reason"],+ "consumer_profile_endpoint_requires_grant"+ );+ assert_eq!(+ refusal["refusal"]["detail"]["next_action"],+ "browser_prepare"+ );+ assert!(+ !managed_discovery_invoked.load(Ordering::SeqCst),+ "read-only bind must not inspect a consent-gated endpoint"+ );+ assert!(+ !setup_invoked.load(Ordering::SeqCst),+ "read-only bind must never invoke browser setup UI"+ );+}+#[tokio::test]async fn approved_existing_profile_attach_claims_then_binds_one_generation() {// Match Chrome's per-instance toggle: the endpoint is discoverable only@@ -1024,6 +1081,103 @@ async fn approved_existing_profile_attach_claims_then_binds_one_generation() {crate::session::fire_session_end("transport-v2-attach");}+#[tokio::test]+async fn approved_existing_profile_tools_stay_within_the_reviewed_cdp_surface() {+ const TRANSPORT: &str = "transport-v2-method-policy";+ let (f, _) = protected_existing_profile_fixture().await;+ let prepare = BrowserPrepareTool::new(f.engine.clone())+ .invoke(json!({+ "pid": 1,+ "window_id": 7,+ "session": SESSION,+ "_transport_session_id": TRANSPORT,+ "strategy": { "kind": "existing_profile" }+ }))+ .await;+ assert_eq!(+ structured(&prepare)["status"],+ "ok",+ "{}",+ structured(&prepare)+ );++ let state = GetBrowserStateTool::new(f.engine.clone())+ .invoke(json!({+ "pid": 1,+ "window_id": 7,+ "session": SESSION,+ "_transport_session_id": TRANSPORT+ }))+ .await;+ let bound = structured(&state);+ assert_eq!(bound["status"], "ok", "{bound}");+ let target = bound["target_id"].as_str().unwrap().to_owned();+ let tab = bound["tabs"][0]["tab_id"].as_str().unwrap().to_owned();++ let snap = snapshot(&f, &target, &tab).await;+ let button = ref_of(&snap, "main", "main-btn");+ let input = ref_of(&snap, "main", "Shadow Input");+ let clicked = BrowserClickTool::new(f.engine.clone())+ .invoke(json!({+ "target_id": target,+ "tab_id": tab,+ "ref": button,+ "input_route": "dom_event",+ "session": SESSION+ }))+ .await;+ assert_eq!(+ structured(&clicked)["status"],+ "ok",+ "{}",+ structured(&clicked)+ );+ let typed = BrowserTypeTool::new(f.engine.clone())+ .invoke(json!({+ "target_id": target,+ "tab_id": tab,+ "ref": input,+ "text": "policy-check",+ "session": SESSION+ }))+ .await;+ assert_eq!(structured(&typed)["status"], "ok", "{}", structured(&typed));+ let navigated = BrowserNavigateTool::new(f.engine.clone())+ .invoke(json!({+ "target_id": target,+ "tab_id": tab,+ "url": "https://fixture.test/policy-check",+ "session": SESSION+ }))+ .await;+ assert_eq!(+ structured(&navigated)["status"],+ "ok",+ "{}",+ structured(&navigated)+ );++ let forbidden = [+ "Runtime.enable",+ "Target.setDiscoverTargets",+ "Page.addScriptToEvaluateOnNewDocument",+ "Network.enable",+ "Fetch.enable",+ "Emulation.setUserAgentOverride",+ "Emulation.setDeviceMetricsOverride",+ "Emulation.setTimezoneOverride",+ ];+ let calls = f.state.lock().unwrap().calls.clone();+ for method in forbidden {+ assert!(+ calls.iter().all(|(_, observed, _)| observed != method),+ "existing-profile operation emitted forbidden CDP method {method}: {calls:?}"+ );+ }++ crate::session::fire_session_end(TRANSPORT);+}+#[tokio::test]async fn protected_provider_accepts_exact_attach_and_session_end_revokes_the_grant() {const PROTECTED_SESSION: &str = "protected-provider-v2";@@ -1106,6 +1260,8 @@ async fn refused_consent_cancels_stalled_claim_before_revoking_grant() {ws_url: format!("ws://{address}/devtools/browser"),trusted_input_limited: false,managed_endpoint_visible: false,+ process_role: BrowserProcessRole::StandaloneConsumer,+ managed_discovery_invoked: Arc::new(AtomicBool::new(false)),existing_endpoint_visible: Arc::new(AtomicBool::new(false)),setup_invoked: Arc::new(AtomicBool::new(false)),setup_aborted: Arc::new(AtomicBool::new(false)),@@ -1148,6 +1304,8 @@ async fn cancelled_prepare_aborts_the_exact_pending_setup() {ws_url: format!("ws://{address}/devtools/browser"),trusted_input_limited: false,managed_endpoint_visible: false,+ process_role: BrowserProcessRole::StandaloneConsumer,+ managed_discovery_invoked: Arc::new(AtomicBool::new(false)),existing_endpoint_visible: Arc::new(AtomicBool::new(false)),setup_invoked: Arc::new(AtomicBool::new(false)),setup_aborted: setup_aborted.clone(),diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/standalone_browser_behavior_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/standalone_browser_behavior_test.rsindex a47940c8cf..ea5f2b8baf 100644--- a/libs/cua-driver/rust/crates/cua-driver/tests/standalone_browser_behavior_test.rs+++ b/libs/cua-driver/rust/crates/cua-driver/tests/standalone_browser_behavior_test.rs@@ -1393,9 +1393,20 @@ fn bind(fixture: &mut BrowserFixture, session: &str) -> (String, String, ToolResassert!(!started.is_error(), "start_session failed: {}", started.raw);let prepared = fixture.driver.call("browser_prepare",- serde_json::json!({ "pid": fixture.pid as i64, "session": session }),+ serde_json::json!({+ "pid": fixture.pid as i64,+ "window_id": fixture.window_id,+ "session": session,+ "strategy": {"kind": "existing_profile"},+ }),+ );+ assert_eq!(prepared.structured()["status"], "ok", "{}", prepared.raw);+ assert_eq!(+ prepared.structured()["action"],+ "attached_existing_profile",+ "{}",+ prepared.raw);- assert_eq!(prepared.structured()["prepared"], true, "{}", prepared.raw);// A newly mapped Wayland toplevel can briefly appear with a protocol-local// id before the compositor publishes its stable pid/geometry identity.// Model the real client preamble: re-list windows and bind only the id the@@ -4471,10 +4482,18 @@ fn run_two_window_collision(spec: &BrowserSpec) {"browser_prepare",serde_json::json!({"pid": fixture.pid as i64,+ "window_id": fixture.window_id,"session": session,+ "strategy": {"kind": "existing_profile"},}),);- assert_eq!(prepared.structured()["prepared"], true, "{}", prepared.raw);+ assert_eq!(prepared.structured()["status"], "ok", "{}", prepared.raw);+ assert_eq!(+ prepared.structured()["action"],+ "attached_existing_profile",+ "{}",+ prepared.raw+ );let refused = fixture.driver.call("get_browser_state",serde_json::json!({diff --git a/libs/cua-driver/rust/crates/platform-linux/src/browser_platform.rs b/libs/cua-driver/rust/crates/platform-linux/src/browser_platform.rsindex 67a7f84d5c..0816d173d8 100644--- a/libs/cua-driver/rust/crates/platform-linux/src/browser_platform.rs+++ b/libs/cua-driver/rust/crates/platform-linux/src/browser_platform.rs@@ -14,9 +14,9 @@ use cua_driver_core::browser::platform::{};use cua_driver_core::browser::refusal::{BrowserRefusal, BrowserRefusalCode};use cua_driver_core::browser::types::{- BrowserClassification, BrowserEngineFamily, BrowserProduct, EndpointOwnershipMethod,- EndpointOwnershipProof, NativeOwnershipMethod, NativeOwnershipProof, NativeWindowInfo,- OwnedEndpoint, ProcessFingerprint, Rect,+ BrowserClassification, BrowserEngineFamily, BrowserProcessRole, BrowserProduct,+ EndpointOwnershipMethod, EndpointOwnershipProof, EndpointTransport, NativeOwnershipMethod,+ NativeOwnershipProof, NativeWindowInfo, OwnedEndpoint, ProcessFingerprint, Rect,};use tokio::io::{AsyncReadExt, AsyncWriteExt};@@ -110,6 +110,34 @@ fn trusted_root_owned_installation(executable: &std::path::Path) -> bool {.is_ok_and(|metadata| metadata.is_file() && metadata.mode() & 0o111 != 0)}+fn process_role_for_pid(pid: i64, product: BrowserProduct) -> BrowserProcessRole {+ let helper = std::fs::read(format!("/proc/{pid}/cmdline"))+ .ok()+ .is_some_and(|bytes| {+ bytes.split(|byte| *byte == 0).any(|arg| {+ arg.starts_with(b"--type=") && arg.get(7..).is_some_and(|kind| !kind.is_empty())+ })+ });+ if helper {+ BrowserProcessRole::Helper+ } else if product == BrowserProduct::Electron {+ BrowserProcessRole::EmbeddedApplication+ } else if matches!(+ product,+ BrowserProduct::GoogleChrome+ | BrowserProduct::Chromium+ | BrowserProduct::MicrosoftEdge+ | BrowserProduct::Brave+ | BrowserProduct::Vivaldi+ | BrowserProduct::Opera+ | BrowserProduct::Arc+ ) {+ BrowserProcessRole::StandaloneConsumer+ } else {+ BrowserProcessRole::Unknown+ }+}+fn loopback_websocket_port(url: &str) -> Option<u16> {["ws://127.0.0.1:", "ws://localhost:", "ws://[::1]:"].iter()@@ -335,6 +363,7 @@ fn active_port_endpoint(pid: i64) -> Result<Option<OwnedEndpoint>, BrowserRefusaOk(Some(OwnedEndpoint {ws_url: format!("ws://127.0.0.1:{port}{path}"),http_port: Some(port),+ transport: EndpointTransport::DevToolsActivePort,ownership: EndpointOwnershipProof {method: EndpointOwnershipMethod::DevtoolsActivePortsFile,owner_pid: pid,@@ -486,6 +515,7 @@ impl BrowserPlatform for LinuxBrowserPlatform {product_kind,product: Some(process.name),channel: None,+ process_role: process_role_for_pid(pid, product_kind),supports_cdp: chromium,})}@@ -692,9 +722,6 @@ impl BrowserPlatform for LinuxBrowserPlatform {&self,pid: i64,) -> Result<Option<OwnedEndpoint>, BrowserRefusal> {- if let Some(endpoint) = active_port_endpoint(pid)? {- return Ok(Some(endpoint));- }let ports = tokio::task::spawn_blocking(move || loopback_ports_for_pid(pid)).await.map_err(|error| {@@ -708,6 +735,7 @@ impl BrowserPlatform for LinuxBrowserPlatform {return Ok(Some(OwnedEndpoint {ws_url,http_port: Some(port),+ transport: EndpointTransport::LegacyJsonVersion,ownership: EndpointOwnershipProof {method: EndpointOwnershipMethod::ListeningSocketPid,owner_pid: pid,@@ -746,6 +774,7 @@ impl BrowserPlatform for LinuxBrowserPlatform {[(port, ws_url)] => Ok(Some(OwnedEndpoint {ws_url: ws_url.clone(),http_port: Some(*port),+ transport: EndpointTransport::LegacyJsonVersion,ownership: EndpointOwnershipProof {method: EndpointOwnershipMethod::ListeningSocketPid,owner_pid: pid,@@ -771,6 +800,15 @@ impl BrowserPlatform for LinuxBrowserPlatform {"the approved existing-profile endpoint is not loopback-only",));};+ if let Some(endpoint) = active_port_endpoint(pid)? {+ if endpoint.ws_url != expected_ws_url {+ return Err(refusal(+ BrowserRefusalCode::BrowserEndpointOwnerMismatch,+ "the browser's exact DevTools endpoint changed after approval",+ ));+ }+ return Ok(Some(endpoint));+ }let ports = tokio::task::spawn_blocking(move || loopback_ports_for_pid(pid)).await.map_err(|error| {@@ -785,6 +823,7 @@ impl BrowserPlatform for LinuxBrowserPlatform {Ok(Some(OwnedEndpoint {ws_url: expected_ws_url.to_owned(),http_port: Some(port),+ transport: EndpointTransport::LegacyJsonVersion,ownership: EndpointOwnershipProof {method: EndpointOwnershipMethod::ListeningSocketPid,owner_pid: pid,@@ -910,6 +949,7 @@ impl BrowserPlatform for LinuxBrowserPlatform {break Ok(OwnedEndpoint {ws_url: ws_url.clone(),http_port: Some(*port),+ transport: EndpointTransport::LegacyJsonVersion,ownership: EndpointOwnershipProof {method: EndpointOwnershipMethod::ListeningSocketPid,owner_pid: request.pid,diff --git a/libs/cua-driver/rust/crates/platform-macos/src/browser/platform.rs b/libs/cua-driver/rust/crates/platform-macos/src/browser/platform.rsindex 79c8aa10f4..3d86ea7e8c 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/browser/platform.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/browser/platform.rs@@ -16,9 +16,9 @@ use cua_driver_core::browser::platform::{};use cua_driver_core::browser::refusal::{BrowserRefusal, BrowserRefusalCode};use cua_driver_core::browser::types::{- BrowserClassification, BrowserEngineFamily, BrowserProduct, EndpointOwnershipMethod,- EndpointOwnershipProof, NativeOwnershipMethod, NativeOwnershipProof, NativeWindowInfo,- OwnedEndpoint, ProcessFingerprint, Rect,+ BrowserClassification, BrowserEngineFamily, BrowserProcessRole, BrowserProduct,+ EndpointOwnershipMethod, EndpointOwnershipProof, EndpointTransport, NativeOwnershipMethod,+ NativeOwnershipProof, NativeWindowInfo, OwnedEndpoint, ProcessFingerprint, Rect,};use tokio::io::{AsyncReadExt, AsyncWriteExt};@@ -251,26 +251,129 @@ fn parse_devtools_active_port(text: &str) -> Option<(u16, &str)> {.then_some((port, path))}-async fn process_uses_custom_user_data_dir(pid: i64) -> Result<bool, BrowserRefusal> {- let output = tokio::process::Command::new("ps")- .args(["-p", &pid.to_string(), "-o", "command="])- .stdin(Stdio::null())- .stderr(Stdio::null())- .output()- .await- .map_err(|error| {- refusal(- BrowserRefusalCode::BrowserRouteUnavailable,- format!("could not inspect browser arguments for pid {pid}: {error}"),- )- })?;- if !output.status.success() {+fn process_arguments(pid: i64) -> Result<Vec<Vec<u8>>, BrowserRefusal> {+ let pid = libc::pid_t::try_from(pid).map_err(|_| {+ refusal(+ BrowserRefusalCode::BrowserWrongTargetRefused,+ "browser pid is outside the macOS process-id range",+ )+ })?;+ let mut mib = [libc::CTL_KERN, libc::KERN_PROCARGS2, pid];+ let mut size = 0usize;+ let size_result = unsafe {+ libc::sysctl(+ mib.as_mut_ptr(),+ mib.len() as u32,+ std::ptr::null_mut(),+ &mut size,+ std::ptr::null_mut(),+ 0,+ )+ };+ if size_result != 0 || size < std::mem::size_of::<libc::c_int>() {return Err(refusal(BrowserRefusalCode::BrowserBindingStale,- format!("browser process {pid} is no longer available"),+ format!("browser process {pid} arguments are unavailable"),));}- Ok(String::from_utf8_lossy(&output.stdout).contains("--user-data-dir"))+ let mut bytes = vec![0u8; size];+ let read_result = unsafe {+ libc::sysctl(+ mib.as_mut_ptr(),+ mib.len() as u32,+ bytes.as_mut_ptr().cast(),+ &mut size,+ std::ptr::null_mut(),+ 0,+ )+ };+ if read_result != 0 {+ return Err(refusal(+ BrowserRefusalCode::BrowserBindingStale,+ format!("browser process {pid} arguments changed during inspection"),+ ));+ }+ bytes.truncate(size);+ let argc = libc::c_int::from_ne_bytes(+ bytes[..std::mem::size_of::<libc::c_int>()]+ .try_into()+ .expect("c_int byte width"),+ );+ if argc <= 0 {+ return Ok(Vec::new());+ }+ let mut cursor = std::mem::size_of::<libc::c_int>();+ while cursor < bytes.len() && bytes[cursor] != 0 {+ cursor += 1;+ }+ while cursor < bytes.len() && bytes[cursor] == 0 {+ cursor += 1;+ }+ let mut args = Vec::with_capacity(argc as usize);+ for _ in 0..argc {+ if cursor >= bytes.len() {+ break;+ }+ let end = bytes[cursor..]+ .iter()+ .position(|byte| *byte == 0)+ .map(|offset| cursor + offset)+ .unwrap_or(bytes.len());+ args.push(bytes[cursor..end].to_vec());+ cursor = end.saturating_add(1);+ }+ Ok(args)+}++fn user_data_dir_from_arguments(+ args: &[Vec<u8>],+ default: Option<PathBuf>,+) -> Result<Option<PathBuf>, BrowserRefusal> {+ use std::os::unix::ffi::OsStringExt;++ let mut directories = Vec::new();+ for (index, arg) in args.iter().enumerate() {+ if let Some(path) = arg.strip_prefix(b"--user-data-dir=") {+ if !path.is_empty() {+ directories.push(PathBuf::from(std::ffi::OsString::from_vec(path.to_vec())));+ }+ } else if arg == b"--user-data-dir" {+ if let Some(path) = args.get(index + 1).filter(|path| !path.is_empty()) {+ directories.push(PathBuf::from(std::ffi::OsString::from_vec(path.clone())));+ }+ }+ }+ directories.sort();+ directories.dedup();+ match directories.as_slice() {+ [] => Ok(default),+ [path] if path.is_absolute() => Ok(Some(path.clone())),+ [_] => Err(refusal(+ BrowserRefusalCode::BrowserRouteUnavailable,+ "the browser uses a relative --user-data-dir that cannot be attested without its launch working directory",+ )),+ _ => Err(refusal(+ BrowserRefusalCode::BrowserBindingAmbiguous,+ "browser process has multiple distinct --user-data-dir arguments",+ )),+ }+}++async fn user_data_dir_for_pid(+ pid: i64,+ product: BrowserProduct,+) -> Result<Option<PathBuf>, BrowserRefusal> {+ tokio::task::spawn_blocking(move || {+ let args = process_arguments(pid)?;+ user_data_dir_from_arguments(&args, default_user_data_dir(product))+ })+ .await+ .map_err(|error| {+ refusal(+ BrowserRefusalCode::BrowserRouteUnavailable,+ format!("browser argument inspection task failed: {error}"),+ )+ })?}fn exact_browser_surface_ids(@@ -373,13 +476,9 @@ async fn active_port_endpoint() -> Result<Option<OwnedEndpoint>, BrowserRefusal> {// The Chrome 144+ existing-profile bridge deliberately returns 404 for// legacy /json discovery. Its exact browser WebSocket path is instead- // published in the default profile's DevToolsActivePort file. Custom- // user-data dirs remain on the launch/HTTP discovery paths because this- // adapter cannot safely recover an arbitrary argv path from `ps` text.- if process_uses_custom_user_data_dir(pid).await? {- return Ok(None);- }- let Some(user_data_dir) = default_user_data_dir(product) else {+ // published in the exact user-data root's DevToolsActivePort file. argv+ // comes from KERN_PROCARGS2 rather than lossy `ps` text.+ let Some(user_data_dir) = user_data_dir_for_pid(pid, product).await? else {return Ok(None);};let text = match tokio::fs::read_to_string(user_data_dir.join("DevToolsActivePort")).await {@@ -404,6 +503,7 @@ async fn active_port_endpoint(Ok(Some(OwnedEndpoint {ws_url: format!("ws://127.0.0.1:{port}{path}"),http_port: Some(port),+ transport: EndpointTransport::DevToolsActivePort,ownership: EndpointOwnershipProof {method: EndpointOwnershipMethod::DevtoolsActivePortsFile,owner_pid: pid,@@ -580,6 +680,31 @@ impl BrowserPlatform for MacOsBrowserPlatform {let webkit = bundle_id == "com.apple.Safari" || name.eq_ignore_ascii_case("Safari");let gecko = is_firefox(name, bundle_id);let product_kind = browser_product(name, bundle_id);+ let helper = name.to_ascii_lowercase().contains("helper")+ || bundle_id.to_ascii_lowercase().contains(".helper")+ || process_arguments(pid).ok().is_some_and(|args| {+ args.iter().any(|arg| {+ arg.starts_with(b"--type=") && arg.get(7..).is_some_and(|kind| !kind.is_empty())+ })+ });+ let process_role = if helper {+ BrowserProcessRole::Helper+ } else if product_kind == BrowserProduct::Electron {+ BrowserProcessRole::EmbeddedApplication+ } else if matches!(+ product_kind,+ BrowserProduct::GoogleChrome+ | BrowserProduct::Chromium+ | BrowserProduct::MicrosoftEdge+ | BrowserProduct::Brave+ | BrowserProduct::Vivaldi+ | BrowserProduct::Opera+ | BrowserProduct::Arc+ ) {+ BrowserProcessRole::StandaloneConsumer+ } else {+ BrowserProcessRole::Unknown+ };Ok(BrowserClassification {is_browser: chromium || webkit || gecko,engine: if chromium {@@ -593,7 +718,18 @@ impl BrowserPlatform for MacOsBrowserPlatform {},product_kind,product: (!name.is_empty()).then(|| name.to_owned()),- channel: None,+ channel: (process_role == BrowserProcessRole::StandaloneConsumer).then(|| {+ if bundle_id.to_ascii_lowercase().contains("canary") {+ "canary".to_owned()+ } else if bundle_id.to_ascii_lowercase().contains("beta") {+ "beta".to_owned()+ } else if bundle_id.to_ascii_lowercase().contains("dev") {+ "dev".to_owned()+ } else {+ "stable".to_owned()+ }+ }),+ process_role,supports_cdp: chromium,})}@@ -675,6 +811,7 @@ impl BrowserPlatform for MacOsBrowserPlatform {return Ok(Some(OwnedEndpoint {ws_url,http_port: Some(port),+ transport: EndpointTransport::LegacyJsonVersion,ownership: EndpointOwnershipProof {method: EndpointOwnershipMethod::ListeningSocketPid,owner_pid: pid,@@ -707,6 +844,7 @@ impl BrowserPlatform for MacOsBrowserPlatform {return Ok(Some(OwnedEndpoint {ws_url,http_port: Some(port),+ transport: EndpointTransport::LegacyJsonVersion,ownership: EndpointOwnershipProof {method: EndpointOwnershipMethod::ListeningSocketPid,owner_pid: pid,@@ -755,6 +893,7 @@ impl BrowserPlatform for MacOsBrowserPlatform {Ok(Some(OwnedEndpoint {ws_url: expected_ws_url.to_owned(),http_port: Some(port),+ transport: EndpointTransport::LegacyJsonVersion,ownership: EndpointOwnershipProof {method: EndpointOwnershipMethod::ListeningSocketPid,owner_pid: pid,@@ -861,6 +1000,7 @@ impl BrowserPlatform for MacOsBrowserPlatform {break Ok(OwnedEndpoint {ws_url: ws_url.clone(),http_port: Some(*port),+ transport: EndpointTransport::LegacyJsonVersion,ownership: EndpointOwnershipProof {method: EndpointOwnershipMethod::ListeningSocketPid,owner_pid: request.pid,@@ -1213,6 +1353,39 @@ mod tests {);}+ #[test]+ fn user_data_dir_parser_preserves_exact_custom_argv_path() {+ let custom = std::env::temp_dir().join("cua browser profile with spaces");+ let arg = format!("--user-data-dir={}", custom.display()).into_bytes();+ assert_eq!(+ user_data_dir_from_arguments(&[b"/Applications/Chrome".to_vec(), arg], None)+ .expect("one absolute custom profile"),+ Some(custom)+ );+ }++ #[test]+ fn user_data_dir_parser_does_not_treat_a_path_as_authority() {+ let default = PathBuf::from("/tmp/default-browser-data");+ assert_eq!(+ user_data_dir_from_arguments(+ &[b"/Applications/Chrome".to_vec()],+ Some(default.clone())+ )+ .expect("default path"),+ Some(default)+ );+ assert!(user_data_dir_from_arguments(+ &[+ b"/Applications/Chrome".to_vec(),+ b"--user-data-dir=/tmp/one".to_vec(),+ b"--user-data-dir=/tmp/two".to_vec(),+ ],+ None,+ )+ .is_err());+ }+#[test]fn embedded_window_proof_ignores_untitled_window_server_helpers() {let mut helper = window(8, 42, "");diff --git a/libs/cua-driver/rust/crates/platform-windows/src/browser_platform.rs b/libs/cua-driver/rust/crates/platform-windows/src/browser_platform.rsindex 4831efc409..7dfc66881e 100644--- a/libs/cua-driver/rust/crates/platform-windows/src/browser_platform.rs+++ b/libs/cua-driver/rust/crates/platform-windows/src/browser_platform.rs@@ -16,9 +16,9 @@ use cua_driver_core::browser::platform::{};use cua_driver_core::browser::refusal::{BrowserRefusal, BrowserRefusalCode};use cua_driver_core::browser::types::{- BrowserClassification, BrowserEngineFamily, BrowserProduct, EndpointOwnershipMethod,- EndpointOwnershipProof, NativeOwnershipMethod, NativeOwnershipProof, NativeWindowInfo,- OwnedEndpoint, ProcessFingerprint, Rect,+ BrowserClassification, BrowserEngineFamily, BrowserProcessRole, BrowserProduct,+ EndpointOwnershipMethod, EndpointOwnershipProof, EndpointTransport, NativeOwnershipMethod,+ NativeOwnershipProof, NativeWindowInfo, OwnedEndpoint, ProcessFingerprint, Rect,};use tokio::io::{AsyncReadExt, AsyncWriteExt};use windows::core::PCWSTR;@@ -132,7 +132,8 @@ fn browser_product(name: &str) -> BrowserProduct {.next().unwrap_or(name).to_ascii_lowercase();- match executable.trim_end_matches(".exe") {+ let executable = executable.trim_end_matches(".exe");+ match executable {"chrome" => BrowserProduct::GoogleChrome,"chromium" => BrowserProduct::Chromium,"msedge" => BrowserProduct::MicrosoftEdge,@@ -142,6 +143,12 @@ fn browser_product(name: &str) -> BrowserProduct {"arc" => BrowserProduct::Arc,"electron" => BrowserProduct::Electron,"firefox" => BrowserProduct::Firefox,+ _ if executable+ .split(|ch: char| !ch.is_ascii_alphanumeric())+ .any(|token| token == "electron") =>+ {+ BrowserProduct::Electron+ }_ => BrowserProduct::Other,}}@@ -349,6 +356,223 @@ fn trusted_windows_installation_with_probe(false}+fn default_user_data_dir(product: BrowserProduct) -> Option<PathBuf> {+ let root = std::env::var_os("LOCALAPPDATA").map(PathBuf::from)?;+ let relative = match product {+ BrowserProduct::GoogleChrome => ["Google", "Chrome", "User Data"].as_slice(),+ BrowserProduct::MicrosoftEdge => ["Microsoft", "Edge", "User Data"].as_slice(),+ BrowserProduct::Chromium => ["Chromium", "User Data", ""].as_slice(),+ BrowserProduct::Brave => ["BraveSoftware", "Brave-Browser", "User Data"].as_slice(),+ BrowserProduct::Vivaldi => ["Vivaldi", "User Data", ""].as_slice(),+ _ => return None,+ };+ Some(+ relative+ .iter()+ .filter(|part| !part.is_empty())+ .fold(root, |path, part| path.join(part)),+ )+}++fn parse_windows_command_line(command_line: &str) -> Vec<String> {+ let chars = command_line.chars().collect::<Vec<_>>();+ let mut args = Vec::new();+ let mut index = 0;+ while index < chars.len() {+ while index < chars.len() && chars[index].is_whitespace() {+ index += 1;+ }+ if index == chars.len() {+ break;+ }+ let mut arg = String::new();+ let mut quoted = false;+ while index < chars.len() {+ if !quoted && chars[index].is_whitespace() {+ break;+ }+ let mut slashes = 0;+ while index < chars.len() && chars[index] == '\\' {+ slashes += 1;+ index += 1;+ }+ if index < chars.len() && chars[index] == '"' {+ arg.extend(std::iter::repeat_n('\\', slashes / 2));+ if slashes % 2 == 0 {+ quoted = !quoted;+ } else {+ arg.push('"');+ }+ index += 1;+ } else {+ arg.extend(std::iter::repeat_n('\\', slashes));+ if index < chars.len() && (quoted || !chars[index].is_whitespace()) {+ arg.push(chars[index]);+ index += 1;+ }+ }+ }+ args.push(arg);+ }+ args+}++fn is_windows_absolute_path(path: &std::path::Path) -> bool {+ let value = path.as_os_str().to_string_lossy();+ let bytes = value.as_bytes();+ (bytes.len() >= 3+ && bytes[0].is_ascii_alphabetic()+ && bytes[1] == b':'+ && matches!(bytes[2], b'\\' | b'/'))+ || value.starts_with(r"\\")+}++fn user_data_dir_from_command_line(+ command_line: &str,+ default: Option<PathBuf>,+) -> Result<Option<PathBuf>, BrowserRefusal> {+ let args = parse_windows_command_line(command_line);+ let mut directories = Vec::new();+ for (index, arg) in args.iter().enumerate() {+ if let Some(path) = arg.strip_prefix("--user-data-dir=") {+ if !path.is_empty() {+ directories.push(PathBuf::from(path));+ }+ } else if arg == "--user-data-dir" {+ if let Some(path) = args.get(index + 1).filter(|path| !path.is_empty()) {+ directories.push(PathBuf::from(path));+ }+ }+ }+ directories.sort();+ directories.dedup();+ match directories.as_slice() {+ [] => Ok(default),+ [path] if is_windows_absolute_path(path) => Ok(Some(path.clone())),+ [_] => Err(refusal(+ BrowserRefusalCode::BrowserRouteUnavailable,+ "the browser uses a relative --user-data-dir that cannot be attested without its launch working directory",+ )),+ _ => Err(refusal(+ BrowserRefusalCode::BrowserBindingAmbiguous,+ "browser process has multiple distinct --user-data-dir arguments",+ )),+ }+}++fn system_powershell_path() -> Result<PathBuf, BrowserRefusal> {+ let system = system_netstat_path()?+ .parent()+ .map(PathBuf::from)+ .ok_or_else(|| {+ refusal(+ BrowserRefusalCode::BrowserRouteUnavailable,+ "could not resolve the trusted Windows system directory",+ )+ })?;+ Ok(system.join("WindowsPowerShell\\v1.0\\powershell.exe"))+}++async fn browser_command_line(pid: u32) -> Result<String, BrowserRefusal> {+ let powershell = system_powershell_path()?;+ let script = format!(+ "$OutputEncoding=[Console]::OutputEncoding=[Text.UTF8Encoding]::new($false); (Get-CimInstance Win32_Process -Filter 'ProcessId = {pid}' -ErrorAction Stop).CommandLine"+ );+ let output = tokio::process::Command::new(powershell)+ .args([+ "-NoLogo",+ "-NoProfile",+ "-NonInteractive",+ "-Command",+ &script,+ ])+ .stdin(Stdio::null())+ .stderr(Stdio::null())+ .output()+ .await+ .map_err(|error| {+ refusal(+ BrowserRefusalCode::BrowserRouteUnavailable,+ format!("could not inspect browser arguments: {error}"),+ )+ })?;+ if !output.status.success() {+ return Err(refusal(+ BrowserRefusalCode::BrowserBindingStale,+ format!("browser process {pid} arguments are unavailable"),+ ));+ }+ let command_line = String::from_utf8_lossy(&output.stdout).trim().to_owned();+ if command_line.is_empty() {+ return Err(refusal(+ BrowserRefusalCode::BrowserBindingStale,+ format!("browser process {pid} has no command line"),+ ));+ }+ Ok(command_line)+}++fn parse_devtools_active_port(text: &str) -> Option<(u16, &str)> {+ let mut lines = text.lines().map(str::trim).filter(|line| !line.is_empty());+ let port = lines.next()?.parse::<u16>().ok()?;+ let path = lines.next()?;+ if lines.next().is_some() {+ return None;+ }+ let instance = path.strip_prefix("/devtools/browser/")?;+ (!instance.is_empty()+ && instance+ .bytes()+ .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-' || byte == b'_'))+ .then_some((port, path))+}++async fn active_port_endpoint(+ pid: u32,+ product: BrowserProduct,+) -> Result<Option<OwnedEndpoint>, BrowserRefusal> {+ let default = default_user_data_dir(product);+ let user_data_dir = match browser_command_line(pid).await {+ Ok(command_line) => user_data_dir_from_command_line(&command_line, default.clone())?,+ Err(_) => default,+ };+ let Some(user_data_dir) = user_data_dir else {+ return Ok(None);+ };+ let text = match tokio::fs::read_to_string(user_data_dir.join("DevToolsActivePort")).await {+ Ok(text) => text,+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),+ Err(error) => {+ return Err(refusal(+ BrowserRefusalCode::BrowserRouteUnavailable,+ format!("could not read the browser's DevToolsActivePort file: {error}"),+ ))+ }+ };+ let Some((port, path)) = parse_devtools_active_port(&text) else {+ return Err(refusal(+ BrowserRefusalCode::BrowserEndpointOwnerMismatch,+ "the browser's DevToolsActivePort file did not contain one exact browser endpoint",+ ));+ };+ if !loopback_ports_for_exact_pid(pid).await?.contains(&port) {+ return Ok(None);+ }+ Ok(Some(OwnedEndpoint {+ ws_url: format!("ws://127.0.0.1:{port}{path}"),+ http_port: Some(port),+ transport: EndpointTransport::DevToolsActivePort,+ ownership: EndpointOwnershipProof {+ method: EndpointOwnershipMethod::DevtoolsActivePortsFile,+ owner_pid: i64::from(pid),+ listener_pid: Some(i64::from(pid)),+ detail: Some(+ "exact OS-reported argv profile port file plus loopback listener owner".to_owned(),+ ),+ },+ }))+}+fn allows_embedded_descendant_endpoint(executable_path: &str) -> bool {let executable = executable_path.rsplit(['/', '\\'])@@ -943,10 +1167,12 @@ fn owned_endpoint_from_listener(ws_url: String,listener_pid: u32,context: &str,+ transport: EndpointTransport,) -> OwnedEndpoint {OwnedEndpoint {ws_url,http_port: Some(port),+ transport,ownership: EndpointOwnershipProof {method: EndpointOwnershipMethod::ListeningSocketPid,// The discovery route proved listener_pid under its documented@@ -966,6 +1192,7 @@ fn select_unique_owned_endpoint(root_pid: i64,discovered: Vec<(u16, String, u32)>,context: &str,+ transport: EndpointTransport,) -> Result<Option<OwnedEndpoint>, BrowserRefusal> {match discovered.as_slice() {[] => Ok(None),@@ -975,6 +1202,7 @@ fn select_unique_owned_endpoint(ws_url.clone(),*listener_pid,context,+ transport,))),_ => Err(refusal(BrowserRefusalCode::BrowserBindingAmbiguous,@@ -1005,6 +1233,21 @@ async fn loopback_port_is_owned_with_retry(.await}+fn legacy_setup_endpoint_is_stable(+ observation: &mut Option<(String, std::time::Instant)>,+ ws_url: &str,+ now: std::time::Instant,+ preference_window: Duration,+) -> bool {+ if let Some((observed_url, observed_at)) = observation.as_ref() {+ if observed_url == ws_url {+ return now.saturating_duration_since(*observed_at) >= preference_window;+ }+ }+ *observation = Some((ws_url.to_owned(), now));+ false+}+async fn retry_port_ownership<F, Fut>(attempts: usize,delay: Duration,@@ -1147,6 +1390,34 @@ impl BrowserPlatform for WindowsBrowserPlatform {let chromium = is_chromium(&name);let gecko = is_firefox(&name);let product_kind = browser_product(&name);+ let command_line = if chromium {+ browser_command_line(pid_u32).await.ok()+ } else {+ None+ };+ let helper = command_line.as_deref().is_some_and(|line| {+ parse_windows_command_line(line)+ .iter()+ .any(|arg| arg.starts_with("--type=") && arg.len() > "--type=".len())+ });+ let process_role = if helper {+ BrowserProcessRole::Helper+ } else if product_kind == BrowserProduct::Electron {+ BrowserProcessRole::EmbeddedApplication+ } else if matches!(+ product_kind,+ BrowserProduct::GoogleChrome+ | BrowserProduct::Chromium+ | BrowserProduct::MicrosoftEdge+ | BrowserProduct::Brave+ | BrowserProduct::Vivaldi+ | BrowserProduct::Opera+ | BrowserProduct::Arc+ ) {+ BrowserProcessRole::StandaloneConsumer+ } else {+ BrowserProcessRole::Unknown+ };Ok(BrowserClassification {is_browser: chromium || gecko,engine: if chromium {@@ -1158,7 +1429,23 @@ impl BrowserPlatform for WindowsBrowserPlatform {},product_kind,product: Some(name),- channel: None,+ channel: if process_role == BrowserProcessRole::StandaloneConsumer {+ command_line.as_deref().map(|line| {+ let lower = line.to_ascii_lowercase();+ if lower.contains("chrome sxs") || lower.contains("canary") {+ "canary".to_owned()+ } else if lower.contains(" beta") || lower.contains("\\beta\\") {+ "beta".to_owned()+ } else if lower.contains(" dev") || lower.contains("\\dev\\") {+ "dev".to_owned()+ } else {+ "stable".to_owned()+ }+ })+ } else {+ None+ },+ process_role,supports_cdp: chromium,})}@@ -1246,6 +1533,7 @@ impl BrowserPlatform for WindowsBrowserPlatform {pid,browser_endpoints_for_pid(pid_u32).await?,"listener owned by the exact approved browser pid or its classified embedded webview tree",+ EndpointTransport::LegacyJsonVersion,)}@@ -1264,6 +1552,7 @@ impl BrowserPlatform for WindowsBrowserPlatform {pid,spawned_browser_endpoints_for_pid(pid_u32, expected_ws_url).await?,"exact private-profile endpoint owned by the driver-spawned browser tree",+ EndpointTransport::SpawnedExact,)}@@ -1277,10 +1566,15 @@ impl BrowserPlatform for WindowsBrowserPlatform {format!("pid {pid} is outside the Windows process-id range"),)})?;+ let classification = self.classify_browser(pid).await?;+ if let Some(endpoint) = active_port_endpoint(pid_u32, classification.product_kind).await? {+ return Ok(Some(endpoint));+ }select_unique_owned_endpoint(pid,exact_browser_endpoints_for_pid(pid_u32).await?,"Windows exact browser-pid listener plus /json/version",+ EndpointTransport::LegacyJsonVersion,)}@@ -1301,6 +1595,16 @@ impl BrowserPlatform for WindowsBrowserPlatform {"the approved existing-profile endpoint is not loopback-only",));};+ let classification = self.classify_browser(pid).await?;+ if let Some(endpoint) = active_port_endpoint(pid_u32, classification.product_kind).await? {+ if endpoint.ws_url != expected_ws_url {+ return Err(refusal(+ BrowserRefusalCode::BrowserEndpointOwnerMismatch,+ "the browser's exact DevTools endpoint changed after approval",+ ));+ }+ return Ok(Some(endpoint));+ }// Setup may approve the exact PID-owned port before Chromium publishes// its final browser WebSocket id. Reprove that stable port ownership// here; the connection layer still uses the approved WebSocket path.@@ -1310,6 +1614,7 @@ impl BrowserPlatform for WindowsBrowserPlatform {Ok(Some(OwnedEndpoint {ws_url: expected_ws_url.to_owned(),http_port: Some(port),+ transport: EndpointTransport::LegacyJsonVersion,ownership: EndpointOwnershipProof {method: EndpointOwnershipMethod::ListeningSocketPid,owner_pid: pid,@@ -1362,7 +1667,19 @@ impl BrowserPlatform for WindowsBrowserPlatform {let injected_global_input = handle.injected_global_input;let deadline = std::time::Instant::now() + Duration::from_secs(6);+ // Chrome and Edge can expose /json/version a few milliseconds before+ // their profile-scoped DevToolsActivePort file becomes visible on+ // Windows. Prefer the stronger file + exact-pid listener proof during+ // that bounded publication window. Accepting the HTTP result+ // immediately can mint a grant for a transient browser WebSocket id+ // that the just-published file then (correctly) disproves.+ let mut legacy_endpoint_observation: Option<(String, std::time::Instant)> = None;let endpoint_result = loop {+ match active_port_endpoint(pid_u32, request.browser).await {+ Ok(Some(endpoint)) => break Ok(endpoint),+ Ok(None) => {}+ Err(error) => break Err(error),+ }let ports = match loopback_ports_for_exact_pid(pid_u32).await {Ok(ports) => ports,Err(error) => break Err(error),@@ -1401,9 +1718,29 @@ impl BrowserPlatform for WindowsBrowserPlatform {}match endpoints.as_slice() {[(port, ws_url, detail)] => {+ let now = std::time::Instant::now();+ if !legacy_setup_endpoint_is_stable(+ &mut legacy_endpoint_observation,+ ws_url,+ now,+ Duration::from_secs(1),+ ) {+ if now >= deadline {+ break Err(refusal(+ BrowserRefusalCode::BrowserEndpointOwnerMismatch,+ format!(+ "{} did not keep one exact browser endpoint stable after the approved setup action",+ descriptor.product_name+ ),+ ));+ }+ tokio::time::sleep(Duration::from_millis(100)).await;+ continue;+ }break Ok(OwnedEndpoint {ws_url: ws_url.clone(),http_port: Some(*port),+ transport: EndpointTransport::LegacyJsonVersion,ownership: EndpointOwnershipProof {method: EndpointOwnershipMethod::ListeningSocketPid,owner_pid: request.pid,@@ -1624,6 +1961,11 @@ mod tests {root,|path, directory| !(directory && path.ends_with(r"Google\Chrome")),));+ assert!(!trusted_windows_installation_with_probe(+ &executable,+ root,+ |path, directory| !(directory && path == root),+ ));assert!(!trusted_windows_installation_with_probe(&std::path::PathBuf::from(r"D:\UserControlled\chrome.exe"),root,@@ -1698,6 +2040,10 @@ mod tests {diagnostics.iter().any(|(_, reason)| reason.is_some()),"a refused installation must identify an explicitly granted write right: {diagnostics:?}");+ assert!(+ std::env::var_os("CUA_TEST_REQUIRE_PROTECTED_WINDOWS_BROWSER").is_none(),+ "the standalone-browser runner must provide a vendor-signed browser tree protected from its current token: {diagnostics:?}"+ );eprintln!("installed browser correctly refused for this write-capable runner token: {diagnostics:?}");@@ -1774,6 +2120,7 @@ mod tests {"ws://127.0.0.1:9222/devtools/browser/id".to_owned(),43,"verified process tree",+ EndpointTransport::EmbeddedDescendant,);assert_eq!(endpoint.ownership.owner_pid, 42);@@ -1788,11 +2135,14 @@ mod tests {#[test]fn owned_endpoint_selection_requires_exactly_one_lifetime_matched_listener() {- assert!(- select_unique_owned_endpoint(42, Vec::new(), "verified process tree")- .expect("empty discovery is not an error")- .is_none()- );+ assert!(select_unique_owned_endpoint(+ 42,+ Vec::new(),+ "verified process tree",+ EndpointTransport::LegacyJsonVersion,+ )+ .expect("empty discovery is not an error")+ .is_none());let selected = select_unique_owned_endpoint(42,@@ -1802,6 +2152,7 @@ mod tests {43,)],"verified process tree",+ EndpointTransport::LegacyJsonVersion,).expect("one lifetime-matched listener").expect("selected endpoint");@@ -1823,6 +2174,7 @@ mod tests {),],"verified process tree",+ EndpointTransport::LegacyJsonVersion,).expect_err("multiple lifetime-matched listeners must be refused");assert_eq!(ambiguous.code, BrowserRefusalCode::BrowserBindingAmbiguous);@@ -1842,6 +2194,10 @@ mod tests {#[test]fn classifier_covers_embedded_and_standalone_chromium() {assert!(is_chromium("CuaTestHarness.Electron.exe"));+ assert_eq!(+ browser_product("CuaTestHarness.Electron.exe"),+ BrowserProduct::Electron+ );assert!(is_chromium("msedge.exe"));assert!(!is_chromium("firefox.exe"));assert!(!is_chromium("Operator.exe"));@@ -2028,6 +2384,83 @@ mod tests {assert_eq!(literal_loopback_websocket_port("ws://127.0.0.1:9222"), None);}+ #[test]+ fn windows_command_line_parser_preserves_quoted_profile_paths() {+ let args = parse_windows_command_line(+ r#""C:\Program Files\Google\Chrome\Application\chrome.exe" --flag "--user-data-dir=C:\Profiles\Personal Browser""#,+ );+ assert_eq!(+ args,+ vec![+ r#"C:\Program Files\Google\Chrome\Application\chrome.exe"#,+ "--flag",+ r#"--user-data-dir=C:\Profiles\Personal Browser"#,+ ]+ );+ assert_eq!(+ user_data_dir_from_command_line(+ r#"chrome.exe "--user-data-dir=C:\Profiles\Personal Browser""#,+ None,+ )+ .expect("one absolute custom profile"),+ Some(PathBuf::from(r#"C:\Profiles\Personal Browser"#))+ );+ }++ #[test]+ fn active_port_parser_rejects_non_browser_and_ambiguous_paths() {+ assert_eq!(+ parse_devtools_active_port("9222\n/devtools/browser/exact-id\n"),+ Some((9222, "/devtools/browser/exact-id"))+ );+ assert_eq!(+ parse_devtools_active_port("9222\n/devtools/page/id\n"),+ None+ );+ assert_eq!(+ parse_devtools_active_port("9222\n/devtools/browser/id\nextra\n"),+ None+ );+ }++ #[test]+ fn legacy_setup_endpoint_must_remain_exact_during_active_port_preference_window() {+ let start = std::time::Instant::now();+ let window = Duration::from_secs(1);+ let mut observation = None;++ assert!(!legacy_setup_endpoint_is_stable(+ &mut observation,+ "ws://127.0.0.1:9222/devtools/browser/first",+ start,+ window,+ ));+ assert!(!legacy_setup_endpoint_is_stable(+ &mut observation,+ "ws://127.0.0.1:9222/devtools/browser/first",+ start + Duration::from_millis(999),+ window,+ ));+ assert!(legacy_setup_endpoint_is_stable(+ &mut observation,+ "ws://127.0.0.1:9222/devtools/browser/first",+ start + window,+ window,+ ));+ assert!(!legacy_setup_endpoint_is_stable(+ &mut observation,+ "ws://127.0.0.1:9222/devtools/browser/second",+ start + window,+ window,+ ));+ assert!(legacy_setup_endpoint_is_stable(+ &mut observation,+ "ws://127.0.0.1:9222/devtools/browser/second",+ start + window + window,+ window,+ ));+ }+#[tokio::test]async fn endpoint_discovery_retries_only_empty_socket_snapshots() {let calls = Arc::new(AtomicUsize::new(0));