Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

142 KB
Raw Blame
// SPDX-License-Identifier: MIT
// Copyright (c) 2026 Cua AI, Inc.

//! Windows identity and endpoint evidence for the first-class browser tools.

use std::collections::HashMap;
use std::ffi::c_void;
use std::future::Future;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use std::path::PathBuf;
use std::process::Stdio;
use std::sync::{Arc, Mutex};
use std::time::Duration;

use async_trait::async_trait;
use cua_driver_core::browser::platform::{
    BrowserConsentOutcome, BrowserConsentRequest, BrowserPlatform, BrowserVisualAction,
    BrowserVisualActionKind, ExistingProfileSetupOutcome, ExistingProfileSetupRequest,
    IsolatedBrowserProcess, PrepareAction, PrepareOutcome, PrepareRequest,
};
use cua_driver_core::browser::refusal::{BrowserRefusal, BrowserRefusalCode};
use cua_driver_core::browser::types::{
    BrowserClassification, BrowserEngineFamily, BrowserProcessRole, BrowserProduct,
    EndpointOwnershipMethod, EndpointOwnershipProof, EndpointTransport, NativeOwnershipMethod,
    NativeOwnershipProof, NativeWindowInfo, OwnedEndpoint, ProcessFingerprint, Rect,
};
use cua_driver_core::browser::{
    existing_profile_setup_descriptor, fetch_json_version_ws_url, is_firefox,
    parse_devtools_active_port, BrowserCursorTracker,
};

use crate::browser_installation_path::{
    plain_windows_path, resolve_installation, InstallationEntry, InstallationFs,
    InstallationResolution,
};
use crate::browser_isolated_selection::{
    decide_isolated_browser, InstallationWriteAccess, IsolatedBrowserDecision,
    IsolatedCandidateFacts, NO_PROTECTED_BROWSER_MESSAGE,
};
use crate::browser_standard_user::{
    browser_launch_context, require_profile_writable, spawn_with_token, with_impersonation,
    BrowserLaunchContext,
};
use windows::core::PCWSTR;
use windows::Win32::Foundation::{
    CloseHandle, BOOL, ERROR_INSUFFICIENT_BUFFER, E_ACCESSDENIED, FILETIME, HWND, LPARAM, NO_ERROR,
    RECT,
};
use windows::Win32::Graphics::Gdi::{
    EnumDisplayMonitors, GetMonitorInfoW, MonitorFromWindow, HDC, HMONITOR, MONITORINFO,
    MONITOR_DEFAULTTONEAREST,
};
use windows::Win32::NetworkManagement::IpHelper::{
    GetExtendedTcpTable, MIB_TCP6ROW_OWNER_PID, MIB_TCP6TABLE_OWNER_PID, MIB_TCPROW_OWNER_PID,
    MIB_TCPTABLE_OWNER_PID, MIB_TCP_STATE_LISTEN, TCP_TABLE_OWNER_PID_LISTENER,
};
use windows::Win32::Networking::WinSock::{AF_INET, AF_INET6};
use windows::Win32::Storage::FileSystem::{
    CreateFileW, DELETE, FILE_ADD_FILE, FILE_ADD_SUBDIRECTORY, FILE_APPEND_DATA, FILE_DELETE_CHILD,
    FILE_FLAGS_AND_ATTRIBUTES, FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT,
    FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE, FILE_WRITE_ATTRIBUTES, FILE_WRITE_DATA,
    FILE_WRITE_EA, OPEN_EXISTING, WRITE_DAC, WRITE_OWNER,
};
use windows::Win32::System::Com::CoTaskMemFree;
use windows::Win32::System::SystemInformation::GetSystemDirectoryW;
use windows::Win32::System::Threading::{
    GetProcessTimes, OpenProcess, QueryFullProcessImageNameW, PROCESS_NAME_FORMAT,
    PROCESS_QUERY_LIMITED_INFORMATION,
};
use windows::Win32::UI::HiDpi::{GetDpiForMonitor, GetDpiForWindow, MDT_EFFECTIVE_DPI};
use windows::Win32::UI::Shell::{
    FOLDERID_ProgramFiles, FOLDERID_ProgramFilesX86, SHGetKnownFolderPath, KF_FLAG_DEFAULT,
};
use windows::Win32::UI::WindowsAndMessaging::{GetAncestor, GetWindowRect, GA_ROOT};

#[derive(Clone)]
pub struct WindowsBrowserPlatform {
    cursor_registry: Arc<cursor_overlay::CursorRegistry>,
    browser_cursors: Arc<Mutex<BrowserCursorTracker>>,
}

impl WindowsBrowserPlatform {
    pub fn new(cursor_registry: Arc<cursor_overlay::CursorRegistry>) -> Self {
        Self {
            cursor_registry,
            browser_cursors: Arc::new(Mutex::new(BrowserCursorTracker::default())),
        }
    }
}

impl Default for WindowsBrowserPlatform {
    fn default() -> Self {
        Self::new(Arc::new(cursor_overlay::CursorRegistry::new()))
    }
}

fn is_chromium(name: &str) -> bool {
    let name = name.to_ascii_lowercase();
    let products = [
        "chrome", "chromium", "electron", "msedge", "brave", "vivaldi", "opera", "arc", "thorium",
        "iridium", "yandex",
    ];
    name.split(|ch: char| !ch.is_ascii_alphanumeric())
        .any(|token| products.contains(&token))
}

fn browser_product(name: &str) -> BrowserProduct {
    let executable = name
        .rsplit(['/', '\\'])
        .next()
        .unwrap_or(name)
        .to_ascii_lowercase();
    let executable = executable.trim_end_matches(".exe");
    match executable {
        "chrome" => BrowserProduct::GoogleChrome,
        "chromium" => BrowserProduct::Chromium,
        "msedge" => BrowserProduct::MicrosoftEdge,
        "brave" => BrowserProduct::Brave,
        "vivaldi" => BrowserProduct::Vivaldi,
        "opera" => BrowserProduct::Opera,
        "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,
    }
}

fn isolated_browser_candidates_from_roots(
    program_files: &std::path::Path,
    program_files_x86: &std::path::Path,
) -> Vec<(PathBuf, PathBuf, &'static str, &'static str)> {
    vec![
        (
            program_files.join(r"Google\Chrome\Application\chrome.exe"),
            program_files.to_owned(),
            "CN=Google LLC",
            "O=Google LLC",
        ),
        (
            program_files_x86.join(r"Google\Chrome\Application\chrome.exe"),
            program_files_x86.to_owned(),
            "CN=Google LLC",
            "O=Google LLC",
        ),
        (
            program_files.join(r"Microsoft\Edge\Application\msedge.exe"),
            program_files.to_owned(),
            "CN=Microsoft Corporation",
            "O=Microsoft Corporation",
        ),
        (
            program_files_x86.join(r"Microsoft\Edge\Application\msedge.exe"),
            program_files_x86.to_owned(),
            "CN=Microsoft Corporation",
            "O=Microsoft Corporation",
        ),
    ]
}

fn known_folder_path(id: &windows::core::GUID) -> Result<PathBuf, BrowserRefusal> {
    let raw = unsafe { SHGetKnownFolderPath(id, KF_FLAG_DEFAULT, None) }.map_err(|error| {
        BrowserRefusal::new(
            BrowserRefusalCode::BrowserRouteUnavailable,
            format!("could not resolve trusted Windows installation root: {error}"),
        )
    })?;
    let decoded = unsafe { raw.to_string() };
    unsafe { CoTaskMemFree(Some(raw.0.cast())) };
    decoded.map(PathBuf::from).map_err(|error| {
        BrowserRefusal::new(
            BrowserRefusalCode::BrowserRouteUnavailable,
            format!("trusted Windows installation root was not valid Unicode: {error}"),
        )
    })
}

fn isolated_browser_candidates(
) -> Result<Vec<(PathBuf, PathBuf, &'static str, &'static str)>, BrowserRefusal> {
    let program_files = known_folder_path(&FOLDERID_ProgramFiles)?;
    let program_files_x86 = known_folder_path(&FOLDERID_ProgramFilesX86)?;
    Ok(isolated_browser_candidates_from_roots(
        &program_files,
        &program_files_x86,
    ))
}

fn authenticode_identity_matches(details: &str, expected_cn: &str, expected_org: &str) -> bool {
    let mut lines = details.lines();
    if lines.next().map(str::trim) != Some("Valid") {
        return false;
    }
    let Some(subject) = lines.next() else {
        return false;
    };
    let Some(attributes) = parse_distinguished_name(subject) else {
        return false;
    };
    [expected_cn, expected_org].iter().all(|expected| {
        let Some((expected_type, expected_value)) = expected.split_once('=') else {
            return false;
        };
        let expected_type = expected_type.trim();
        let expected_value = expected_value.trim();
        attributes.iter().any(|(attribute_type, value)| {
            attribute_type.eq_ignore_ascii_case(expected_type) && value == expected_value
        })
    })
}

/// Parses a certificate subject distinguished name into `(type, value)` pairs.
///
/// Accepts the RFC 4514 string form and the Windows `X500DistinguishedName`
/// rendering used by `Get-AuthenticodeSignature`: attributes separated by
/// unquoted, unescaped `,` / `;` (RDNs) or `+` (multi-valued RDNs); values may
/// be double-quoted (a doubled `""` is a literal quote) or contain
/// backslash-escaped characters (`\,`, `\"`, or a `\XX` hex byte). Unescaped
/// whitespace around types and values is ignored. Returns `None` for malformed
/// input so callers fail closed.
fn parse_distinguished_name(subject: &str) -> Option<Vec<(String, String)>> {
    let chars = subject.chars().collect::<Vec<_>>();
    let mut attributes = Vec::new();
    let mut index = 0;
    loop {
        while chars.get(index).is_some_and(|c| c.is_whitespace()) {
            index += 1;
        }
        if index >= chars.len() {
            // An empty subject has no attributes; a trailing separator is malformed.
            return if attributes.is_empty() {
                Some(attributes)
            } else {
                None
            };
        }

        let type_start = index;
        while chars.get(index).is_some_and(|&c| c != '=') {
            if matches!(chars[index], ',' | ';' | '+' | '"' | '\\') {
                return None;
            }
            index += 1;
        }
        if index >= chars.len() {
            return None;
        }
        let attribute_type = chars[type_start..index]
            .iter()
            .collect::<String>()
            .trim()
            .to_owned();
        if attribute_type.is_empty() {
            return None;
        }
        index += 1; // '='

        while chars.get(index).is_some_and(|c| c.is_whitespace()) {
            index += 1;
        }
        let mut value = String::new();
        if chars.get(index) == Some(&'"') {
            index += 1;
            loop {
                match chars.get(index) {
                    None => return None,
                    Some('"') if chars.get(index + 1) == Some(&'"') => {
                        value.push('"');
                        index += 2;
                    }
                    Some('"') => {
                        index += 1;
                        break;
                    }
                    Some('\\') => {
                        let (decoded, consumed) = decode_dn_escape(&chars[index + 1..])?;
                        value.push_str(&decoded);
                        index += 1 + consumed;
                    }
                    Some(&c) => {
                        value.push(c);
                        index += 1;
                    }
                }
            }
            while chars.get(index).is_some_and(|c| c.is_whitespace()) {
                index += 1;
            }
            if chars
                .get(index)
                .is_some_and(|c| !matches!(c, ',' | ';' | '+'))
            {
                return None;
            }
        } else {
            // Length of `value` that must survive trailing-whitespace trimming
            // because it ends in an escaped character.
            let mut protected_len = 0;
            while let Some(&c) = chars.get(index) {
                match c {
                    ',' | ';' | '+' => break,
                    '"' => return None,
                    '\\' => {
                        let (decoded, consumed) = decode_dn_escape(&chars[index + 1..])?;
                        value.push_str(&decoded);
                        protected_len = value.len();
                        index += 1 + consumed;
                    }
                    _ => {
                        value.push(c);
                        index += 1;
                    }
                }
            }
            let trimmed_len = value.trim_end().len().max(protected_len);
            value.truncate(trimmed_len);
        }
        attributes.push((attribute_type, value));

        match chars.get(index) {
            None => return Some(attributes),
            Some(_) => index += 1, // separator
        }
    }
}

/// Decodes the character(s) following a `\` in a DN value. Returns the decoded
/// text and the number of characters consumed after the backslash.
fn decode_dn_escape(rest: &[char]) -> Option<(String, usize)> {
    let first = *rest.first()?;
    if first.is_ascii_hexdigit() {
        // One or more consecutive `\XX` hex pairs encode UTF-8 bytes.
        let mut bytes = Vec::new();
        let mut consumed = 0;
        loop {
            let high = rest.get(consumed)?.to_digit(16)?;
            let low = rest.get(consumed + 1)?.to_digit(16)?;
            bytes.push((high * 16 + low) as u8);
            consumed += 2;
            let continues = rest.get(consumed) == Some(&'\\')
                && rest.get(consumed + 1).is_some_and(char::is_ascii_hexdigit)
                && rest.get(consumed + 2).is_some_and(char::is_ascii_hexdigit);
            if !continues {
                break;
            }
            consumed += 1;
        }
        return String::from_utf8(bytes).ok().map(|text| (text, consumed));
    }
    Some((first.to_string(), 1))
}

fn has_trusted_authenticode_identity(
    executable: &std::path::Path,
    expected_cn: &str,
    expected_org: &str,
) -> bool {
    let Ok(output) = authenticode_output(executable) else {
        return false;
    };
    output.status.success()
        && authenticode_identity_matches(
            &String::from_utf8_lossy(&output.stdout),
            expected_cn,
            expected_org,
        )
}

fn authenticode_output(executable: &std::path::Path) -> std::io::Result<std::process::Output> {
    // Some Windows PowerShell 5.1 builds cannot resolve a `\\?\` verbatim
    // path through `-LiteralPath` ("A drive named '\?\C' does not exist"),
    // which would make every candidate look unsigned. Pass the plain path.
    let executable = executable
        .to_str()
        .and_then(plain_windows_path)
        .ok_or_else(|| {
            std::io::Error::other(format!(
                "browser executable {} has no plain Win32 path",
                executable.display()
            ))
        })?;
    let Ok(system32) = system_directory_path() else {
        return Err(std::io::Error::other(
            "could not resolve the Windows system directory",
        ));
    };
    let powershell = system32.join(r"WindowsPowerShell\v1.0\powershell.exe");
    std::process::Command::new(powershell)
        .args([
            "-NoLogo",
            "-NoProfile",
            "-NonInteractive",
            "-Command",
            r#"$ErrorActionPreference = 'Stop'; $utf8 = [System.Text.UTF8Encoding]::new($false); [Console]::OutputEncoding = $utf8; $module = Join-Path $PSHOME 'Modules\Microsoft.PowerShell.Security\Microsoft.PowerShell.Security.psd1'; Import-Module -Name $module -Force -ErrorAction Stop; $path = [Environment]::GetEnvironmentVariable('CUA_BROWSER_ATTEST_PATH'); $signature = Microsoft.PowerShell.Security\Get-AuthenticodeSignature -LiteralPath $path; Write-Output $signature.Status; Write-Output $signature.SignerCertificate.Subject"#,
        ])
        // The static command imports Security beside the trusted System32
        // PowerShell, ignoring an incompatible inherited PSModulePath. Pass the
        // browser path as data so PowerShell never parses it as command text.
        .env("CUA_BROWSER_ATTEST_PATH", &executable)
        .stdin(Stdio::null())
        .output()
}

/// Result of probing one path for write-class rights held by the calling
/// thread's effective token.
enum WriteProbe {
    Denied,
    Granted(&'static str),
    Failed(String),
}

fn current_token_write_denial_reason(path: &std::path::Path, directory: bool) -> Option<String> {
    match current_token_write_probe(path, directory, false) {
        WriteProbe::Denied => None,
        WriteProbe::Granted(name) => Some(format!("current token was granted {name}")),
        WriteProbe::Failed(reason) => Some(reason),
    }
}

/// Probe `path` for write-class rights. With `link`, the junction or symbolic
/// link object itself is opened rather than its target, because rewriting or
/// replacing a link redirects every path through it.
fn current_token_write_probe(path: &std::path::Path, directory: bool, link: bool) -> WriteProbe {
    use std::os::windows::ffi::OsStrExt;

    // This launch boundary keeps the token that runs the browser (the
    // Driver's own token, or the standard-user token an elevated Driver
    // derives) from executing a browser tree that it can modify. The probe
    // uses the calling thread's effective token, so a caller impersonating
    // the standard-user token probes for that token. Principals more
    // privileged than the launch token that can replace an installed browser
    // are outside this runtime authorization boundary.
    let wide = path
        .as_os_str()
        .encode_wide()
        .chain(std::iter::once(0))
        .collect::<Vec<_>>();
    let rights: &[(&str, u32)] = if directory {
        &[
            ("add_file", FILE_ADD_FILE.0),
            ("add_subdirectory", FILE_ADD_SUBDIRECTORY.0),
            ("delete_child", FILE_DELETE_CHILD.0),
            ("write_ea", FILE_WRITE_EA.0),
            ("write_attributes", FILE_WRITE_ATTRIBUTES.0),
            ("delete", DELETE.0),
            ("write_dac", WRITE_DAC.0),
            ("write_owner", WRITE_OWNER.0),
        ]
    } else {
        &[
            ("write_data", FILE_WRITE_DATA.0),
            ("append_data", FILE_APPEND_DATA.0),
            ("write_ea", FILE_WRITE_EA.0),
            ("write_attributes", FILE_WRITE_ATTRIBUTES.0),
            ("delete", DELETE.0),
            ("write_dac", WRITE_DAC.0),
            ("write_owner", WRITE_OWNER.0),
        ]
    };
    let mut flags = if directory {
        FILE_FLAG_BACKUP_SEMANTICS
    } else {
        FILE_FLAGS_AND_ATTRIBUTES(0)
    };
    if link {
        flags |= FILE_FLAG_OPEN_REPARSE_POINT;
    }
    for &(name, right) in rights {
        match unsafe {
            CreateFileW(
                PCWSTR(wide.as_ptr()),
                right,
                FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
                None,
                OPEN_EXISTING,
                flags,
                None,
            )
        } {
            Ok(handle) => {
                let _ = unsafe { CloseHandle(handle) };
                return WriteProbe::Granted(name);
            }
            Err(error) if error.code() == E_ACCESSDENIED => {}
            Err(error) => {
                return WriteProbe::Failed(format!("{name} probe failed closed: {error}"))
            }
        }
    }
    WriteProbe::Denied
}

/// Outcome of resolving and probing one isolated-launch candidate.
#[derive(Debug, PartialEq, Eq)]
struct CandidateInstallation {
    installed: bool,
    /// The real executable in plain drive form, when it resolved.
    executable: Option<String>,
    write_access: InstallationWriteAccess,
    /// Why the candidate is not `Protected`, for the refusal detail.
    reason: Option<String>,
}

/// The real filesystem, as seen by the calling thread's effective token.
struct WindowsInstallationFs;

impl InstallationFs for WindowsInstallationFs {
    fn entry(&self, path: &str) -> Result<InstallationEntry, String> {
        match std::fs::symlink_metadata(path) {
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
                Ok(InstallationEntry::Missing)
            }
            Err(error) => Err(error.to_string()),
            // std reports name-surrogate reparse points (junctions and
            // symbolic links) as symlinks.
            Ok(metadata) if metadata.file_type().is_symlink() => std::fs::read_link(path)
                .map(|target| InstallationEntry::Link(target.to_string_lossy().into_owned()))
                .map_err(|error| format!("could not read link target: {error}")),
            Ok(metadata) if metadata.is_dir() => Ok(InstallationEntry::Directory),
            Ok(_) => Ok(InstallationEntry::File),
        }
    }

    fn canonical(&self, path: &str) -> Result<String, String> {
        std::fs::canonicalize(path)
            .map(|path| path.to_string_lossy().into_owned())
            .map_err(|error| error.to_string())
    }
}

/// Resolve the candidate below `trusted_root`, following junctions and
/// symbolic links only when they keep the installation layout, and require
/// every object on the resolved chain (each link object, each real directory
/// up to each root, and the executable) to deny write access to the calling
/// thread's token. The first non-denied probe decides the rejection kind: a
/// granted right is `WritableByLaunchToken`, a failed probe is `Untrusted`
/// (fail closed).
fn windows_installation_write_access_with(
    executable: &std::path::Path,
    trusted_root: &std::path::Path,
    fs: &impl InstallationFs,
    mut probe: impl FnMut(&std::path::Path, bool, bool) -> WriteProbe,
) -> CandidateInstallation {
    let untrusted = |reason: String| CandidateInstallation {
        installed: true,
        executable: None,
        write_access: InstallationWriteAccess::Untrusted,
        reason: Some(reason),
    };
    let (Some(executable_text), Some(root_text)) = (executable.to_str(), trusted_root.to_str())
    else {
        return untrusted("installation path is not valid Unicode".to_owned());
    };
    let resolved = match resolve_installation(executable_text, root_text, fs) {
        InstallationResolution::Missing => {
            return CandidateInstallation {
                installed: false,
                executable: None,
                write_access: InstallationWriteAccess::Untrusted,
                reason: None,
            }
        }
        InstallationResolution::Untrusted(reason) => return untrusted(reason),
        InstallationResolution::Resolved(resolved) => resolved,
    };
    let mut write_access = InstallationWriteAccess::Protected;
    let mut reason = None;
    for target in &resolved.probes {
        let path = std::path::Path::new(&target.path);
        match probe(path, target.directory, target.link) {
            WriteProbe::Denied => continue,
            WriteProbe::Granted(right) => {
                write_access = InstallationWriteAccess::WritableByLaunchToken;
                reason = Some(format!(
                    "launch token was granted {right} on {}",
                    target.path
                ));
            }
            WriteProbe::Failed(error) => {
                write_access = InstallationWriteAccess::Untrusted;
                reason = Some(format!("{}: {error}", target.path));
            }
        }
        break;
    }
    CandidateInstallation {
        installed: true,
        executable: Some(resolved.executable),
        write_access,
        reason,
    }
}

fn windows_installation_write_access(
    executable: &std::path::Path,
    trusted_root: &std::path::Path,
) -> CandidateInstallation {
    windows_installation_write_access_with(
        executable,
        trusted_root,
        &WindowsInstallationFs,
        current_token_write_probe,
    )
}

/// Resolve and probe the installation for the token that will run the
/// browser. For a standard-user launch the whole check runs while
/// impersonating that token; if impersonation fails the candidate is
/// `Untrusted` (fail closed).
fn launch_token_installation_write_access(
    context: &BrowserLaunchContext,
    executable: &std::path::Path,
    trusted_root: &std::path::Path,
) -> CandidateInstallation {
    match context {
        BrowserLaunchContext::Driver => windows_installation_write_access(executable, trusted_root),
        BrowserLaunchContext::StandardUser(token) => with_impersonation(token, || {
            windows_installation_write_access(executable, trusted_root)
        })
        .unwrap_or_else(|error| CandidateInstallation {
            installed: true,
            executable: None,
            write_access: InstallationWriteAccess::Untrusted,
            reason: Some(format!(
                "could not impersonate the standard-user launch token: {error}"
            )),
        }),
    }
}

#[cfg(test)]
fn trusted_windows_installation(
    executable: &std::path::Path,
    trusted_root: &std::path::Path,
) -> bool {
    windows_installation_write_access(executable, trusted_root).write_access
        == InstallationWriteAccess::Protected
}

fn isolated_browser_product_name(executable: &std::path::Path) -> &'static str {
    match browser_product(&executable.to_string_lossy()) {
        BrowserProduct::MicrosoftEdge => "Edge",
        _ => "Chrome",
    }
}

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(BrowserRefusal::new(
            BrowserRefusalCode::BrowserRouteUnavailable,
            "the browser uses a relative --user-data-dir that cannot be attested without its launch working directory",
        )),
        _ => Err(BrowserRefusal::new(
            BrowserRefusalCode::BrowserBindingAmbiguous,
            "browser process has multiple distinct --user-data-dir arguments",
        )),
    }
}

fn system_powershell_path() -> Result<PathBuf, BrowserRefusal> {
    Ok(system_directory_path()?.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| {
            BrowserRefusal::new(
                BrowserRefusalCode::BrowserRouteUnavailable,
                format!("could not inspect browser arguments: {error}"),
            )
        })?;
    if !output.status.success() {
        return Err(BrowserRefusal::new(
            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(BrowserRefusal::new(
            BrowserRefusalCode::BrowserBindingStale,
            format!("browser process {pid} has no command line"),
        ));
    }
    Ok(command_line)
}

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(BrowserRefusal::new(
                BrowserRefusalCode::BrowserRouteUnavailable,
                format!("could not read the browser's DevToolsActivePort file: {error}"),
            ))
        }
    };
    let Some((port, path)) = parse_devtools_active_port(&text) else {
        return Err(BrowserRefusal::new(
            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(['/', '\\'])
        .next()
        .unwrap_or(executable_path);
    browser_product(executable) == BrowserProduct::Other && !is_chromium(executable)
}

fn is_embedded_webview_runtime(executable_path: &str) -> bool {
    executable_path
        .rsplit(['/', '\\'])
        .next()
        .unwrap_or(executable_path)
        .eq_ignore_ascii_case("msedgewebview2.exe")
}

fn listener_process_belongs_to_root_lifetime(root_started: u64, listener_started: u64) -> bool {
    listener_started >= root_started
}

#[derive(Debug)]
struct LifetimeScopedProcessTree {
    pids: Vec<u32>,
    started_at: HashMap<u32, u64>,
}

fn lifetime_scoped_descendants_from_processes(
    root_pid: u32,
    processes: &[crate::win32::ProcessInfo],
    mut started_at: impl FnMut(u32) -> Option<u64>,
) -> Option<LifetimeScopedProcessTree> {
    let root_started = started_at(root_pid)?;
    let mut pids = vec![root_pid];
    let mut starts = HashMap::from([(root_pid, root_started)]);
    let mut frontier = vec![root_pid];
    while let Some(parent_pid) = frontier.pop() {
        let parent_started = starts[&parent_pid];
        for process in processes {
            if process.parent_pid != parent_pid || starts.contains_key(&process.pid) {
                continue;
            }
            let Some(child_started) = started_at(process.pid) else {
                continue;
            };
            // Toolhelp parent ids are not lifetime-scoped. Validate every
            // parent -> child edge so pid reuse anywhere in the transitive
            // tree cannot graft an older unrelated process onto this root.
            if !listener_process_belongs_to_root_lifetime(parent_started, child_started) {
                continue;
            }
            pids.push(process.pid);
            starts.insert(process.pid, child_started);
            frontier.push(process.pid);
        }
    }
    Some(LifetimeScopedProcessTree {
        pids,
        started_at: starts,
    })
}

fn retain_identity_matched_listeners(
    observed: Vec<(u16, u32)>,
    expected_starts: &HashMap<u32, u64>,
    mut current_started_at: impl FnMut(u32) -> Option<u64>,
) -> Vec<(u16, u32)> {
    observed
        .into_iter()
        .filter(|(_port, owner_pid)| {
            expected_starts
                .get(owner_pid)
                .zip(current_started_at(*owner_pid))
                .is_some_and(|(expected, current)| *expected == current)
        })
        .collect()
}

fn websocket_port_and_suffix<'a>(url: &'a str, prefix: &str) -> Option<(u16, &'a str)> {
    let remainder = url.strip_prefix(prefix)?;
    let path_start = remainder.find('/')?;
    let port = remainder[..path_start].parse::<u16>().ok()?;
    Some((port, &remainder[path_start..]))
}

fn literal_loopback_websocket_port(url: &str) -> Option<u16> {
    ["ws://127.0.0.1:", "ws://[::1]:"]
        .iter()
        .find_map(|prefix| websocket_port_and_suffix(url, prefix).map(|(port, _)| port))
}

fn canonical_discovered_websocket_url(url: &str, expected_port: u16) -> Option<String> {
    ["ws://127.0.0.1:", "ws://[::1]:", "ws://localhost:"]
        .iter()
        .find_map(|prefix| websocket_port_and_suffix(url, prefix))
        .and_then(|(port, suffix)| {
            (port == expected_port).then(|| format!("ws://127.0.0.1:{expected_port}{suffix}"))
        })
}

fn process_identity(pid: u32) -> Result<(u64, Option<String>), BrowserRefusal> {
    let handle =
        unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pid) }.map_err(|_| {
            BrowserRefusal::new(
                BrowserRefusalCode::BrowserBindingStale,
                format!("browser process {pid} is no longer available"),
            )
        })?;
    let mut created = FILETIME::default();
    let mut exited = FILETIME::default();
    let mut kernel = FILETIME::default();
    let mut user = FILETIME::default();
    let times =
        unsafe { GetProcessTimes(handle, &mut created, &mut exited, &mut kernel, &mut user) };
    let mut path_buf = [0u16; 1024];
    let mut path_len = path_buf.len() as u32;
    let path = unsafe {
        QueryFullProcessImageNameW(
            handle,
            PROCESS_NAME_FORMAT(0),
            windows::core::PWSTR(path_buf.as_mut_ptr()),
            &mut path_len,
        )
    }
    .ok()
    .filter(|_| path_len > 0)
    .map(|_| String::from_utf16_lossy(&path_buf[..path_len as usize]))
    .map(canonical_process_executable);
    let _ = unsafe { CloseHandle(handle) };
    times.map_err(|error| {
        BrowserRefusal::new(
            BrowserRefusalCode::BrowserRouteUnavailable,
            format!("could not fingerprint browser process {pid}: {error}"),
        )
    })?;
    let started = (u64::from(created.dwHighDateTime) << 32) | u64::from(created.dwLowDateTime);
    Ok((started, path))
}

fn canonical_process_executable(path: String) -> String {
    // Manifest executable grants use `canonicalize` too. Normalize the Windows
    // process evidence at collection time so shared authorization stays exact.
    std::fs::canonicalize(&path)
        .map(|canonical| canonical.to_string_lossy().into_owned())
        .unwrap_or(path)
}

fn cdp_comparable_window_bounds(window_id: u64) -> Result<Rect, BrowserRefusal> {
    let hwnd = HWND(window_id as *mut _);
    let mut outer = RECT::default();
    unsafe { GetWindowRect(hwnd, &mut outer) }.map_err(|error| {
        BrowserRefusal::new(
            BrowserRefusalCode::BrowserBindingStale,
            format!("could not read Windows outer bounds for window {window_id}: {error}"),
        )
    })?;
    let physical = (
        outer.left,
        outer.top,
        outer.right - outer.left,
        outer.bottom - outer.top,
    );
    let displays = physical_displays();
    let window_monitor = unsafe { MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST) };
    let monitor_rect = monitor_info(window_monitor).map(|(rect, _)| rect);
    let window_display = monitor_rect.and_then(|rect| {
        displays.iter().position(|display| {
            (display.left, display.top, display.right, display.bottom)
                == (rect.left, rect.top, rect.right, rect.bottom)
        })
    });
    if let Some(bounds) =
        window_display.and_then(|index| physical_window_to_chromium_dip(physical, &displays, index))
    {
        return Ok(bounds);
    }
    // Fallback (display layout unavailable or not edge-connected to the
    // primary): scale absolute coordinates by the window DPI. Exact on the
    // primary display and on any display whose physical origin equals its
    // Chromium DIP origin.
    let dpi = unsafe { GetDpiForWindow(hwnd) };
    let scale = if dpi == 0 { 1.0 } else { f64::from(dpi) / 96.0 };
    Ok(Rect::new(
        f64::from(physical.0) / scale,
        f64::from(physical.1) / scale,
        f64::from(physical.2) / scale,
        f64::from(physical.3) / scale,
    ))
}

/// One monitor in physical (virtual-screen) pixels with its effective scale.
#[derive(Debug, Clone, Copy, PartialEq)]
struct PhysicalDisplay {
    left: i32,
    top: i32,
    right: i32,
    bottom: i32,
    scale: f64,
    primary: bool,
}

const MONITORINFOF_PRIMARY_FLAG: u32 = 1;

fn monitor_info(monitor: HMONITOR) -> Option<(RECT, bool)> {
    if monitor.is_invalid() {
        return None;
    }
    let mut info = MONITORINFO {
        cbSize: std::mem::size_of::<MONITORINFO>() as u32,
        ..Default::default()
    };
    unsafe { GetMonitorInfoW(monitor, &mut info) }
        .as_bool()
        .then_some((
            info.rcMonitor,
            info.dwFlags & MONITORINFOF_PRIMARY_FLAG != 0,
        ))
}

fn physical_displays() -> Vec<PhysicalDisplay> {
    unsafe extern "system" fn collect(
        monitor: HMONITOR,
        _hdc: HDC,
        _clip: *mut RECT,
        data: LPARAM,
    ) -> BOOL {
        let displays = &mut *(data.0 as *mut Vec<PhysicalDisplay>);
        if let Some((rect, primary)) = monitor_info(monitor) {
            let (mut dpi_x, mut dpi_y) = (0u32, 0u32);
            let scale = match GetDpiForMonitor(monitor, MDT_EFFECTIVE_DPI, &mut dpi_x, &mut dpi_y) {
                Ok(()) if dpi_x != 0 => f64::from(dpi_x) / 96.0,
                _ => 1.0,
            };
            displays.push(PhysicalDisplay {
                left: rect.left,
                top: rect.top,
                right: rect.right,
                bottom: rect.bottom,
                scale,
                primary,
            });
        }
        BOOL(1)
    }

    let mut displays: Vec<PhysicalDisplay> = Vec::new();
    unsafe {
        let _ = EnumDisplayMonitors(
            HDC::default(),
            None,
            Some(collect),
            LPARAM(&mut displays as *mut Vec<PhysicalDisplay> as isize),
        );
    }
    displays
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum DisplayEdge {
    Right,
    Left,
    Bottom,
    Top,
}

/// Which edge of `parent` the `child` display shares (with a non-empty
/// overlap along that edge), mirroring Chromium's touching-display test.
fn shared_edge(parent: &PhysicalDisplay, child: &PhysicalDisplay) -> Option<DisplayEdge> {
    let overlaps = |a0: i32, a1: i32, b0: i32, b1: i32| a0.max(b0) < a1.min(b1);
    let vertical_overlap = overlaps(parent.top, parent.bottom, child.top, child.bottom);
    let horizontal_overlap = overlaps(parent.left, parent.right, child.left, child.right);
    if child.left == parent.right && vertical_overlap {
        Some(DisplayEdge::Right)
    } else if child.right == parent.left && vertical_overlap {
        Some(DisplayEdge::Left)
    } else if child.top == parent.bottom && horizontal_overlap {
        Some(DisplayEdge::Bottom)
    } else if child.bottom == parent.top && horizontal_overlap {
        Some(DisplayEdge::Top)
    } else {
        None
    }
}

/// Lay displays out in DIP space the way Chromium's `display::win::ScreenWin`
/// does: the primary display keeps its origin, and every other display is
/// placed against the edge it shares with an already placed display. The
/// offset along that edge is scaled by the display it lies within (the
/// child's scale when the child starts before the parent, otherwise the
/// parent's), so a display's DIP origin generally differs from its physical
/// origin divided by its own scale. Returns `None` for displays that are not
/// edge-connected to the primary display.
fn chromium_dip_origins(displays: &[PhysicalDisplay]) -> Vec<Option<(f64, f64)>> {
    let mut origins: Vec<Option<(f64, f64)>> = vec![None; displays.len()];
    let Some(primary) = displays.iter().position(|display| display.primary) else {
        return origins;
    };
    origins[primary] = Some((
        f64::from(displays[primary].left),
        f64::from(displays[primary].top),
    ));
    let mut remaining: Vec<usize> = (0..displays.len()).filter(|&i| i != primary).collect();
    let mut parents = vec![primary];
    while let Some(parent_index) = parents.pop() {
        let parent = displays[parent_index];
        let (parent_x, parent_y) = origins[parent_index].expect("placed parent");
        let parent_width = f64::from(parent.right - parent.left) / parent.scale;
        let parent_height = f64::from(parent.bottom - parent.top) / parent.scale;
        let mut still_remaining = Vec::with_capacity(remaining.len());
        for child_index in remaining {
            let child = displays[child_index];
            let Some(edge) = shared_edge(&parent, &child) else {
                still_remaining.push(child_index);
                continue;
            };
            let (parent_begin, child_begin) = match edge {
                DisplayEdge::Right | DisplayEdge::Left => (parent.top, child.top),
                DisplayEdge::Bottom | DisplayEdge::Top => (parent.left, child.left),
            };
            let offset = if child_begin < parent_begin {
                -(f64::from(parent_begin - child_begin) / child.scale)
            } else {
                f64::from(child_begin - parent_begin) / parent.scale
            }
            .floor();
            let child_width = f64::from(child.right - child.left) / child.scale;
            let child_height = f64::from(child.bottom - child.top) / child.scale;
            origins[child_index] = Some(match edge {
                DisplayEdge::Right => (parent_x + parent_width, parent_y + offset),
                DisplayEdge::Left => (parent_x - child_width, parent_y + offset),
                DisplayEdge::Bottom => (parent_x + offset, parent_y + parent_height),
                DisplayEdge::Top => (parent_x + offset, parent_y - child_height),
            });
            parents.push(child_index);
        }
        remaining = still_remaining;
    }
    origins
}

/// Convert a physical window rect `(x, y, width, height)` on
/// `displays[display_index]` to the DIP coordinates Chromium reports through
/// CDP `Browser.getWindowForTarget` (#4428).
fn physical_window_to_chromium_dip(
    physical: (i32, i32, i32, i32),
    displays: &[PhysicalDisplay],
    display_index: usize,
) -> Option<Rect> {
    let display = displays.get(display_index)?;
    let (origin_x, origin_y) = chromium_dip_origins(displays)
        .get(display_index)
        .copied()??;
    let scale = display.scale;
    Some(Rect::new(
        origin_x + f64::from(physical.0 - display.left) / scale,
        origin_y + f64::from(physical.1 - display.top) / scale,
        f64::from(physical.2) / scale,
        f64::from(physical.3) / scale,
    ))
}

fn overlay_window_and_scale(window_id: u64) -> Option<(u64, f64)> {
    let hwnd = HWND(window_id as *mut _);
    if hwnd.0.is_null() {
        return None;
    }
    let root = unsafe { GetAncestor(hwnd, GA_ROOT) };
    let overlay_window = if root.0.is_null() {
        window_id
    } else {
        root.0 as u64
    };
    let dpi = unsafe { GetDpiForWindow(hwnd) };
    let scale = if dpi == 0 { 1.0 } else { f64::from(dpi) / 96.0 };
    Some((overlay_window, scale))
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct TcpOwnerRow {
    local_ip: IpAddr,
    local_port: u16,
    state: u32,
    owner_pid: u32,
}

fn network_port(value: u32) -> u16 {
    u16::from_be((value & u32::from(u16::MAX)) as u16)
}

const MAX_TCP_OWNER_TABLE_BYTES: usize = 64 * 1024 * 1024;
const TCP_OWNER_TABLE_READ_ATTEMPTS: usize = 3;

fn select_loopback_listeners(rows: &[TcpOwnerRow], allowed_pids: &[u32]) -> Vec<(u16, u32)> {
    let mut listeners = rows
        .iter()
        .filter(|row| {
            row.state == MIB_TCP_STATE_LISTEN.0 as u32
                && row.local_ip.is_loopback()
                && allowed_pids.contains(&row.owner_pid)
        })
        .map(|row| (row.local_port, row.owner_pid))
        .collect::<Vec<_>>();
    listeners.sort_unstable();
    listeners.dedup();
    listeners
}

/// # Safety
///
/// `R` must be a Windows owner-table row whose every bit pattern is valid.
/// `row_offset` must identify the first row in the table; invalid offsets are
/// bounds-checked and refused rather than read.
unsafe fn decode_owner_table<R: Copy>(
    bytes: &[u8],
    row_offset: usize,
) -> Result<Vec<R>, BrowserRefusal> {
    let count_bytes: [u8; 4] = bytes
        .get(..4)
        .and_then(|part| part.try_into().ok())
        .ok_or_else(|| {
            BrowserRefusal::new(
                BrowserRefusalCode::BrowserRouteUnavailable,
                "Windows returned a truncated TCP owner table",
            )
        })?;
    let count = u32::from_ne_bytes(count_bytes) as usize;
    let row_size = std::mem::size_of::<R>();
    if row_offset < count_bytes.len() || row_size == 0 {
        return Err(BrowserRefusal::new(
            BrowserRefusalCode::BrowserRouteUnavailable,
            "Windows returned an invalid TCP owner table layout",
        ));
    }
    let required = count
        .checked_mul(row_size)
        .and_then(|rows| rows.checked_add(row_offset))
        .filter(|required| *required <= bytes.len())
        .ok_or_else(|| {
            BrowserRefusal::new(
                BrowserRefusalCode::BrowserRouteUnavailable,
                "Windows returned an invalid TCP owner table length",
            )
        })?;

    let mut rows = Vec::with_capacity(count);
    let mut offset = row_offset;
    while offset < required {
        rows.push(unsafe { std::ptr::read_unaligned(bytes.as_ptr().add(offset).cast::<R>()) });
        offset += row_size;
    }
    Ok(rows)
}

fn query_tcp_owner_table_with(
    mut query: impl FnMut(Option<*mut c_void>, &mut u32) -> u32,
) -> Result<Vec<u8>, BrowserRefusal> {
    let mut size = 0u32;
    let status = query(None, &mut size);
    if status != ERROR_INSUFFICIENT_BUFFER.0 && status != NO_ERROR.0 {
        return Err(BrowserRefusal::new(
            BrowserRefusalCode::BrowserRouteUnavailable,
            format!("could not size the Windows TCP owner table: error {status}"),
        ));
    }
    if size == 0 {
        return Ok(0u32.to_ne_bytes().to_vec());
    }

    for _ in 0..TCP_OWNER_TABLE_READ_ATTEMPTS {
        let requested = size as usize;
        if requested > MAX_TCP_OWNER_TABLE_BYTES {
            return Err(BrowserRefusal::new(
                BrowserRefusalCode::BrowserRouteUnavailable,
                format!("Windows TCP owner table exceeded {MAX_TCP_OWNER_TABLE_BYTES} bytes"),
            ));
        }
        let word_count = requested.div_ceil(std::mem::size_of::<u32>());
        let mut buffer = vec![0u32; word_count];
        let mut buffer_size = (word_count * std::mem::size_of::<u32>()) as u32;
        let status = query(Some(buffer.as_mut_ptr().cast()), &mut buffer_size);
        if status == NO_ERROR.0 {
            let returned = buffer_size as usize;
            let allocated = buffer.len() * std::mem::size_of::<u32>();
            if returned > allocated {
                return Err(BrowserRefusal::new(
                    BrowserRefusalCode::BrowserRouteUnavailable,
                    "Windows returned an oversized TCP owner table",
                ));
            }
            let bytes =
                unsafe { std::slice::from_raw_parts(buffer.as_ptr().cast::<u8>(), returned) };
            return Ok(bytes.to_vec());
        }
        if status != ERROR_INSUFFICIENT_BUFFER.0 {
            return Err(BrowserRefusal::new(
                BrowserRefusalCode::BrowserRouteUnavailable,
                format!("could not read the Windows TCP owner table: error {status}"),
            ));
        }
        size = buffer_size;
    }

    Err(BrowserRefusal::new(
        BrowserRefusalCode::BrowserRouteUnavailable,
        format!(
            "Windows TCP owner table changed during {TCP_OWNER_TABLE_READ_ATTEMPTS} consecutive reads"
        ),
    ))
}

fn query_tcp_owner_table(address_family: u32) -> Result<Vec<u8>, BrowserRefusal> {
    query_tcp_owner_table_with(|buffer, size| unsafe {
        GetExtendedTcpTable(
            buffer,
            size,
            false,
            address_family,
            TCP_TABLE_OWNER_PID_LISTENER,
            0,
        )
    })
}

fn windows_loopback_listeners_with(
    allowed_pids: &[u32],
    mut query: impl FnMut(u32) -> Result<Vec<u8>, BrowserRefusal>,
) -> Result<Vec<(u16, u32)>, BrowserRefusal> {
    let ipv4 = query(u32::from(AF_INET.0));
    let ipv6 = query(u32::from(AF_INET6.0));
    if let (Err(ipv4), Err(ipv6)) = (&ipv4, &ipv6) {
        return Err(BrowserRefusal::new(
            BrowserRefusalCode::BrowserRouteUnavailable,
            format!(
                "could not inspect either Windows TCP owner table: IPv4: {}; IPv6: {}",
                ipv4.message, ipv6.message
            ),
        ));
    }
    if let Err(error) = &ipv4 {
        tracing::warn!(
            code = ?error.code,
            message = %error.message,
            "continuing Windows listener discovery without the IPv4 owner table"
        );
    }
    if let Err(error) = &ipv6 {
        tracing::warn!(
            code = ?error.code,
            message = %error.message,
            "continuing Windows listener discovery without the IPv6 owner table"
        );
    }

    // These Win32 rows contain only integer fields and byte arrays, so every
    // bit pattern returned by the operating system is a valid Rust value.
    let mut rows = Vec::new();
    if let Ok(ipv4) = ipv4 {
        rows.extend(
            unsafe {
                decode_owner_table::<MIB_TCPROW_OWNER_PID>(
                    &ipv4,
                    std::mem::offset_of!(MIB_TCPTABLE_OWNER_PID, table),
                )
            }?
            .into_iter()
            .map(|row| TcpOwnerRow {
                local_ip: IpAddr::V4(Ipv4Addr::from(u32::from_be(row.dwLocalAddr))),
                local_port: network_port(row.dwLocalPort),
                state: row.dwState,
                owner_pid: row.dwOwningPid,
            }),
        );
    }
    if let Ok(ipv6) = ipv6 {
        rows.extend(
            unsafe {
                decode_owner_table::<MIB_TCP6ROW_OWNER_PID>(
                    &ipv6,
                    std::mem::offset_of!(MIB_TCP6TABLE_OWNER_PID, table),
                )
            }?
            .into_iter()
            .map(|row| TcpOwnerRow {
                local_ip: IpAddr::V6(Ipv6Addr::from(row.ucLocalAddr)),
                local_port: network_port(row.dwLocalPort),
                state: row.dwState,
                owner_pid: row.dwOwningPid,
            }),
        );
    }
    Ok(select_loopback_listeners(&rows, allowed_pids))
}

fn windows_loopback_listeners(allowed_pids: &[u32]) -> Result<Vec<(u16, u32)>, BrowserRefusal> {
    windows_loopback_listeners_with(allowed_pids, query_tcp_owner_table)
}

fn system_directory_path() -> Result<PathBuf, BrowserRefusal> {
    let mut buffer = [0u16; 32768];
    let length = unsafe { GetSystemDirectoryW(Some(&mut buffer)) } as usize;
    if length == 0 || length >= buffer.len() {
        return Err(BrowserRefusal::new(
            BrowserRefusalCode::BrowserRouteUnavailable,
            "could not resolve the trusted Windows system directory",
        ));
    }
    Ok(PathBuf::from(String::from_utf16_lossy(&buffer[..length])))
}

async fn native_loopback_listeners(
    allowed_pids: &[u32],
) -> Result<Vec<(u16, u32)>, BrowserRefusal> {
    let allowed_pids = allowed_pids.to_vec();
    tokio::task::spawn_blocking(move || windows_loopback_listeners(&allowed_pids))
        .await
        .map_err(|error| {
            BrowserRefusal::new(
                BrowserRefusalCode::BrowserRouteUnavailable,
                format!("could not inspect Windows TCP listener ownership: {error}"),
            )
        })?
}

async fn raw_loopback_listeners_for_process_tree(
    root_pid: u32,
) -> Result<Vec<(u16, u32)>, BrowserRefusal> {
    let allowed_pids =
        tokio::task::spawn_blocking(move || crate::win32::list_descendants(root_pid))
            .await
            .map_err(|error| {
                BrowserRefusal::new(
                    BrowserRefusalCode::BrowserRouteUnavailable,
                    format!("could not inspect browser process tree: {error}"),
                )
            })?;
    let observed = native_loopback_listeners(&allowed_pids).await?;
    tokio::task::spawn_blocking(move || {
        observed
            .into_iter()
            .filter(|(_port, owner_pid)| process_identity(*owner_pid).is_ok())
            .collect::<Vec<_>>()
    })
    .await
    .map_err(|error| {
        BrowserRefusal::new(
            BrowserRefusalCode::BrowserRouteUnavailable,
            format!("could not inspect spawned browser listener identities: {error}"),
        )
    })
}

async fn loopback_listeners_for_process_tree(
    root_pid: u32,
) -> Result<Vec<(u16, u32)>, BrowserRefusal> {
    let tree = tokio::task::spawn_blocking(move || {
        let processes = crate::win32::list_processes();
        lifetime_scoped_descendants_from_processes(root_pid, &processes, |pid| {
            process_identity(pid).ok().map(|identity| identity.0)
        })
    })
    .await
    .map_err(|error| {
        BrowserRefusal::new(
            BrowserRefusalCode::BrowserRouteUnavailable,
            format!("could not inspect browser process lifetimes: {error}"),
        )
    })?
    .ok_or_else(|| {
        BrowserRefusal::new(
            BrowserRefusalCode::BrowserBindingStale,
            format!("browser process {root_pid} is no longer available"),
        )
    })?;

    let observed = native_loopback_listeners(&tree.pids).await?;
    let expected_starts = tree.started_at;
    tokio::task::spawn_blocking(move || {
        retain_identity_matched_listeners(observed, &expected_starts, |pid| {
            process_identity(pid).ok().map(|identity| identity.0)
        })
    })
    .await
    .map_err(|error| {
        BrowserRefusal::new(
            BrowserRefusalCode::BrowserRouteUnavailable,
            format!("could not reprove browser listener identities: {error}"),
        )
    })
}

async fn loopback_listeners_for_exact_pid(pid: u32) -> Result<Vec<(u16, u32)>, BrowserRefusal> {
    let expected_started =
        tokio::task::spawn_blocking(move || process_identity(pid).map(|identity| identity.0))
            .await
            .map_err(|error| {
                BrowserRefusal::new(
                    BrowserRefusalCode::BrowserRouteUnavailable,
                    format!("could not inspect browser process identity: {error}"),
                )
            })??;
    let observed = native_loopback_listeners(&[pid]).await?;
    tokio::task::spawn_blocking(move || {
        retain_identity_matched_listeners(
            observed,
            &HashMap::from([(pid, expected_started)]),
            |candidate_pid| {
                process_identity(candidate_pid)
                    .ok()
                    .map(|identity| identity.0)
            },
        )
    })
    .await
    .map_err(|error| {
        BrowserRefusal::new(
            BrowserRefusalCode::BrowserRouteUnavailable,
            format!("could not reprove browser process identity: {error}"),
        )
    })
}

async fn loopback_ports_for_exact_pid(pid: u32) -> Result<Vec<u16>, BrowserRefusal> {
    let mut ports = loopback_listeners_for_exact_pid(pid)
        .await?
        .into_iter()
        .map(|(port, _owner_pid)| port)
        .collect::<Vec<_>>();
    ports.sort_unstable();
    ports.dedup();
    Ok(ports)
}

async fn unfiltered_loopback_ports_for_exact_pid(pid: u32) -> Result<Vec<u16>, BrowserRefusal> {
    let mut ports = native_loopback_listeners(&[pid])
        .await?
        .into_iter()
        .map(|(port, _owner_pid)| port)
        .collect::<Vec<_>>();
    ports.sort_unstable();
    ports.dedup();
    Ok(ports)
}

async fn browser_websocket_url(port: u16) -> Option<String> {
    let url = fetch_json_version_ws_url(port).await?;
    canonical_discovered_websocket_url(&url, port)
}

fn select_provisional_setup_port(
    ports: &[u16],
    listeners_before: &[u16],
    setup_was_already_enabled: bool,
) -> Result<Option<u16>, BrowserRefusal> {
    let correlated = ports
        .iter()
        .copied()
        .filter(|port| !listeners_before.contains(port))
        .collect::<Vec<_>>();
    match correlated.as_slice() {
        [port] => Ok(Some(*port)),
        [] if setup_was_already_enabled => match ports {
            [] => Ok(None),
            [port] => Ok(Some(*port)),
            _ => Err(BrowserRefusal::new(
                BrowserRefusalCode::BrowserBindingAmbiguous,
                "the pre-enabled browser setup exposed multiple existing exact-pid loopback listeners",
            )),
        },
        [] => Ok(None),
        _ => Err(BrowserRefusal::new(
            BrowserRefusalCode::BrowserBindingAmbiguous,
            "the approved setup action exposed multiple newly correlated exact-pid listeners",
        )),
    }
}

const ENDPOINT_DISCOVERY_ATTEMPTS: usize = 4;
const ENDPOINT_DISCOVERY_RETRY_DELAY: Duration = Duration::from_millis(100);

async fn browser_endpoints_once(pid: u32) -> Result<Vec<(u16, String, u32)>, BrowserRefusal> {
    let mut endpoints = Vec::new();
    for (port, owner_pid) in loopback_listeners_for_exact_pid(pid).await? {
        if let Some(ws_url) = browser_websocket_url(port).await {
            // Re-read both the socket owner and process identity after the
            // HTTP probe so pid recycling during discovery cannot become
            // exact ownership evidence.
            let reproved = loopback_listeners_for_exact_pid(pid).await?;
            if reproved.contains(&(port, owner_pid)) {
                endpoints.push((port, ws_url, owner_pid));
            } else {
                tracing::debug!(
                    browser_pid = pid,
                    listener_pid = owner_pid,
                    port,
                    "discarding browser endpoint whose listener ownership changed during discovery"
                );
            }
        }
    }
    Ok(endpoints)
}

async fn retry_empty_endpoint_discovery<T, F, Fut>(
    attempts: usize,
    delay: Duration,
    mut probe: F,
) -> Result<Vec<T>, BrowserRefusal>
where
    F: FnMut() -> Fut,
    Fut: Future<Output = Result<Vec<T>, BrowserRefusal>>,
{
    let attempts = attempts.max(1);
    for attempt in 0..attempts {
        let endpoints = probe().await?;
        if !endpoints.is_empty() || attempt + 1 == attempts {
            return Ok(endpoints);
        }
        tokio::time::sleep(delay).await;
    }
    unreachable!("the bounded endpoint-discovery loop always returns")
}

async fn exact_browser_endpoints_for_pid(
    pid: u32,
) -> Result<Vec<(u16, String, u32)>, BrowserRefusal> {
    retry_empty_endpoint_discovery(
        ENDPOINT_DISCOVERY_ATTEMPTS,
        ENDPOINT_DISCOVERY_RETRY_DELAY,
        || browser_endpoints_once(pid),
    )
    .await
}

async fn root_can_use_embedded_descendant_endpoint(pid: u32) -> Result<bool, BrowserRefusal> {
    tokio::task::spawn_blocking(move || {
        let (_started, executable) = process_identity(pid)?;
        Ok(executable.is_some_and(|path| allows_embedded_descendant_endpoint(&path)))
    })
    .await
    .map_err(|error| {
        BrowserRefusal::new(
            BrowserRefusalCode::BrowserRouteUnavailable,
            format!("could not classify browser process identity: {error}"),
        )
    })?
}

async fn embedded_browser_endpoints_once(
    pid: u32,
) -> Result<Vec<(u16, String, u32)>, BrowserRefusal> {
    let mut endpoints = Vec::new();
    for (port, listener_pid) in loopback_listeners_for_process_tree(pid).await? {
        let is_webview_runtime = tokio::task::spawn_blocking(move || {
            process_identity(listener_pid)
                .ok()
                .and_then(|identity| identity.1)
                .is_some_and(|path| is_embedded_webview_runtime(&path))
        })
        .await
        .map_err(|error| {
            BrowserRefusal::new(
                BrowserRefusalCode::BrowserRouteUnavailable,
                format!("could not classify embedded browser listener: {error}"),
            )
        })?;
        if !is_webview_runtime {
            continue;
        }
        if let Some(ws_url) = browser_websocket_url(port).await {
            let reproved = loopback_listeners_for_process_tree(pid).await?;
            if reproved.contains(&(port, listener_pid)) {
                endpoints.push((port, ws_url, listener_pid));
            }
        }
    }
    Ok(endpoints)
}

async fn browser_endpoints_for_pid(pid: u32) -> Result<Vec<(u16, String, u32)>, BrowserRefusal> {
    let exact = exact_browser_endpoints_for_pid(pid).await?;
    if !exact.is_empty() || !root_can_use_embedded_descendant_endpoint(pid).await? {
        return Ok(exact);
    }
    // Native embedded hosts such as Tauri/WPF own the window while a
    // WebView2 child owns DevTools. Standalone Chromium/Electron executables
    // never enter this fallback: their endpoint must be owned by the exact
    // approved pid.
    retry_empty_endpoint_discovery(
        ENDPOINT_DISCOVERY_ATTEMPTS,
        ENDPOINT_DISCOVERY_RETRY_DELAY,
        || embedded_browser_endpoints_once(pid),
    )
    .await
}

async fn loopback_listeners_for_spawned_tree(
    root_pid: u32,
) -> Result<Vec<(u16, u32)>, BrowserRefusal> {
    match loopback_listeners_for_process_tree(root_pid).await {
        Ok(listeners) => Ok(listeners),
        // Edge on Windows ARM can transfer the browser role to a descendant
        // and let its launcher exit. This fallback is used only while core
        // attests the exact private-profile DevTools URL it just read from
        // DevToolsActivePort; ordinary and existing-profile discovery never
        // accept descendant-owned endpoints.
        Err(error) if error.code == BrowserRefusalCode::BrowserBindingStale => {
            raw_loopback_listeners_for_process_tree(root_pid).await
        }
        Err(error) => Err(error),
    }
}

async fn spawned_browser_endpoints_once(
    root_pid: u32,
    expected_ws_url: &str,
) -> Result<Vec<(u16, String, u32)>, BrowserRefusal> {
    let Some(expected_port) = literal_loopback_websocket_port(expected_ws_url) else {
        return Err(BrowserRefusal::new(
            BrowserRefusalCode::BrowserEndpointOwnerMismatch,
            "the driver-spawned browser endpoint is not loopback-only",
        ));
    };
    let mut endpoints = Vec::new();
    for (port, listener_pid) in loopback_listeners_for_spawned_tree(root_pid)
        .await?
        .into_iter()
        .filter(|(port, _listener_pid)| *port == expected_port)
    {
        if browser_websocket_url(port).await.as_deref() != Some(expected_ws_url) {
            continue;
        }
        let reproved = loopback_listeners_for_spawned_tree(root_pid).await?;
        if reproved.contains(&(port, listener_pid)) {
            endpoints.push((port, expected_ws_url.to_owned(), listener_pid));
        }
    }
    Ok(endpoints)
}

async fn spawned_browser_endpoints_for_pid(
    root_pid: u32,
    expected_ws_url: &str,
) -> Result<Vec<(u16, String, u32)>, BrowserRefusal> {
    retry_empty_endpoint_discovery(
        ENDPOINT_DISCOVERY_ATTEMPTS,
        ENDPOINT_DISCOVERY_RETRY_DELAY,
        || spawned_browser_endpoints_once(root_pid, expected_ws_url),
    )
    .await
}

fn owned_endpoint_from_listener(
    root_pid: i64,
    port: u16,
    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
            // ownership scope. Core authorizes and fingerprints root_pid;
            // retain the exact socket owner separately for audit evidence and
            // the narrow Windows launcher-handoff promotion path.
            owner_pid: root_pid,
            listener_pid: Some(i64::from(listener_pid)),
            detail: Some(format!(
                "{context}; exact loopback listener pid {listener_pid}"
            )),
        },
    }
}

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),
        [(port, ws_url, listener_pid)] => Ok(Some(owned_endpoint_from_listener(
            root_pid,
            *port,
            ws_url.clone(),
            *listener_pid,
            context,
            transport,
        ))),
        _ => Err(BrowserRefusal::new(
            BrowserRefusalCode::BrowserBindingAmbiguous,
            "multiple browser-level DevTools endpoints satisfy the approved ownership scope",
        )
        .with_detail(serde_json::json!({
            "candidates": discovered
                .iter()
                .map(|(port, _ws_url, listener_pid)| serde_json::json!({
                    "port": port,
                    "listener_pid": listener_pid,
                }))
                .collect::<Vec<_>>(),
        }))),
    }
}

async fn loopback_port_is_owned_with_retry(
    pid: u32,
    expected_port: u16,
) -> Result<bool, BrowserRefusal> {
    retry_port_ownership(
        ENDPOINT_DISCOVERY_ATTEMPTS,
        ENDPOINT_DISCOVERY_RETRY_DELAY,
        expected_port,
        || loopback_ports_for_exact_pid(pid),
    )
    .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,
    expected_port: u16,
    mut probe: F,
) -> Result<bool, BrowserRefusal>
where
    F: FnMut() -> Fut,
    Fut: Future<Output = Result<Vec<u16>, BrowserRefusal>>,
{
    let attempts = attempts.max(1);
    for attempt in 0..attempts {
        if probe().await?.contains(&expected_port) {
            return Ok(true);
        }
        if attempt + 1 < attempts {
            tokio::time::sleep(delay).await;
        }
    }
    Ok(false)
}

#[async_trait]
impl BrowserPlatform for WindowsBrowserPlatform {
    fn isolated_browser_executable(&self) -> Result<String, BrowserRefusal> {
        // An elevated Driver runs the browser with a derived standard-user
        // token, so installation protection is proven for that token.
        let context = browser_launch_context()?;
        let mut facts = Vec::new();
        let mut executables = Vec::new();
        let mut diagnostics = Vec::new();
        for (candidate, trusted_root, expected_cn, expected_org) in isolated_browser_candidates()? {
            let product = isolated_browser_product_name(&candidate);
            // Resolves junctions and symbolic links that keep the installation
            // layout and probes every object on the resolved chain, so the
            // executable is the real file in plain drive form.
            let installation =
                launch_token_installation_write_access(&context, &candidate, &trusted_root);
            let Some(executable) = installation.executable.filter(|_| installation.installed)
            else {
                diagnostics.push(serde_json::json!({
                    "candidate": candidate.display().to_string(),
                    "installed": installation.installed,
                    "reason": installation.reason,
                }));
                facts.push(if installation.installed {
                    IsolatedCandidateFacts {
                        product,
                        installed: true,
                        write_access: InstallationWriteAccess::Untrusted,
                        vendor_signed: false,
                    }
                } else {
                    IsolatedCandidateFacts::missing(product)
                });
                executables.push(None);
                continue;
            };
            let write_access = installation.write_access;
            // The signature of a writable candidate is read only to explain
            // the refusal; such a candidate is never launched.
            let vendor_signed = write_access != InstallationWriteAccess::Untrusted
                && has_trusted_authenticode_identity(
                    std::path::Path::new(&executable),
                    expected_cn,
                    expected_org,
                );
            diagnostics.push(serde_json::json!({
                "candidate": candidate.display().to_string(),
                "installed": true,
                "resolved": executable,
                "vendor_signed": vendor_signed,
                "reason": installation.reason,
            }));
            let fact = IsolatedCandidateFacts {
                product,
                installed: true,
                write_access,
                vendor_signed,
            };
            let launchable = fact.launchable();
            facts.push(fact);
            executables.push(Some(executable));
            if launchable {
                break;
            }
        }
        match decide_isolated_browser(&facts, context.kind()) {
            IsolatedBrowserDecision::Launch(index) => executables[index].take().ok_or_else(|| {
                BrowserRefusal::new(
                    BrowserRefusalCode::BrowserRouteUnavailable,
                    NO_PROTECTED_BROWSER_MESSAGE,
                )
            }),
            IsolatedBrowserDecision::Refuse(message) => Err(BrowserRefusal::new(
                BrowserRefusalCode::BrowserRouteUnavailable,
                message,
            )
            .with_detail(serde_json::json!({ "candidates": diagnostics }))),
        }
    }

    fn spawn_isolated_browser(
        &self,
        mut command: std::process::Command,
        profile: &std::path::Path,
    ) -> Result<Box<dyn IsolatedBrowserProcess>, BrowserRefusal> {
        match browser_launch_context()? {
            BrowserLaunchContext::Driver => command
                .spawn()
                .map(|child| Box::new(child) as Box<dyn IsolatedBrowserProcess>)
                .map_err(|error| {
                    BrowserRefusal::new(
                        BrowserRefusalCode::BrowserRouteUnavailable,
                        format!("could not launch an isolated browser process: {error}"),
                    )
                }),
            BrowserLaunchContext::StandardUser(token) => {
                require_profile_writable(&token, profile)?;
                tracing::info!(
                    "launching the isolated browser with a standard-user token derived from the \
                     elevated Driver token"
                );
                spawn_with_token(token, &command)
                    .map(|child| Box::new(child) as Box<dyn IsolatedBrowserProcess>)
                    .map_err(|error| {
                        BrowserRefusal::new(
                            BrowserRefusalCode::BrowserRouteUnavailable,
                            format!(
                                "could not launch the isolated browser with the standard-user \
                                 token: {error}"
                            ),
                        )
                    })
            }
        }
    }

    async fn visualize_browser_action(&self, action: BrowserVisualAction) {
        if action.session.is_empty()
            || action.cdp_target_id.is_empty()
            || cua_driver_core::session::is_session_ended(&action.session)
        {
            return;
        }

        let visibility_updates = self.browser_cursors.lock().unwrap().update(
            &action.session,
            action.window_id,
            &action.cdp_target_id,
            action.tab_is_active,
        );
        let cursor_enabled = self
            .cursor_registry
            .get_or_create(&action.session)
            .config
            .enabled;
        for (key, visible) in visibility_updates {
            let enabled = if key == action.session {
                visible && cursor_enabled
            } else {
                visible
                    && self
                        .cursor_registry
                        .get(&key)
                        .is_some_and(|state| state.config.enabled)
            };
            crate::overlay::send_command(key, cursor_overlay::OverlayCommand::SetEnabled(enabled));
        }
        if !action.tab_is_active || !cursor_enabled {
            return;
        }
        let (Some(screen_x), Some(screen_y)) = (action.screen_x, action.screen_y) else {
            return;
        };
        if !screen_x.is_finite() || !screen_y.is_finite() {
            return;
        }
        let Some((overlay_window, scale)) = overlay_window_and_scale(action.window_id) else {
            return;
        };
        let screen_x = screen_x * scale;
        let screen_y = screen_y * scale;

        crate::overlay::send_command(
            action.session.clone(),
            cursor_overlay::OverlayCommand::PinAbove(overlay_window),
        );
        crate::overlay::animate_cursor_to(action.session.clone(), screen_x, screen_y).await;
        self.cursor_registry
            .update_position(&action.session, screen_x, screen_y);

        if matches!(
            action.kind,
            BrowserVisualActionKind::Click
                | BrowserVisualActionKind::Type
                | BrowserVisualActionKind::RightClick
                | BrowserVisualActionKind::DoubleClick
                | BrowserVisualActionKind::Drag
        ) {
            crate::overlay::send_command(
                action.session,
                cursor_overlay::OverlayCommand::ClickPulse {
                    x: screen_x,
                    y: screen_y,
                },
            );
        }
    }

    async fn classify_browser(&self, pid: i64) -> Result<BrowserClassification, BrowserRefusal> {
        let pid_u32 = u32::try_from(pid).map_err(|_| {
            BrowserRefusal::new(
                BrowserRefusalCode::BrowserWrongTargetRefused,
                format!("pid {pid} is outside the Windows process-id range"),
            )
        })?;
        let name = tokio::task::spawn_blocking(move || {
            crate::win32::list_processes()
                .into_iter()
                .find(|process| process.pid == pid_u32)
                .map(|process| process.name)
        })
        .await
        .ok()
        .flatten()
        .ok_or_else(|| {
            BrowserRefusal::new(
                BrowserRefusalCode::BrowserBindingStale,
                format!("browser process {pid} is no longer available"),
            )
        })?;
        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 {
                BrowserEngineFamily::Chromium
            } else if gecko {
                BrowserEngineFamily::Gecko
            } else {
                BrowserEngineFamily::Unknown
            },
            product_kind,
            product: Some(name),
            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,
        })
    }

    async fn native_window(
        &self,
        pid: i64,
        window_id: u64,
    ) -> Result<NativeWindowInfo, BrowserRefusal> {
        let pid_u32 = u32::try_from(pid).map_err(|_| {
            BrowserRefusal::new(
                BrowserRefusalCode::BrowserWrongTargetRefused,
                format!("pid {pid} is outside the Windows process-id range"),
            )
        })?;
        let window = tokio::task::spawn_blocking(move || {
            crate::win32::find_window_by_pid_and_handle(pid_u32, window_id)
        })
        .await
        .ok()
        .flatten()
        .ok_or_else(|| {
            BrowserRefusal::new(
                BrowserRefusalCode::BrowserBindingStale,
                format!("Windows window {window_id} is not owned by pid {pid}"),
            )
        })?;
        // CDP Browser.getWindowBounds reports Chromium's outer Win32 rect,
        // including the invisible resize border. General window enumeration
        // intentionally uses DWM's visible frame instead, so obtain the
        // correlation geometry directly from GetWindowRect here.
        let bounds = cdp_comparable_window_bounds(window_id)?;
        Ok(NativeWindowInfo {
            pid,
            window_id,
            title: window.title,
            bounds,
            geometry_exact: true,
            ownership: NativeOwnershipProof {
                method: NativeOwnershipMethod::WindowServerOwner,
                owner_pid: pid,
                detail: Some("GetWindowThreadProcessId".to_owned()),
            },
        })
    }

    async fn is_only_exact_native_window(
        &self,
        pid: i64,
        window_id: u64,
    ) -> Result<Option<bool>, BrowserRefusal> {
        let pid_u32 = u32::try_from(pid).map_err(|_| {
            BrowserRefusal::new(
                BrowserRefusalCode::BrowserWrongTargetRefused,
                format!("pid {pid} is outside the Windows process-id range"),
            )
        })?;
        let windows = tokio::task::spawn_blocking(move || {
            crate::win32::list_windows_via_win32(Some(pid_u32))
                .into_iter()
                .map(|window| window.hwnd)
                .collect::<Vec<_>>()
        })
        .await
        .map_err(|error| {
            BrowserRefusal::new(
                BrowserRefusalCode::BrowserRouteUnavailable,
                format!("could not enumerate Windows browser windows: {error}"),
            )
        })?;
        Ok(Some(windows.len() == 1 && windows[0] == window_id))
    }

    async fn discover_owned_endpoint(
        &self,
        pid: i64,
    ) -> Result<Option<OwnedEndpoint>, BrowserRefusal> {
        let pid_u32 = u32::try_from(pid).map_err(|_| {
            BrowserRefusal::new(
                BrowserRefusalCode::BrowserWrongTargetRefused,
                format!("pid {pid} is outside the Windows process-id range"),
            )
        })?;
        select_unique_owned_endpoint(
            pid,
            browser_endpoints_for_pid(pid_u32).await?,
            "listener owned by the exact approved browser pid or its classified embedded webview tree",
            EndpointTransport::LegacyJsonVersion,
        )
    }

    async fn discover_spawned_endpoint(
        &self,
        pid: i64,
        expected_ws_url: &str,
    ) -> Result<Option<OwnedEndpoint>, BrowserRefusal> {
        let pid_u32 = u32::try_from(pid).map_err(|_| {
            BrowserRefusal::new(
                BrowserRefusalCode::BrowserWrongTargetRefused,
                format!("pid {pid} is outside the Windows process-id range"),
            )
        })?;
        select_unique_owned_endpoint(
            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,
        )
    }

    async fn discover_existing_profile_endpoint(
        &self,
        pid: i64,
    ) -> Result<Option<OwnedEndpoint>, BrowserRefusal> {
        let pid_u32 = u32::try_from(pid).map_err(|_| {
            BrowserRefusal::new(
                BrowserRefusalCode::BrowserWrongTargetRefused,
                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,
        )
    }

    async fn reprove_existing_profile_endpoint(
        &self,
        pid: i64,
        expected_ws_url: &str,
    ) -> Result<Option<OwnedEndpoint>, BrowserRefusal> {
        let pid_u32 = u32::try_from(pid).map_err(|_| {
            BrowserRefusal::new(
                BrowserRefusalCode::BrowserWrongTargetRefused,
                format!("pid {pid} is outside the Windows process-id range"),
            )
        })?;
        let Some(port) = literal_loopback_websocket_port(expected_ws_url) else {
            return Err(BrowserRefusal::new(
                BrowserRefusalCode::BrowserEndpointOwnerMismatch,
                "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(BrowserRefusal::new(
                    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.
        if !loopback_port_is_owned_with_retry(pid_u32, port).await? {
            return Ok(None);
        }
        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,
                listener_pid: None,
                detail: Some("Windows exact browser-pid owner of approved endpoint".to_owned()),
            },
        }))
    }

    async fn setup_existing_profile_endpoint(
        &self,
        request: ExistingProfileSetupRequest,
    ) -> Result<ExistingProfileSetupOutcome, BrowserRefusal> {
        let descriptor = existing_profile_setup_descriptor(request.browser).ok_or_else(|| {
            BrowserRefusal::new(
                BrowserRefusalCode::BrowserRouteUnavailable,
                format!(
                    "approved existing-profile setup is not implemented for {:?}",
                    request.browser
                ),
            )
        })?;
        let pid_u32 = u32::try_from(request.pid).map_err(|_| {
            BrowserRefusal::new(
                BrowserRefusalCode::BrowserWrongTargetRefused,
                "the approved browser pid is outside the Windows process-id range",
            )
        })?;
        let hwnd = request.window_id;
        // The subtraction baseline must remain a conservative superset: a
        // transient identity-reproof failure must not make an old exact-pid
        // listener appear newly created after the approved setup action.
        let listeners_before = unfiltered_loopback_ports_for_exact_pid(pid_u32).await?;
        let handle =
            tokio::task::spawn_blocking(move || crate::browser_setup_ui::enable(hwnd, descriptor))
                .await
                .map_err(|error| {
                    BrowserRefusal::new(
                        BrowserRefusalCode::BrowserRouteUnavailable,
                        format!(
                            "could not inspect {}'s remote-debugging setup UI: {error}",
                            descriptor.product_name
                        ),
                    )
                })??;
        let opened_setup_page = handle.opened_setup_page;
        let enabled_remote_debugging = handle.enabled_remote_debugging;
        let setup_was_already_enabled = !enabled_remote_debugging;
        let focused_setup_address_field = handle.focused_setup_address_field;
        let foregrounded_window = handle.foregrounded_window;
        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),
            };
            let mut endpoints = Vec::new();
            for port in &ports {
                if let Some(ws_url) = browser_websocket_url(*port).await {
                    endpoints.push((
                        *port,
                        ws_url,
                        "Windows exact browser-pid owner plus /json/version",
                    ));
                }
            }
            if endpoints.is_empty() {
                match select_provisional_setup_port(
                    &ports,
                    &listeners_before,
                    setup_was_already_enabled,
                ) {
                    Ok(Some(port)) => endpoints.push((
                        port,
                        format!("ws://127.0.0.1:{port}/devtools/browser"),
                        if listeners_before.contains(&port) {
                            "unique existing exact browser-pid listener bound to a pre-enabled exact setup page"
                        } else {
                            "new exact browser-pid listener correlated with approved setup"
                        },
                    )),
                    Ok(None) => {}
                    Err(error) => break Err(error),
                }
            }
            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(BrowserRefusal::new(
                                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,
                            listener_pid: None,
                            detail: Some((*detail).to_owned()),
                        },
                    })
                }
                [] if std::time::Instant::now() < deadline => {
                    tokio::time::sleep(Duration::from_millis(100)).await;
                }
                [] => {
                    break Err(BrowserRefusal::new(
                        BrowserRefusalCode::BrowserRequiresSetup,
                        format!(
                            "{} did not expose a uniquely exact-pid-owned loopback endpoint after the exact setup action",
                            descriptor.product_name
                        ),
                    ))
                }
                _ => {
                    break Err(BrowserRefusal::new(
                        BrowserRefusalCode::BrowserBindingAmbiguous,
                        format!(
                            "{} exposed multiple exact-pid-owned endpoint candidates after the exact setup action",
                            descriptor.product_name
                        ),
                    ))
                }
            }
        };
        let endpoint = match endpoint_result {
            Ok(endpoint) => endpoint,
            Err(error) => {
                let error = tokio::task::spawn_blocking(move || handle.abort(error))
                    .await
                    .map_err(|join_error| {
                        BrowserRefusal::new(
                            BrowserRefusalCode::BrowserRouteUnavailable,
                            format!("could not roll back browser setup: {join_error}"),
                        )
                    })?;
                return Err(error);
            }
        };
        crate::browser_setup_ui::retain_pending(hwnd, handle)?;

        Ok(ExistingProfileSetupOutcome {
            opened_setup_page,
            closed_setup_page: false,
            enabled_remote_debugging,
            used_bounded_pixel_fallback: false,
            focused_setup_address_field,
            foregrounded_window,
            injected_global_input,
            endpoint: Some(endpoint),
        })
    }

    async fn commit_existing_profile_setup(
        &self,
        request: ExistingProfileSetupRequest,
    ) -> Result<bool, BrowserRefusal> {
        tokio::task::spawn_blocking(move || {
            crate::browser_setup_ui::commit_pending(request.window_id)
        })
        .await
        .map_err(|error| {
            BrowserRefusal::new(
                BrowserRefusalCode::BrowserRouteUnavailable,
                format!("could not commit exact browser setup cleanup: {error}"),
            )
        })?
    }

    fn cleanup_existing_profile_setup(
        &self,
        request: ExistingProfileSetupRequest,
    ) -> Result<bool, BrowserRefusal> {
        let descriptor = existing_profile_setup_descriptor(request.browser).ok_or_else(|| {
            BrowserRefusal::new(
                BrowserRefusalCode::BrowserRouteUnavailable,
                format!(
                    "existing-profile cleanup is not implemented for {:?}",
                    request.browser
                ),
            )
        })?;
        let pid = u32::try_from(request.pid).map_err(|_| {
            BrowserRefusal::new(
                BrowserRefusalCode::BrowserWrongTargetRefused,
                "the approved browser pid is outside the Windows process-id range",
            )
        })?;
        let dismissed_before = crate::browser_consent_ui::dismiss(pid, request.window_id)?;
        let closed_setup_page = crate::browser_setup_ui::disable(request.window_id, descriptor)?;
        let dismissed_after = crate::browser_consent_ui::dismiss(pid, request.window_id)?;
        Ok(dismissed_before || closed_setup_page || dismissed_after)
    }

    async fn abort_existing_profile_setup(
        &self,
        request: ExistingProfileSetupRequest,
        error: BrowserRefusal,
    ) -> BrowserRefusal {
        tokio::task::spawn_blocking(move || {
            crate::browser_setup_ui::abort_pending(request.window_id, error)
        })
        .await
        .unwrap_or_else(|join_error| {
            BrowserRefusal::new(
                BrowserRefusalCode::BrowserRouteUnavailable,
                format!("could not roll back exact browser setup: {join_error}"),
            )
        })
    }

    async fn handle_existing_profile_consent(
        &self,
        request: BrowserConsentRequest,
    ) -> Result<BrowserConsentOutcome, BrowserRefusal> {
        crate::browser_consent_ui::handle(request).await
    }

    async fn process_fingerprint(&self, pid: i64) -> Result<ProcessFingerprint, BrowserRefusal> {
        let pid_u32 = u32::try_from(pid).map_err(|_| {
            BrowserRefusal::new(
                BrowserRefusalCode::BrowserWrongTargetRefused,
                format!("pid {pid} is outside the Windows process-id range"),
            )
        })?;
        let (start_time, executable) =
            tokio::task::spawn_blocking(move || process_identity(pid_u32))
                .await
                .map_err(|error| {
                    BrowserRefusal::new(
                        BrowserRefusalCode::BrowserRouteUnavailable,
                        format!("process fingerprint task failed: {error}"),
                    )
                })??;
        Ok(ProcessFingerprint {
            pid,
            start_time: Some(start_time),
            executable,
        })
    }

    async fn prepare_endpoint(
        &self,
        request: PrepareRequest,
    ) -> Result<PrepareOutcome, BrowserRefusal> {
        let Some(pid) = request.pid else {
            return Err(BrowserRefusal::new(
                BrowserRefusalCode::BrowserRequiresSetup,
                "pid-free isolated launch is handled by shared core",
            ));
        };
        if let Some(endpoint) = self.discover_owned_endpoint(pid).await? {
            return Ok(PrepareOutcome {
                action: PrepareAction::AlreadyPrepared,
                prepared_pid: Some(endpoint.ownership.owner_pid),
                endpoint: Some(endpoint),
                message: "An owned loopback DevTools endpoint is already available.".to_owned(),
                side_effects: Default::default(),
                attachment: None,
            });
        }
        Err(BrowserRefusal::new(
            BrowserRefusalCode::BrowserRequiresSetup,
            "No owned endpoint is available. Acting setup is handled by shared core only for a verified driver-owned isolated profile.",
        ))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn display(left: i32, top: i32, right: i32, bottom: i32, scale: f64) -> PhysicalDisplay {
        PhysicalDisplay {
            left,
            top,
            right,
            bottom,
            scale,
            primary: left == 0 && top == 0,
        }
    }

    /// The mixed-DPI layout measured in #4428 (Chrome stable, Windows 11).
    fn issue_4428_displays() -> Vec<PhysicalDisplay> {
        vec![
            display(6000, 13, 9840, 2173, 1.0),    // DISPLAY1, 100%
            display(3840, -1000, 6000, 2840, 1.5), // DISPLAY2, 150%
            display(0, 0, 3840, 2160, 1.0),        // DISPLAY3, primary
        ]
    }

    fn assert_cdp_match(actual: Rect, expected: Rect) {
        assert!(
            actual.approx_eq(&expected, 2.0),
            "actual {actual:?} expected CDP {expected:?}"
        );
    }

    #[test]
    fn chromium_dip_layout_matches_measured_cdp_bounds_on_mixed_dpi() {
        let displays = issue_4428_displays();
        // Primary, 100%: exact.
        assert_cdp_match(
            physical_window_to_chromium_dip((1470, 19, 2356, 2119), &displays, 2).unwrap(),
            Rect::new(1470.0, 19.0, 2356.0, 2119.0),
        );
        // DISPLAY1, 100%, right of the 150% display: x shifted by its lost width.
        assert_cdp_match(
            physical_window_to_chromium_dip((6193, 200, 2014, 1507), &displays, 0).unwrap(),
            Rect::new(5473.0, 195.0, 2014.0, 1507.0),
        );
        // DISPLAY2, 150%: monitor origin keeps 3840 DIP, not 3840 / 1.5.
        assert_cdp_match(
            physical_window_to_chromium_dip((3943, -800, 2721, 2261), &displays, 1).unwrap(),
            Rect::new(3909.0, -534.0, 1815.0, 1508.0),
        );
    }

    #[test]
    fn chromium_dip_layout_places_left_top_and_detached_displays() {
        let displays = vec![
            display(0, 0, 1920, 1080, 1.0),
            display(-3840, 0, 0, 2160, 2.0),      // left, 200%
            display(0, -1440, 2560, 0, 1.0),      // above
            display(5000, 5000, 6000, 6000, 1.0), // not edge-connected
        ];
        let origins = chromium_dip_origins(&displays);
        assert_eq!(origins[0], Some((0.0, 0.0)));
        assert_eq!(origins[1], Some((-1920.0, 0.0)));
        assert_eq!(origins[2], Some((0.0, -1440.0)));
        assert_eq!(origins[3], None);
        assert!(physical_window_to_chromium_dip((5100, 5100, 10, 10), &displays, 3).is_none());
    }

    #[test]
    fn chromium_dip_layout_without_primary_is_unplaced() {
        let mut displays = issue_4428_displays();
        for display in &mut displays {
            display.primary = false;
        }
        assert!(chromium_dip_origins(&displays).iter().all(Option::is_none));
    }

    #[test]
    fn process_fingerprint_uses_manifest_canonical_executable_path() {
        let (_started, executable) =
            process_identity(std::process::id()).expect("current process fingerprint");
        let expected = std::fs::canonicalize(std::env::current_exe().expect("current executable"))
            .expect("canonical current executable")
            .to_string_lossy()
            .into_owned();

        assert_eq!(executable.as_deref(), Some(expected.as_str()));
    }

    #[tokio::test]
    async fn live_executable_grant_matches_without_installed_app_identity() {
        use cua_driver_core::session_manifest::load_manifest;
        use std::io::Write;

        let pid = i64::from(std::process::id());
        let fingerprint = WindowsBrowserPlatform::default()
            .process_fingerprint(pid)
            .await
            .expect("live Windows process identity");
        let directory = tempfile::tempdir().unwrap();
        for (executable, allowed) in [
            (std::env::current_exe().unwrap(), true),
            (directory.path().join("ungranted-application.exe"), false),
        ] {
            let mut file = tempfile::NamedTempFile::new().unwrap();
            write!(file, "version: 3\nallow:\n  tools: [get_window_state, click]\nresources:\n  apps:\n    - executable: {}\n      windows: all\n",
                serde_json::to_string(&executable).unwrap()).unwrap();
            let manifest = load_manifest(file.path()).unwrap();
            for (adapter, kind) in [
                ("private_observation", "window"),
                ("desktop_input", "window_input"),
            ] {
                let resource = serde_json::json!({
                    "kind": kind,
                    "pid": pid,
                    "window_id": 7,
                    "fingerprint": fingerprint,
                    "bundle_id": null,
                    "launch_path": null,
                });
                assert_eq!(manifest.authorize_protected_resource(adapter, &resource).is_ok(), allowed,
                    "{adapter} must use the live executable fingerprint even without an installed-app match");
            }
        }
    }

    #[test]
    fn isolated_browser_candidates_are_vendor_attested_protected_installs() {
        let candidates = isolated_browser_candidates_from_roots(
            std::path::Path::new(r"D:\Apps"),
            std::path::Path::new(r"E:\Apps32"),
        );
        assert_eq!(candidates.len(), 4);
        assert_eq!(
            candidates[0].0,
            PathBuf::from(r"D:\Apps\Google\Chrome\Application\chrome.exe")
        );
        assert_eq!(
            candidates[1].0,
            PathBuf::from(r"E:\Apps32\Google\Chrome\Application\chrome.exe")
        );
        assert_eq!(
            candidates[2].0,
            PathBuf::from(r"D:\Apps\Microsoft\Edge\Application\msedge.exe")
        );
    }

    #[test]
    fn authenticode_identity_requires_valid_exact_publisher_fields() {
        let details = "Valid\r\nCN=Google LLC, O=Google LLC, L=Mountain View\r\n";
        assert!(authenticode_identity_matches(
            details,
            "CN=Google LLC",
            "O=Google LLC"
        ));
        assert!(!authenticode_identity_matches(
            "NotSigned\r\nCN=Google LLC, O=Google LLC\r\n",
            "CN=Google LLC",
            "O=Google LLC"
        ));
        assert!(!authenticode_identity_matches(
            "Valid\r\nCN=Google LLC, O=Google LLC Evil\r\n",
            "CN=Google LLC",
            "O=Google LLC"
        ));
    }

    #[test]
    fn authenticode_identity_matches_current_browser_subjects() {
        for (subject, cn, org) in [
            (
                "CN=Google LLC, O=Google LLC, L=Mountain View, S=California, C=US",
                "CN=Google LLC",
                "O=Google LLC",
            ),
            (
                "CN=Microsoft Corporation, O=Microsoft Corporation, L=Redmond, S=Washington, C=US",
                "CN=Microsoft Corporation",
                "O=Microsoft Corporation",
            ),
        ] {
            let details = format!("Valid\r\n{subject}\r\n");
            assert!(
                authenticode_identity_matches(&details, cn, org),
                "{subject}"
            );
        }
        assert!(!authenticode_identity_matches(
            "Valid\r\nCN=Microsoft Corporation, O=Google LLC\r\n",
            "CN=Google LLC",
            "O=Google LLC"
        ));
    }

    #[test]
    fn authenticode_identity_matches_plain_names() {
        assert!(authenticode_identity_matches(
            "Valid\nCN=Example Inc,O=Example Inc\n",
            "CN=Example Inc",
            "O=Example Inc"
        ));
        assert!(authenticode_identity_matches(
            "Valid\ncn = Example Inc ; o=Example Inc\n",
            "CN=Example Inc",
            "O=Example Inc"
        ));
    }

    #[test]
    fn authenticode_identity_matches_quoted_organization_with_comma() {
        let details = "Valid\r\nCN=\"Example, Inc.\", O=\"Example, Inc.\", L=Somewhere, C=US\r\n";
        assert!(authenticode_identity_matches(
            details,
            "CN=Example, Inc.",
            "O=Example, Inc."
        ));
        // A quoted value is one attribute: its inner text never forms new fields.
        assert!(!authenticode_identity_matches(
            "Valid\r\nCN=\"Other, CN=Example\", O=\"x, O=Example\"\r\n",
            "CN=Example",
            "O=Example"
        ));
        assert!(!authenticode_identity_matches(
            "Valid\r\nCN=\"Example, Inc.\", O=Example\r\n",
            "CN=Example",
            "O=Example"
        ));
    }

    #[test]
    fn authenticode_identity_matches_escaped_commas() {
        let details = "Valid\nCN=Example\\, Inc., O=Example\\2C Inc.\n";
        assert!(authenticode_identity_matches(
            details,
            "CN=Example, Inc.",
            "O=Example, Inc."
        ));
        assert!(!authenticode_identity_matches(
            details,
            "CN=Example",
            "O=Example"
        ));
    }

    #[test]
    fn distinguished_name_parser_handles_rfc4514_forms() {
        let parsed = parse_distinguished_name(
            r#"CN="Say ""Hi"", Ltd" + OU=Unit, O=A\;B, L=Trailing\ , C=US"#,
        )
        .expect("well-formed subject");
        assert_eq!(
            parsed,
            vec![
                ("CN".to_owned(), r#"Say "Hi", Ltd"#.to_owned()),
                ("OU".to_owned(), "Unit".to_owned()),
                ("O".to_owned(), "A;B".to_owned()),
                ("L".to_owned(), "Trailing ".to_owned()),
                ("C".to_owned(), "US".to_owned()),
            ]
        );
        assert_eq!(
            parse_distinguished_name("O=Caf\\C3\\A9").unwrap()[0].1,
            "Café"
        );
        assert!(parse_distinguished_name("CN=\"unterminated").is_none());
        assert!(parse_distinguished_name("CN=\"quoted\" junk").is_none());
        assert!(parse_distinguished_name("CN=Google LLC,").is_none());
        assert!(parse_distinguished_name("=Google LLC").is_none());
        assert!(parse_distinguished_name("Google LLC").is_none());
        assert!(parse_distinguished_name("CN=trailing\\").is_none());
        assert!(parse_distinguished_name("CN=bad\\2G").is_none());
        assert!(!authenticode_identity_matches(
            "Valid\nCN=\"Google LLC\nO=Google LLC\n",
            "CN=Google LLC",
            "O=Google LLC"
        ));
    }

    #[test]
    fn writable_installation_tree_is_rejected() {
        let root = tempfile::tempdir().expect("writable product root");
        let product = root.path().join(r"Google\Chrome\Application");
        std::fs::create_dir_all(&product).expect("writable product directories");
        let executable = product.join("chrome.exe");
        std::fs::write(&executable, b"not a browser").expect("writable executable");

        assert!(!trusted_windows_installation(&executable, root.path()));
    }

    /// A link-free installation tree: `.exe` paths are files, the rest are
    /// directories, and every path is already canonical.
    struct PlainTreeFs;

    impl InstallationFs for PlainTreeFs {
        fn entry(&self, path: &str) -> Result<InstallationEntry, String> {
            Ok(if path.ends_with(".exe") {
                InstallationEntry::File
            } else {
                InstallationEntry::Directory
            })
        }
        fn canonical(&self, path: &str) -> Result<String, String> {
            Ok(format!(r"\\?\{path}"))
        }
    }

    /// A tree whose `Application` directory is a junction to `target`.
    struct JunctionedTreeFs {
        target: &'static str,
    }

    impl InstallationFs for JunctionedTreeFs {
        fn entry(&self, path: &str) -> Result<InstallationEntry, String> {
            if path.eq_ignore_ascii_case(r"C:\Program Files\Google\Chrome\Application") {
                return Ok(InstallationEntry::Link(format!(r"\\?\{}", self.target)));
            }
            PlainTreeFs.entry(path)
        }
        fn canonical(&self, path: &str) -> Result<String, String> {
            let relocated = path.replacen(
                r"C:\Program Files\Google\Chrome\Application",
                self.target,
                1,
            );
            Ok(format!(r"\\?\{relocated}"))
        }
    }

    fn write_access_with_probe(
        fs: &impl InstallationFs,
        probe: impl FnMut(&std::path::Path, bool, bool) -> WriteProbe,
    ) -> CandidateInstallation {
        let root = std::path::Path::new(r"C:\Program Files");
        windows_installation_write_access_with(
            &root.join(r"Google\Chrome\Application\chrome.exe"),
            root,
            fs,
            probe,
        )
    }

    #[test]
    fn installation_trust_walk_requires_every_probe_to_deny_write() {
        let root = std::path::Path::new(r"C:\Program Files");
        let protected = write_access_with_probe(&PlainTreeFs, |_, _, _| WriteProbe::Denied);
        assert_eq!(protected.write_access, InstallationWriteAccess::Protected);
        assert_eq!(
            protected.executable.as_deref(),
            Some(r"C:\Program Files\Google\Chrome\Application\chrome.exe")
        );
        for writable in [r"C:\Program Files\Google\Chrome", r"C:\Program Files"] {
            let result = write_access_with_probe(&PlainTreeFs, |path, directory, _| {
                if directory && path == std::path::Path::new(writable) {
                    WriteProbe::Granted("add_file")
                } else {
                    WriteProbe::Denied
                }
            });
            assert_eq!(
                result.write_access,
                InstallationWriteAccess::WritableByLaunchToken,
                "{writable}"
            );
        }
        let outside = windows_installation_write_access_with(
            std::path::Path::new(r"D:\UserControlled\chrome.exe"),
            root,
            &PlainTreeFs,
            |_, _, _| WriteProbe::Denied,
        );
        assert!(outside.installed);
        assert_eq!(outside.executable, None);
        assert_eq!(outside.write_access, InstallationWriteAccess::Untrusted);
    }

    #[test]
    fn installation_write_access_distinguishes_granted_from_failed_probes() {
        let root = std::path::Path::new(r"C:\Program Files");
        let executable = root.join(r"Google\Chrome\Application\chrome.exe");
        let failed = write_access_with_probe(&PlainTreeFs, |_, directory, _| {
            if directory {
                WriteProbe::Denied
            } else {
                WriteProbe::Failed("write_data probe failed closed".to_owned())
            }
        });
        assert_eq!(failed.write_access, InstallationWriteAccess::Untrusted);
        assert!(failed
            .reason
            .as_deref()
            .is_some_and(|reason| reason.contains("write_data probe failed closed")));
        assert_eq!(isolated_browser_product_name(&executable), "Chrome");
        assert_eq!(
            isolated_browser_product_name(&root.join(r"Microsoft\Edge\Application\msedge.exe")),
            "Edge"
        );
    }

    #[test]
    fn junctioned_installation_is_accepted_only_when_the_whole_chain_is_protected() {
        let fs = JunctionedTreeFs {
            target: r"E:\Program Files\Google\Chrome\Application",
        };
        let mut probed = Vec::new();
        let protected = write_access_with_probe(&fs, |path, directory, link| {
            probed.push((path.to_path_buf(), directory, link));
            WriteProbe::Denied
        });
        assert_eq!(protected.write_access, InstallationWriteAccess::Protected);
        assert_eq!(
            protected.executable.as_deref(),
            Some(r"E:\Program Files\Google\Chrome\Application\chrome.exe")
        );
        assert!(probed.contains(&(
            PathBuf::from(r"C:\Program Files\Google\Chrome\Application"),
            true,
            true
        )));

        // The junction itself, each real directory, and the real root must
        // all deny write access.
        for writable in [
            r"C:\Program Files\Google\Chrome\Application",
            r"E:\Program Files",
            r"E:\Program Files\Google\Chrome\Application",
            r"E:\Program Files\Google\Chrome\Application\chrome.exe",
        ] {
            let result = write_access_with_probe(&fs, |path, _, _| {
                if path == std::path::Path::new(writable) {
                    WriteProbe::Granted("write_dac")
                } else {
                    WriteProbe::Denied
                }
            });
            assert_eq!(
                result.write_access,
                InstallationWriteAccess::WritableByLaunchToken,
                "{writable}"
            );
            assert!(result.reason.unwrap().contains(writable));
        }

        // A junction that leaves the installation layout is never followed.
        let escaped = write_access_with_probe(
            &JunctionedTreeFs {
                target: r"C:\Users\Public\Chrome",
            },
            |_, _, _| WriteProbe::Denied,
        );
        assert_eq!(escaped.write_access, InstallationWriteAccess::Untrusted);
        assert_eq!(escaped.executable, None);
    }

    #[test]
    fn installed_vendor_browser_tree_is_accepted_only_for_a_nonwritable_token() {
        let candidates = isolated_browser_candidates().expect("trusted Known Folder roots");
        let installed = candidates
            .iter()
            .find(|(candidate, _, expected_cn, expected_org)| {
                candidate.is_file()
                    && has_trusted_authenticode_identity(candidate, expected_cn, expected_org)
            });
        let Some(installed) = installed else {
            let diagnostics = candidates
                .iter()
                .map(|(candidate, _, _, _)| {
                    let name = candidate
                        .file_name()
                        .and_then(|value| value.to_str())
                        .unwrap_or("unknown.exe");
                    if !candidate.is_file() {
                        return format!("{name}: missing");
                    }
                    match authenticode_output(candidate) {
                        Ok(output) => format!(
                            "{name}: exit={:?}, stdout_utf8={:?}, stdout_bytes={:?}, stderr_utf8={:?}",
                            output.status.code(),
                            String::from_utf8_lossy(&output.stdout),
                            output.stdout,
                            String::from_utf8_lossy(&output.stderr),
                        ),
                        Err(error) => format!("{name}: invocation_error={error}"),
                    }
                })
                .collect::<Vec<_>>();
            panic!(
                "Windows CI image must provide signed Chrome or Edge; diagnostics: {diagnostics:?}"
            );
        };

        // An elevated host (GitHub-hosted Windows runs tests elevated) must
        // prove the vendor tree protected from the derived standard-user
        // token and select it end to end, instead of refusing.
        let context = browser_launch_context().expect("browser launch context");
        if matches!(context, BrowserLaunchContext::StandardUser(_)) {
            assert_eq!(
                launch_token_installation_write_access(&context, &installed.0, &installed.1)
                    .write_access,
                InstallationWriteAccess::Protected,
                "the standard-user launch token must not be able to modify {}",
                installed.0.display()
            );
            let selected = WindowsBrowserPlatform::default()
                .isolated_browser_executable()
                .expect(
                    "an elevated Driver selects a protected browser for its standard-user token",
                );
            let selected_path = selected.strip_prefix(r"\\?\").unwrap_or(&selected);
            assert!(
                candidates.iter().any(|(candidate, _, _, _)| selected_path
                    .eq_ignore_ascii_case(&candidate.to_string_lossy())),
                "selected executable must be a trusted candidate: {selected}"
            );
            return;
        }

        if !trusted_windows_installation(&installed.0, &installed.1) {
            let mut diagnostics = vec![(
                "executable".to_string(),
                current_token_write_denial_reason(&installed.0, false),
            )];
            let mut current = installed.0.parent();
            let mut index = 0;
            while let Some(directory) = current {
                diagnostics.push((
                    format!("ancestor_{index}"),
                    current_token_write_denial_reason(directory, true),
                ));
                if directory == installed.1 {
                    break;
                }
                current = directory.parent();
                index += 1;
            }
            for (location, reason) in &diagnostics {
                if let Some(reason) = reason {
                    assert!(
                        reason.starts_with("current token was granted "),
                        "{location} refusal must prove write-capable token posture, not an unexpected probe failure: {reason}"
                    );
                }
            }
            assert!(
                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:?}"
            );
            return;
        }
    }
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::sync::Arc;

    #[test]
    fn native_listener_selection_requires_loopback_listen_state_and_process_tree() {
        let rows = [
            TcpOwnerRow {
                local_ip: "127.0.0.1".parse().unwrap(),
                local_port: 9222,
                state: MIB_TCP_STATE_LISTEN.0 as u32,
                owner_pid: 42,
            },
            TcpOwnerRow {
                local_ip: "0.0.0.0".parse().unwrap(),
                local_port: 9333,
                state: MIB_TCP_STATE_LISTEN.0 as u32,
                owner_pid: 43,
            },
            TcpOwnerRow {
                local_ip: "::1".parse().unwrap(),
                local_port: 9444,
                state: MIB_TCP_STATE_LISTEN.0 as u32,
                owner_pid: 43,
            },
            TcpOwnerRow {
                local_ip: "127.0.0.1".parse().unwrap(),
                local_port: 9555,
                state: MIB_TCP_STATE_LISTEN.0 as u32,
                owner_pid: 7,
            },
            TcpOwnerRow {
                local_ip: "127.0.0.1".parse().unwrap(),
                local_port: 9666,
                state: 5,
                owner_pid: 42,
            },
        ];
        assert_eq!(
            select_loopback_listeners(&rows, &[42, 43]),
            vec![(9222, 42), (9444, 43)]
        );
    }

    #[test]
    fn native_listener_selection_preserves_owner_and_deduplicates_rows() {
        let row = TcpOwnerRow {
            local_ip: "127.0.0.1".parse().unwrap(),
            local_port: 9222,
            state: MIB_TCP_STATE_LISTEN.0 as u32,
            owner_pid: 43,
        };
        assert_eq!(
            select_loopback_listeners(&[row, row], &[42, 43]),
            vec![(9222, 43)]
        );
    }

    #[test]
    fn native_owner_table_port_uses_network_byte_order() {
        assert_eq!(network_port(0x0000_0624), 9222);
    }

    fn owner_table_bytes<R: Copy>(row_offset: usize, rows: &[R]) -> Vec<u8> {
        // The Win32 owner rows used by these tests contain no padding.
        let mut bytes = vec![0; row_offset + std::mem::size_of_val(rows)];
        bytes[..4].copy_from_slice(&(rows.len() as u32).to_ne_bytes());
        unsafe {
            std::ptr::copy_nonoverlapping(
                rows.as_ptr().cast::<u8>(),
                bytes.as_mut_ptr().add(row_offset),
                std::mem::size_of_val(rows),
            );
        }
        bytes
    }

    #[test]
    fn native_owner_table_decoder_rejects_truncated_and_invalid_counts() {
        let truncated = unsafe { decode_owner_table::<u32>(&[0, 0, 0], 4) }.unwrap_err();
        assert!(truncated.message.contains("truncated TCP owner table"));

        let invalid_offset = unsafe { decode_owner_table::<u32>(&[0; 8], 3) }.unwrap_err();
        assert!(invalid_offset
            .message
            .contains("invalid TCP owner table layout"));

        let impossible_count = u32::MAX.to_ne_bytes();
        let invalid = unsafe { decode_owner_table::<u32>(&impossible_count, 4) }.unwrap_err();
        assert!(invalid.message.contains("invalid TCP owner table length"));
    }

    #[test]
    fn native_owner_table_decoder_uses_the_real_ipv4_and_ipv6_layouts() {
        let ipv4_offset = std::mem::offset_of!(MIB_TCPTABLE_OWNER_PID, table);
        assert_eq!(ipv4_offset, 4);
        assert_eq!(std::mem::size_of::<MIB_TCPROW_OWNER_PID>(), 24);
        let ipv4_row = MIB_TCPROW_OWNER_PID {
            dwState: MIB_TCP_STATE_LISTEN.0 as u32,
            dwLocalAddr: u32::from_ne_bytes(Ipv4Addr::LOCALHOST.octets()),
            dwLocalPort: 0x0000_0624,
            dwRemoteAddr: 0,
            dwRemotePort: 0,
            dwOwningPid: 42,
        };
        let ipv4_bytes = owner_table_bytes(ipv4_offset, &[ipv4_row]);
        let decoded_ipv4 =
            unsafe { decode_owner_table::<MIB_TCPROW_OWNER_PID>(&ipv4_bytes, ipv4_offset) }
                .unwrap();
        assert_eq!(decoded_ipv4, vec![ipv4_row]);

        let ipv6_offset = std::mem::offset_of!(MIB_TCP6TABLE_OWNER_PID, table);
        assert_eq!(ipv6_offset, 4);
        assert_eq!(std::mem::size_of::<MIB_TCP6ROW_OWNER_PID>(), 56);
        let ipv6_row = MIB_TCP6ROW_OWNER_PID {
            ucLocalAddr: Ipv6Addr::LOCALHOST.octets(),
            dwLocalScopeId: 0,
            dwLocalPort: 0x0000_0624,
            ucRemoteAddr: Ipv6Addr::UNSPECIFIED.octets(),
            dwRemoteScopeId: 0,
            dwRemotePort: 0,
            dwState: MIB_TCP_STATE_LISTEN.0 as u32,
            dwOwningPid: 43,
        };
        let ipv6_bytes = owner_table_bytes(ipv6_offset, &[ipv6_row]);
        let decoded_ipv6 =
            unsafe { decode_owner_table::<MIB_TCP6ROW_OWNER_PID>(&ipv6_bytes, ipv6_offset) }
                .unwrap();
        assert_eq!(decoded_ipv6, vec![ipv6_row]);
    }

    #[test]
    fn native_listener_discovery_keeps_ipv4_when_ipv6_is_unavailable() {
        let ipv4_offset = std::mem::offset_of!(MIB_TCPTABLE_OWNER_PID, table);
        let ipv4 = owner_table_bytes(
            ipv4_offset,
            &[MIB_TCPROW_OWNER_PID {
                dwState: MIB_TCP_STATE_LISTEN.0 as u32,
                dwLocalAddr: u32::from_ne_bytes(Ipv4Addr::LOCALHOST.octets()),
                dwLocalPort: 0x0000_0624,
                dwRemoteAddr: 0,
                dwRemotePort: 0,
                dwOwningPid: 42,
            }],
        );

        let listeners = windows_loopback_listeners_with(&[42], |family| {
            if family == u32::from(AF_INET.0) {
                Ok(ipv4.clone())
            } else {
                Err(BrowserRefusal::new(
                    BrowserRefusalCode::BrowserRouteUnavailable,
                    "IPv6 owner table is unsupported",
                ))
            }
        })
        .unwrap();
        assert_eq!(listeners, vec![(9222, 42)]);
    }

    #[test]
    fn native_listener_discovery_refuses_when_both_families_fail() {
        let error = windows_loopback_listeners_with(&[42], |family| {
            Err(BrowserRefusal::new(
                BrowserRefusalCode::BrowserRouteUnavailable,
                format!("family {family} unavailable"),
            ))
        })
        .unwrap_err();
        assert!(error.message.contains("either Windows TCP owner table"));
        assert!(error.message.contains("IPv4:"));
        assert!(error.message.contains("IPv6:"));
    }

    #[test]
    fn native_owner_table_query_rejects_sizing_and_read_errors() {
        let sizing = query_tcp_owner_table_with(|_, _| 5).unwrap_err();
        assert!(sizing.message.contains("size the Windows TCP owner table"));

        let mut calls = 0;
        let reading = query_tcp_owner_table_with(|buffer, size| {
            calls += 1;
            if buffer.is_none() {
                *size = 4;
                ERROR_INSUFFICIENT_BUFFER.0
            } else {
                5
            }
        })
        .unwrap_err();
        assert_eq!(calls, 2);
        assert!(reading.message.contains("read the Windows TCP owner table"));
    }

    #[test]
    fn native_owner_table_query_bounds_growth_and_retry_churn() {
        let oversized = query_tcp_owner_table_with(|buffer, size| {
            assert!(buffer.is_none());
            *size = (MAX_TCP_OWNER_TABLE_BYTES as u32) + 1;
            ERROR_INSUFFICIENT_BUFFER.0
        })
        .unwrap_err();
        assert!(oversized
            .message
            .contains("TCP owner table exceeded 67108864 bytes"));

        let mut calls = 0;
        let churn = query_tcp_owner_table_with(|buffer, size| {
            calls += 1;
            *size = if buffer.is_none() { 4 } else { *size + 4 };
            ERROR_INSUFFICIENT_BUFFER.0
        })
        .unwrap_err();
        assert_eq!(calls, TCP_OWNER_TABLE_READ_ATTEMPTS + 1);
        assert!(churn.message.contains("changed during 3 consecutive reads"));
    }

    #[test]
    fn native_owner_table_query_rejects_oversized_success_length() {
        let oversized = query_tcp_owner_table_with(|buffer, size| {
            if buffer.is_none() {
                *size = 4;
                ERROR_INSUFFICIENT_BUFFER.0
            } else {
                *size = 8;
                NO_ERROR.0
            }
        })
        .unwrap_err();
        assert!(oversized.message.contains("oversized TCP owner table"));
    }

    #[test]
    fn native_owner_table_observes_a_real_loopback_listener() {
        let listener = std::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap();
        let port = listener.local_addr().unwrap().port();
        let pid = std::process::id();

        let listeners = windows_loopback_listeners(&[pid]).unwrap();
        assert!(
            listeners.contains(&(port, pid)),
            "native owner table did not report current-process listener {port}: {listeners:?}"
        );
    }

    #[test]
    fn process_tree_endpoint_uses_the_authorized_root_and_retains_listener_evidence() {
        let endpoint = owned_endpoint_from_listener(
            42,
            9222,
            "ws://127.0.0.1:9222/devtools/browser/id".to_owned(),
            43,
            "verified process tree",
            EndpointTransport::EmbeddedDescendant,
        );

        assert_eq!(endpoint.ownership.owner_pid, 42);
        assert_eq!(endpoint.ownership.listener_pid, Some(43));
        assert_eq!(endpoint.http_port, Some(9222));
        assert!(endpoint
            .ownership
            .detail
            .as_deref()
            .is_some_and(|detail| detail.contains("exact loopback listener pid 43")));
    }

    #[test]
    fn owned_endpoint_selection_requires_exactly_one_lifetime_matched_listener() {
        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,
            vec![(
                9222,
                "ws://127.0.0.1:9222/devtools/browser/edge".to_owned(),
                43,
            )],
            "verified process tree",
            EndpointTransport::LegacyJsonVersion,
        )
        .expect("one lifetime-matched listener")
        .expect("selected endpoint");
        assert_eq!(selected.http_port, Some(9222));
        assert_eq!(selected.ownership.listener_pid, Some(43));

        let ambiguous = select_unique_owned_endpoint(
            42,
            vec![
                (
                    9222,
                    "ws://127.0.0.1:9222/devtools/browser/a".to_owned(),
                    43,
                ),
                (
                    9333,
                    "ws://127.0.0.1:9333/devtools/browser/b".to_owned(),
                    44,
                ),
            ],
            "verified process tree",
            EndpointTransport::LegacyJsonVersion,
        )
        .expect_err("multiple lifetime-matched listeners must be refused");
        assert_eq!(ambiguous.code, BrowserRefusalCode::BrowserBindingAmbiguous);
        let candidates = ambiguous
            .detail
            .as_ref()
            .and_then(|detail| detail.get("candidates"))
            .and_then(serde_json::Value::as_array)
            .expect("candidate detail");
        assert_eq!(candidates.len(), 2);
        assert_eq!(candidates[0]["port"], 9222);
        assert_eq!(candidates[0]["listener_pid"], 43);
        assert_eq!(candidates[1]["port"], 9333);
        assert_eq!(candidates[1]["listener_pid"], 44);
    }

    #[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"));
        assert!(!is_chromium("Knowledge.exe"));
    }

    #[test]
    fn only_native_embedded_hosts_may_use_descendant_owned_devtools() {
        assert!(allows_embedded_descendant_endpoint(
            r"D:\fixtures\CuaTestHarness.Tauri.exe"
        ));
        assert!(allows_embedded_descendant_endpoint(
            r"D:\fixtures\CuaTestHarness.WebView.exe"
        ));
        assert!(!allows_embedded_descendant_endpoint(
            r"C:\Program Files\Google\Chrome\Application\chrome.exe"
        ));
        assert!(!allows_embedded_descendant_endpoint(
            r"D:\fixtures\CuaTestHarness.Electron.exe"
        ));
        assert!(is_embedded_webview_runtime(
            r"C:\Program Files (x86)\Microsoft\EdgeWebView\Application\msedgewebview2.exe"
        ));
        assert!(!is_embedded_webview_runtime(
            r"D:\fixtures\CuaTestHarness.Electron.exe"
        ));
    }

    #[test]
    fn endpoint_listener_cannot_predate_the_authorized_browser_root() {
        assert!(listener_process_belongs_to_root_lifetime(100, 100));
        assert!(listener_process_belongs_to_root_lifetime(100, 101));
        assert!(!listener_process_belongs_to_root_lifetime(100, 99));
    }

    #[test]
    fn lifetime_scoped_tree_validates_every_parent_child_edge() {
        let processes = vec![
            crate::win32::ProcessInfo {
                pid: 42,
                parent_pid: 1,
                name: "msedge.exe".to_owned(),
            },
            crate::win32::ProcessInfo {
                pid: 43,
                parent_pid: 42,
                name: "msedge.exe".to_owned(),
            },
            crate::win32::ProcessInfo {
                pid: 44,
                parent_pid: 43,
                name: "CuaTestHarness.Electron.exe".to_owned(),
            },
            crate::win32::ProcessInfo {
                pid: 45,
                parent_pid: 42,
                name: "msedge.exe".to_owned(),
            },
        ];
        let starts = HashMap::from([
            (42, 100),
            // This pid was reused by a real child of the new browser root.
            (43, 300),
            // This unrelated process names pid 43 as its parent but predates
            // that incarnation, so validating only against root 42 is unsafe.
            (44, 200),
            (45, 400),
        ]);

        let tree = lifetime_scoped_descendants_from_processes(42, &processes, |pid| {
            starts.get(&pid).copied()
        })
        .expect("live root");
        assert_eq!(tree.pids, vec![42, 43, 45]);
        assert!(!tree.pids.contains(&44));
    }

    #[test]
    fn lifetime_scoped_tree_drops_unidentifiable_processes_and_their_children() {
        let processes = vec![
            crate::win32::ProcessInfo {
                pid: 42,
                parent_pid: 1,
                name: "chrome.exe".to_owned(),
            },
            crate::win32::ProcessInfo {
                pid: 43,
                parent_pid: 42,
                name: "chrome.exe".to_owned(),
            },
            crate::win32::ProcessInfo {
                pid: 44,
                parent_pid: 43,
                name: "chrome.exe".to_owned(),
            },
        ];
        let starts = HashMap::from([(42, 100), (44, 300)]);

        let tree = lifetime_scoped_descendants_from_processes(42, &processes, |pid| {
            starts.get(&pid).copied()
        })
        .expect("live root");
        assert_eq!(tree.pids, vec![42]);
    }

    #[test]
    fn listener_identity_reproof_drops_recycled_and_vanished_pids() {
        let observed = vec![(9222, 42), (9333, 43), (9444, 44)];
        let expected = HashMap::from([(42, 100), (43, 200), (44, 300)]);
        let current = HashMap::from([
            (42, 100),
            // pid 43 was recycled between the socket snapshot and reproof.
            (43, 201),
            // pid 44 vanished and is intentionally absent.
        ]);

        assert_eq!(
            retain_identity_matched_listeners(observed, &expected, |pid| {
                current.get(&pid).copied()
            }),
            vec![(9222, 42)]
        );
    }

    #[test]
    fn discovered_websocket_url_is_canonical_and_keeps_the_attested_port() {
        assert_eq!(
            canonical_discovered_websocket_url("ws://localhost:9222/devtools/browser/id", 9222),
            Some("ws://127.0.0.1:9222/devtools/browser/id".to_owned())
        );
        assert_eq!(
            canonical_discovered_websocket_url("ws://[::1]:9222/devtools/browser/id", 9222),
            Some("ws://127.0.0.1:9222/devtools/browser/id".to_owned())
        );
        assert_eq!(
            canonical_discovered_websocket_url(
                "ws://127.0.0.1:9333/devtools/browser/foreign",
                9222
            ),
            None
        );
        assert_eq!(
            canonical_discovered_websocket_url("wss://127.0.0.1:9222/devtools/browser/id", 9222),
            None
        );
        assert_eq!(
            canonical_discovered_websocket_url(
                "ws://127.0.0.1.evil.test:9222/devtools/browser/id",
                9222
            ),
            None
        );
        assert_eq!(
            canonical_discovered_websocket_url(
                "ws://[email protected]:9222/devtools/browser/id",
                9222
            ),
            None
        );
    }

    #[test]
    fn endpoint_reproof_requires_a_literal_loopback_url() {
        assert_eq!(
            literal_loopback_websocket_port("ws://127.0.0.1:9222/devtools/browser/id"),
            Some(9222)
        );
        assert_eq!(
            literal_loopback_websocket_port("ws://[::1]:9222/devtools/browser/id"),
            Some(9222)
        );
        assert_eq!(
            literal_loopback_websocket_port("ws://localhost:9222/devtools/browser/id"),
            None
        );
        assert_eq!(literal_loopback_websocket_port("ws://127.0.0.1:9222"), None);
    }

    #[test]
    fn pre_enabled_setup_reuses_one_exact_pid_port_before_consent() {
        assert_eq!(
            select_provisional_setup_port(&[9222], &[9222], true).unwrap(),
            Some(9222)
        );
        assert_eq!(
            select_provisional_setup_port(&[9222], &[9222], false).unwrap(),
            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 pre_enabled_setup_refuses_multiple_existing_exact_pid_ports() {
        assert_eq!(
            select_provisional_setup_port(&[9222, 9333], &[9222, 9333], true)
                .unwrap_err()
                .code,
            BrowserRefusalCode::BrowserBindingAmbiguous
        );
    }

    #[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));
        let probe_calls = Arc::clone(&calls);
        let endpoints = retry_empty_endpoint_discovery(4, Duration::ZERO, move || {
            let call = probe_calls.fetch_add(1, Ordering::SeqCst);
            async move {
                if call < 2 {
                    Ok(Vec::new())
                } else {
                    Ok(vec![(
                        9222,
                        "ws://127.0.0.1:9222/devtools/browser/proven".to_owned(),
                        43,
                    )])
                }
            }
        })
        .await
        .expect("retry transient empty socket snapshots");

        assert_eq!(calls.load(Ordering::SeqCst), 3);
        assert_eq!(
            endpoints,
            vec![(
                9222,
                "ws://127.0.0.1:9222/devtools/browser/proven".to_owned(),
                43,
            )]
        );
    }

    #[tokio::test]
    async fn endpoint_ownership_retries_transient_socket_snapshots() {
        let calls = Arc::new(AtomicUsize::new(0));
        let probe_calls = Arc::clone(&calls);
        let owned = retry_port_ownership(4, Duration::ZERO, 9222, move || {
            let call = probe_calls.fetch_add(1, Ordering::SeqCst);
            async move {
                if call < 2 {
                    Ok(Vec::new())
                } else {
                    Ok(vec![9222])
                }
            }
        })
        .await
        .expect("retry transient socket snapshots");

        assert!(owned);
        assert_eq!(calls.load(Ordering::SeqCst), 3);
    }

    #[tokio::test]
    async fn endpoint_ownership_exhausts_wrong_ports_and_fails_fast_on_errors() {
        let wrong_calls = Arc::new(AtomicUsize::new(0));
        let probe_calls = Arc::clone(&wrong_calls);
        let owned = retry_port_ownership(3, Duration::ZERO, 9222, move || {
            probe_calls.fetch_add(1, Ordering::SeqCst);
            async { Ok(vec![9333]) }
        })
        .await
        .expect("wrong ports are a clean ownership miss");
        assert!(!owned);
        assert_eq!(wrong_calls.load(Ordering::SeqCst), 3);

        let error_calls = Arc::new(AtomicUsize::new(0));
        let probe_calls = Arc::clone(&error_calls);
        let result = retry_port_ownership(3, Duration::ZERO, 9222, move || {
            probe_calls.fetch_add(1, Ordering::SeqCst);
            async {
                Err(BrowserRefusal::new(
                    BrowserRefusalCode::BrowserRouteUnavailable,
                    "socket inventory failed",
                ))
            }
        })
        .await;
        assert!(result.is_err());
        assert_eq!(error_calls.load(Ordering::SeqCst), 1);
    }
}