The design language that makes your AI harness better at design.
JavaScript
detect --cdp: scan a running desktop app through its DevTools port (#951) (#1037)
Paul Bakaus2a6fc4872e2c
diff --git a/crates/browser/src/attach.rs b/crates/browser/src/attach.rsnew file mode 100644index 000000000..744ec5fe7--- /dev/null+++ b/crates/browser/src/attach.rs@@ -0,0 +1,504 @@+//! `impeccable detect --cdp`: scan a page of a Chromium-based app that is+//! already running (Electron, NW.js, CEF, WebView2) through its DevTools+//! endpoint, with the URL scan's passes and output.+//!+//! The session does not own anything it touches. It never launches or closes+//! the browser, never navigates, reloads or resizes, and changes no+//! emulation. What the scan does change it puts back, on success and on+//! error ([`RESTORE_JS`]): scroll positions (the window and every scroller,+//! open shadow roots included), the videos the pixel pass paused, and the+//! style element and marker attributes that pass adds. Restoring first+//! cancels the scan's waits, so page-side work an evaluation left running+//! (one that outlived its protocol timeout) cannot move the page again. Consent and overlay hiding stay off:+//! the person seeded the state they want reviewed, and hiding part of it+//! would change what they see.+//!+//! Every evaluation runs in an isolated world ([`Browser::attach_page`]), so+//! the app's scripts never see the scan's globals, and the capture reads the+//! untouched built-ins whatever the app did to its own (#1011 without the+//! new-document prelude a URL scan relies on). That world has the timer+//! shim [`PREPARE_JS`] installs: a window hidden behind others or minimized+//! pauses `requestAnimationFrame` and throttles timers to a second or more,+//! which would stall every wait the passes make. Runtime.evaluate is not+//! subject to the page's Content-Security-Policy, so the capture works under+//! a strict CSP; a `style-src` without `'unsafe-inline'` still blocks the+//! pixel pass's hide style, as it does in a URL scan, and the pass then+//! reports no pixel verdicts.++use std::io::{Read, Write};+use std::net::ToSocketAddrs;+use std::time::Duration;++use impeccable_detect::cdp_endpoint::{is_loopback_host, CdpEndpoint};+use impeccable_detect::engines::{EngineError, ScanOptions, UrlScan};+use serde_json::Value;++use crate::cdp::{connect_tcp, Browser, Page, Viewport};+use crate::consent::ConsentReport;+use crate::overlays::OverlayReport;++const HTTP_TIMEOUT: Duration = Duration::from_secs(5);++/// One page the browser reports (`Target.getTargets`).+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct PageTarget {+ pub id: String,+ pub url: String,+ pub title: String,+}++/// The pages a person can mean: `page` targets other than DevTools windows.+pub fn page_targets(targets: &[Value]) -> Vec<PageTarget> {+ targets+ .iter()+ .filter(|t| t.get("type").and_then(Value::as_str) == Some("page"))+ .map(|t| {+ let s = |k: &str| t.get(k).and_then(Value::as_str).unwrap_or("").to_string();+ PageTarget { id: s("targetId"), url: s("url"), title: s("title") }+ })+ .filter(|t| !t.url.starts_with("devtools://"))+ .collect()+}++/// Pick the page to scan: the one `page_id` names (a page's `ws://` URL), else+/// the one whose URL or title contains `filter` (case-insensitive) or whose+/// id it is, else the only page. Anything else is an error that lists the+/// candidates, so the caller can rerun with `--target`.+pub fn pick_target(+ pages: &[PageTarget],+ filter: Option<&str>,+ page_id: Option<&str>,+ authority: &str,+) -> Result<PageTarget, String> {+ if let Some(id) = page_id {+ return pages+ .iter()+ .find(|p| p.id.eq_ignore_ascii_case(id))+ .cloned()+ .ok_or_else(|| format!("no page with id {id} is open on {authority}.{}", listing(pages)));+ }+ if pages.is_empty() {+ return Err(format!("no pages are open on {authority} to scan."));+ }+ let matched: Vec<&PageTarget> = match filter {+ Some(f) => {+ let needle = f.to_lowercase();+ pages+ .iter()+ .filter(|p| {+ p.url.to_lowercase().contains(&needle)+ || p.title.to_lowercase().contains(&needle)+ || p.id.eq_ignore_ascii_case(f)+ })+ .collect()+ }+ None => pages.iter().collect(),+ };+ match (matched.as_slice(), filter) {+ ([one], _) => Ok((*one).clone()),+ ([], Some(f)) => Err(format!(+ "no page on {authority} has a URL or title containing \"{f}\".{}",+ listing(pages)+ )),+ (many, Some(f)) => Err(format!(+ "{} pages on {authority} match \"{f}\". Rerun with a --target that names one of them (a longer part of its URL or title, or its id):{}",+ many.len(),+ listing_of(many)+ )),+ (many, None) => Err(format!(+ "{} pages are open on {authority}. Rerun with --target and part of the URL or title of the one to scan (or its id):{}",+ many.len(),+ listing_of(many)+ )),+ }+}++fn listing(pages: &[PageTarget]) -> String {+ if pages.is_empty() {+ return " No pages are open.".to_string();+ }+ format!(" Open pages:{}", listing_of(&pages.iter().collect::<Vec<_>>()))+}++fn listing_of(pages: &[&PageTarget]) -> String {+ pages+ .iter()+ .map(|p| {+ let title = if p.title.is_empty() { String::new() } else { format!(" \"{}\"", p.title) };+ format!("\n {}{title} (id {})", if p.url.is_empty() { "(no URL)" } else { &p.url }, p.id)+ })+ .collect()+}++/// The hint every failure to reach the endpoint ends with.+fn launch_hint(port: u16) -> String {+ format!(+ "Start the app with --remote-debugging-port={port} (Electron, NW.js, CEF; for WebView2 set WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS=--remote-debugging-port={port}), then run this again."+ )+}++/// Refuse a host that resolves to anything but loopback. The CLI already+/// checked the spelling; this checks where `localhost` actually points.+fn ensure_loopback(endpoint: &CdpEndpoint) -> Result<(), String> {+ if !is_loopback_host(&endpoint.host) {+ return Err(format!("--cdp only attaches to this machine, not {}", endpoint.host));+ }+ if let Ok(addrs) = endpoint.authority().to_socket_addrs() {+ if let Some(addr) = addrs.into_iter().find(|a| !a.ip().is_loopback()) {+ return Err(format!(+ "{} resolves to {}, which is not this machine; --cdp only attaches to a loopback address",+ endpoint.host,+ addr.ip()+ ));+ }+ }+ Ok(())+}++/// A tiny HTTP/1.1 GET for the DevTools discovery endpoints. Returns the+/// body of a 200 response.+fn http_get(authority: &str, path: &str) -> std::io::Result<(u16, String)> {+ let mut stream = connect_tcp(authority, HTTP_TIMEOUT)?;+ stream.set_read_timeout(Some(HTTP_TIMEOUT))?;+ stream.set_write_timeout(Some(HTTP_TIMEOUT))?;+ write!(+ stream,+ "GET {path} HTTP/1.1\r\nHost: {authority}\r\nAccept: application/json\r\nConnection: close\r\n\r\n"+ )?;+ let mut buf: Vec<u8> = Vec::new();+ let mut chunk = [0u8; 16 * 1024];+ let mut body_at: Option<usize> = None;+ let mut length: Option<usize> = None;+ loop {+ let n = match stream.read(&mut chunk) {+ Ok(0) => break,+ Ok(n) => n,+ Err(e) if buf.is_empty() => return Err(e),+ Err(_) => break,+ };+ buf.extend_from_slice(&chunk[..n]);+ if body_at.is_none() {+ if let Some(i) = buf.windows(4).position(|w| w == b"\r\n\r\n") {+ body_at = Some(i + 4);+ let head = String::from_utf8_lossy(&buf[..i]).to_ascii_lowercase();+ length = head+ .lines()+ .find_map(|l| l.strip_prefix("content-length:"))+ .and_then(|v| v.trim().parse().ok());+ }+ }+ if let (Some(at), Some(len)) = (body_at, length) {+ if buf.len() >= at + len {+ break;+ }+ }+ if buf.len() > 16 * 1024 * 1024 {+ break;+ }+ }+ let at = body_at.ok_or_else(|| std::io::Error::other("no HTTP response"))?;+ let head = String::from_utf8_lossy(&buf[..at]);+ let status = head+ .split_whitespace()+ .nth(1)+ .and_then(|s| s.parse::<u16>().ok())+ .ok_or_else(|| std::io::Error::other("no HTTP status"))?;+ let end = length.map_or(buf.len(), |l| (at + l).min(buf.len()));+ Ok((status, String::from_utf8_lossy(&buf[at..end]).into_owned()))+}++/// The browser's DevTools websocket, dialled at the endpoint the person gave+/// (the host `/json/version` writes into its URL is ignored, so a report of+/// `0.0.0.0` or a hostname never moves the connection off loopback).+pub fn browser_ws_url(endpoint: &CdpEndpoint) -> Result<String, String> {+ let authority = endpoint.authority();+ if let Some(path) = &endpoint.browser_path {+ return Ok(format!("ws://{authority}{path}"));+ }+ let (status, body) = http_get(&authority, "/json/version").map_err(|e| {+ format!("could not reach a DevTools endpoint at {authority} ({e}). {}", launch_hint(endpoint.port))+ })?;+ let not_devtools = || {+ format!(+ "{authority} answered, but not as a DevTools endpoint (GET /json/version: {}). {}",+ if status == 200 { "no webSocketDebuggerUrl".to_string() } else { format!("HTTP {status}") },+ launch_hint(endpoint.port)+ )+ };+ if status != 200 {+ return Err(not_devtools());+ }+ let ws = serde_json::from_str::<Value>(&body)+ .ok()+ .and_then(|v| v.get("webSocketDebuggerUrl").and_then(Value::as_str).map(String::from))+ .ok_or_else(not_devtools)?;+ let path = ws+ .strip_prefix("ws://")+ .or_else(|| ws.strip_prefix("wss://"))+ .and_then(|rest| rest.find('/').map(|i| rest[i..].to_string()))+ .filter(|p| p.starts_with("/devtools/browser/"))+ .ok_or_else(not_devtools)?;+ Ok(format!("ws://{authority}{path}"))+}++/// The scan's timer shim and the state it will put back, in the isolated+/// world, before any pass runs.+///+/// - `setTimeout` and `clearTimeout`: while the document is hidden, a wait is+/// a run of message tasks that ends when its time is up, since timers in a+/// hidden page fire a second or more late (and once a minute after five+/// minutes hidden). Visible, they are the native ones.+/// - `requestAnimationFrame` fires on the next frame or after 100ms,+/// whichever comes first, so a frame wait never hangs on a window that+/// paints no frames.+/// - Once [`RESTORE_JS`] sets `__impeccableAttachCancelled`, neither calls+/// anything back, so an async pass still running page-side stops at its+/// next wait instead of scrolling the restored page.+///+/// The page's own globals are untouched: these are the isolated world's.+pub const PREPARE_JS: &str = r#"(() => {+ const g = globalThis;+ if (!g.__impeccableAttachShim) {+ const nativeSetTimeout = g.setTimeout.bind(g);+ const nativeClearTimeout = g.clearTimeout.bind(g);+ const nativeRaf = g.requestAnimationFrame.bind(g);+ const live = new Map();+ let next = 0;+ const spin = (id, ms, run) => {+ const end = performance.now() + ms;+ const channel = new MessageChannel();+ channel.port1.onmessage = () => {+ if (!live.has(id)) { channel.port1.close(); return; }+ const left = end - performance.now();+ if (left <= 0) {+ live.delete(id);+ channel.port1.close();+ run();+ } else if (document.visibilityState !== 'hidden') {+ // Shown again: the native timer is prompt for the rest.+ channel.port1.close();+ live.set(id, nativeSetTimeout(() => { live.delete(id); run(); }, left));+ } else {+ channel.port2.postMessage(0);+ }+ };+ channel.port2.postMessage(0);+ };+ g.setTimeout = (cb, ms, ...args) => {+ const id = ++next;+ const wait = Math.max(0, Number(ms) || 0);+ const run = () => { if (!g.__impeccableAttachCancelled && typeof cb === 'function') cb(...args); };+ if (document.visibilityState === 'hidden') {+ live.set(id, null);+ spin(id, wait, run);+ } else {+ live.set(id, nativeSetTimeout(() => { live.delete(id); run(); }, wait));+ }+ return id;+ };+ g.clearTimeout = (id) => {+ const handle = live.get(id);+ live.delete(id);+ if (handle != null) nativeClearTimeout(handle);+ };+ g.requestAnimationFrame = (cb) => {+ let done = false;+ const fire = () => { if (!done) { done = true; if (!g.__impeccableAttachCancelled) cb(performance.now()); } };+ nativeRaf(fire);+ g.setTimeout(fire, 100);+ return 0;+ };+ g.__impeccableAttachShim = true;+ }+ const scrolled = [];+ const walk = (root) => {+ for (const el of root.querySelectorAll('*')) {+ if (el.scrollTop || el.scrollLeft) scrolled.push([el, el.scrollTop, el.scrollLeft]);+ if (el.shadowRoot) walk(el.shadowRoot);+ }+ };+ walk(document);+ g.__impeccableAttachCancelled = false;+ g.__impeccableAttach = {+ x: window.scrollX,+ y: window.scrollY,+ scrolled,+ hideStyle: !!document.getElementById('impeccable-visual-contrast-hide-style'),+ };+ return { hidden: document.visibilityState === 'hidden', scrollers: scrolled.length };+})()"#;++/// Put back what [`PREPARE_JS`] recorded: first cancel the scan's waits,+/// then every scroller at its old position (a scroller the scan moved off 0+/// back to 0), the window last, the videos the pixel pass paused+/// (`__impeccablePausedMedia`) playing again unless they have ended, and the+/// pixel pass's style element and marker attributes gone. Then the scan's+/// own globals go, so the isolated world holds no references to the page's+/// elements.+pub const RESTORE_JS: &str = r#"(() => {+ const g = globalThis;+ g.__impeccableAttachCancelled = true;+ const saved = g.__impeccableAttach;+ const out = { restored: false };+ if (saved) {+ const was = new Map(saved.scrolled.map(([el, top, left]) => [el, [top, left]]));+ const put = (el, top, left) => {+ if (el.scrollTop !== top || el.scrollLeft !== left) {+ try { el.scrollTo({ top, left, behavior: 'instant' }); } catch (e) {}+ }+ };+ const walk = (root) => {+ for (const el of root.querySelectorAll('*')) {+ const old = was.get(el);+ if (old) put(el, old[0], old[1]);+ else if (el.scrollTop || el.scrollLeft) put(el, 0, 0);+ if (el.shadowRoot) walk(el.shadowRoot);+ }+ };+ walk(document);+ window.scrollTo({ left: saved.x, top: saved.y, behavior: 'instant' });+ for (const m of g.__impeccablePausedMedia || []) {+ if (!m.paused || m.ended || !m.isConnected) continue;+ try { const p = m.play(); if (p && typeof p.catch === 'function') p.catch(() => {}); } catch (e) {}+ }+ if (!saved.hideStyle) {+ const style = document.getElementById('impeccable-visual-contrast-hide-style');+ if (style) style.remove();+ }+ out.restored = true;+ out.scroll = [window.scrollX, window.scrollY];+ out.wanted = [saved.x, saved.y];+ }+ for (const el of document.querySelectorAll('[data-impeccable-visual-contrast-target], [data-impeccable-bgclip-text]')) {+ el.removeAttribute('data-impeccable-visual-contrast-target');+ el.removeAttribute('data-impeccable-bgclip-text');+ }+ for (const key of ['__impeccableSnapshot', '__impCap', '__impIO', '__impeccableContrastRestore', '__impeccableVisualScrollSaved', '__impeccablePausedMedia', '__impeccableAttach']) {+ try { delete g[key]; } catch (e) {}+ }+ return out;+})()"#;++/// `impeccable detect --cdp`: attach, scan the chosen page as it stands, put+/// it back, detach.+pub fn detect_cdp(+ endpoint: &CdpEndpoint,+ filter: Option<&str>,+ options: &ScanOptions,+) -> Result<UrlScan, EngineError> {+ ensure_loopback(endpoint).map_err(EngineError::new)?;+ let ws = browser_ws_url(endpoint).map_err(EngineError::new)?;+ let mut browser = Browser::connect(&ws).map_err(|e| {+ EngineError::new(format!("{}. {}", e.message, launch_hint(endpoint.port)))+ })?;+ let outcome = browser+ .targets()+ .map_err(super::cdp_err)+ .and_then(|targets| {+ pick_target(&page_targets(&targets), filter, endpoint.page_id.as_deref(), &endpoint.authority())+ .map_err(EngineError::new)+ })+ .and_then(|target| scan_target(&mut browser, &target, options));+ browser.close();+ outcome+}++fn scan_target(browser: &mut Browser, target: &PageTarget, options: &ScanOptions) -> Result<UrlScan, EngineError> {+ let mut page = browser.attach_page(&target.id).map_err(super::cdp_err)?;+ let url = if target.url.is_empty() { format!("cdp-target:{}", target.id) } else { target.url.clone() };+ let scanned = page+ .evaluate_value(PREPARE_JS)+ .map_err(super::cdp_err)+ .and_then(|_| scan_attached(&mut page, &url, options));+ let restored = page.evaluate_value(RESTORE_JS);+ page.close();+ let scan = scanned?;+ // Leaving the page as found is part of the contract: a scan that could+ // not put it back fails, so automation sees it.+ let restored_ok = restored.as_ref().is_ok_and(|v| v.get("restored").and_then(Value::as_bool) == Some(true));+ if !restored_ok {+ let why = match restored {+ Err(e) => e.message,+ Ok(_) => "the recorded state was gone".to_string(),+ };+ return Err(EngineError::new(format!(+ "scanned {url} but could not put it back as it was ({why}); check its scroll position and any video it was playing."+ )));+ }+ Ok(scan)+}++/// [`super::scan_loaded`] over an attached page: its own viewport, consent and+/// overlay hiding off.+fn scan_attached(page: &mut Page<'_>, url: &str, options: &ScanOptions) -> Result<UrlScan, EngineError> {+ let (_, (width, height)) = page.viewport_metrics().map_err(super::cdp_err)?;+ let viewport = Viewport { width: width.round().max(1.0) as u32, height: height.round().max(1.0) as u32 };+ let options = ScanOptions { keep_consent_banners: true, keep_overlays: true, ..options.clone() };+ let mut consent = ConsentReport::default();+ let mut overlays = OverlayReport::default();+ let mut notes = Vec::new();+ let results = super::scan_loaded(+ page,+ url,+ &options,+ viewport,+ options.profile.as_deref(),+ None,+ &mut consent,+ &mut notes,+ &mut overlays,+ )?;+ let (findings, _) = super::results_to_findings(url, results, options.design_system.as_deref())?;+ Ok(UrlScan { findings, notes })+}++#[cfg(test)]+mod tests {+ use super::*;++ fn page(id: &str, url: &str, title: &str) -> PageTarget {+ PageTarget { id: id.into(), url: url.into(), title: title.into() }+ }++ #[test]+ fn only_pages_that_are_not_devtools_are_candidates() {+ let targets = serde_json::json!([+ { "targetId": "A", "type": "page", "url": "http://127.0.0.1:5173/", "title": "App" },+ { "targetId": "B", "type": "page", "url": "devtools://devtools/bundled/inspector.html", "title": "DevTools" },+ { "targetId": "C", "type": "service_worker", "url": "http://127.0.0.1:5173/sw.js", "title": "" },+ { "targetId": "D", "type": "iframe", "url": "https://ads.example/", "title": "" },+ ]);+ let pages = page_targets(targets.as_array().unwrap());+ assert_eq!(pages, vec![page("A", "http://127.0.0.1:5173/", "App")]);+ assert_eq!(pick_target(&pages, None, None, "127.0.0.1:9222").unwrap().id, "A");+ }++ #[test]+ fn several_pages_need_a_target() {+ let pages = vec![page("A1", "app://main/index.html", "Inbox"), page("B2", "app://main/settings.html", "Settings")];+ let err = pick_target(&pages, None, None, "127.0.0.1:9222").unwrap_err();+ assert!(err.starts_with("2 pages are open on 127.0.0.1:9222. Rerun with --target"), "{err}");+ assert!(err.contains("\n app://main/index.html \"Inbox\" (id A1)"), "{err}");+ assert!(err.contains("\n app://main/settings.html \"Settings\" (id B2)"), "{err}");+ assert_eq!(pick_target(&pages, Some("settings"), None, "x").unwrap().id, "B2");+ assert_eq!(pick_target(&pages, Some("INBOX"), None, "x").unwrap().id, "A1");+ assert_eq!(pick_target(&pages, Some("b2"), None, "x").unwrap().id, "B2");+ let none = pick_target(&pages, Some("billing"), None, "127.0.0.1:9222").unwrap_err();+ assert!(none.starts_with("no page on 127.0.0.1:9222 has a URL or title containing \"billing\". Open pages:"), "{none}");+ let many = pick_target(&pages, Some("app://main"), None, "127.0.0.1:9222").unwrap_err();+ assert!(many.starts_with("2 pages on 127.0.0.1:9222 match \"app://main\""), "{many}");+ assert_eq!(pick_target(&pages, Some("ignored"), Some("a1"), "x").unwrap().id, "A1");+ assert!(pick_target(&[], None, None, "h:1").unwrap_err().starts_with("no pages are open on h:1"));+ }++ #[test]+ fn a_browser_websocket_url_is_dialled_as_given() {+ let endpoint = CdpEndpoint {+ host: "127.0.0.1".into(),+ port: 9222,+ browser_path: Some("/devtools/browser/abc".into()),+ page_id: None,+ };+ assert_eq!(browser_ws_url(&endpoint).unwrap(), "ws://127.0.0.1:9222/devtools/browser/abc");+ }+}diff --git a/crates/browser/src/cdp.rs b/crates/browser/src/cdp.rsindex 68ac8b14f..f5e935605 100644--- a/crates/browser/src/cdp.rs+++ b/crates/browser/src/cdp.rs@@ -32,6 +32,10 @@ use tungstenite::{Message, WebSocket};const LAUNCH_TIMEOUT: Duration = Duration::from_secs(30);/// puppeteer's per-command `protocolTimeout` (180 s).const PROTOCOL_TIMEOUT: Duration = Duration::from_secs(180);+/// How long a screenshot of an attached page may take. A window that paints+/// no frames (hidden on some systems) never answers one, and the scan of+/// someone else's app should not sit on it for the protocol timeout.+const ATTACHED_SCREENSHOT_TIMEOUT: Duration = Duration::from_secs(15);#[derive(Debug, Clone)]pub struct CdpError {@@ -114,11 +118,15 @@ pub fn default_chrome_args(user_args: &[String], dangerous_no_sandbox: bool) ->}/// A running headless browser: the process, its temp profile, and the-/// browser-level CDP connection.+/// browser-level CDP connection. A browser reached with [`Browser::connect`]+/// (`detect --cdp`) belongs to someone else: it has no process or profile+/// here, and closing it only drops the connection.pub struct Browser {- child: Child,- user_data_dir: PathBuf,+ child: Option<Child>,+ user_data_dir: Option<PathBuf>,conn: Connection,+ /// The DevTools websocket URL this connection was opened on.+ ws_url: String,/// Sessions of `worker` targets whose exceptions count as page errors,/// keyed by session id → owning page session id.worker_owner: HashMap<String, String>,@@ -251,7 +259,7 @@ impl Browser {)));}};- let mut conn = match Connection::connect(&ws_url) {+ let mut conn = match Connection::connect(&ws_url, LAUNCH_TIMEOUT) {Ok(c) => c,Err(e) => {let _ = child.kill();@@ -269,40 +277,120 @@ impl Browser {// timeout, so a navigation deadline measures only the navigation.let _ = conn.send(None, "Storage.getCookies", json!({}), PROTOCOL_TIMEOUT);Ok(Browser {- child,- user_data_dir,+ child: Some(child),+ user_data_dir: Some(user_data_dir),conn,+ ws_url,worker_owner: HashMap::new(),})}+ /// Connect to a browser someone else runs, at its DevTools websocket+ /// (`/devtools/browser/<id>`). Nothing is launched, and [`Browser::close`]+ /// leaves the browser running.+ pub fn connect(ws_url: &str) -> CdpResult<Browser> {+ let conn = Connection::connect(ws_url, Duration::from_secs(10))?;+ Ok(Browser {+ child: None,+ user_data_dir: None,+ conn,+ ws_url: ws_url.to_string(),+ worker_owner: HashMap::new(),+ })+ }++ /// The DevTools websocket URL this connection uses. For a launched+ /// browser its port is the one Chrome picked for `--remote-debugging-port=0`.+ pub fn ws_url(&self) -> &str {+ &self.ws_url+ }+/// `browser.close()`: `Browser.close`, wait for exit, remove the temp- /// profile.+ /// profile. On a browser reached with [`Browser::connect`] it closes the+ /// connection and nothing else.pub fn close(mut self) {+ if self.child.is_none() {+ let _ = self.conn.ws.close(None);+ let _ = self.conn.ws.flush();+ return;+ }let _ = self.conn.send(None, "Browser.close", json!({}), Duration::from_secs(5));let deadline = Instant::now() + Duration::from_secs(5);- loop {- match self.child.try_wait() {- Ok(Some(_)) => break,- Ok(None) if Instant::now() < deadline => {- std::thread::sleep(Duration::from_millis(25))+ if let Some(child) = self.child.as_mut() {+ loop {+ match child.try_wait() {+ Ok(Some(_)) => break,+ Ok(None) if Instant::now() < deadline => {+ std::thread::sleep(Duration::from_millis(25))+ }+ _ => {+ let _ = child.kill();+ let _ = child.wait();+ break;+ }}- _ => {- let _ = self.child.kill();- let _ = self.child.wait();+ }+ }+ if let Some(dir) = self.user_data_dir.as_ref() {+ for _ in 0..10 {+ if std::fs::remove_dir_all(dir).is_ok() || !dir.exists() {break;}+ std::thread::sleep(Duration::from_millis(100));}}- for _ in 0..10 {- if std::fs::remove_dir_all(&self.user_data_dir).is_ok() || !self.user_data_dir.exists()- {- break;- }- std::thread::sleep(Duration::from_millis(100));+ }++ /// `Target.getTargets`: every target the browser knows, as CDP+ /// `TargetInfo` objects.+ pub fn targets(&mut self) -> CdpResult<Vec<Value>> {+ let res = self.conn.send(None, "Target.getTargets", json!({}), PROTOCOL_TIMEOUT)?;+ Ok(res.get("targetInfos").and_then(Value::as_array).cloned().unwrap_or_default())+ }++ /// Attach to a page someone else opened, without changing it: no new+ /// document scripts, no network or auto-attach setup, and+ /// [`Page::close`] detaches instead of closing the target. Every+ /// evaluation runs in an isolated world on the page's current document,+ /// so the page's own scripts never see the scan's globals and the scan+ /// never sees what the page did to its built-ins. A navigation ends the+ /// world, and the next evaluation fails instead of reading the new+ /// document.+ pub fn attach_page(&mut self, target_id: &str) -> CdpResult<Page<'_>> {+ let attached = self.conn.send(+ None,+ "Target.attachToTarget",+ json!({ "targetId": target_id, "flatten": true }),+ PROTOCOL_TIMEOUT,+ )?;+ let session_id = attached+ .get("sessionId")+ .and_then(Value::as_str)+ .ok_or_else(|| CdpError::new("Target.attachToTarget returned no sessionId"))?+ .to_string();+ let mut page = Page {+ browser: self,+ session_id,+ target_id: target_id.to_string(),+ frames: HashMap::new(),+ main_frame_id: String::new(),+ page_errors: Vec::new(),+ swapped: false,+ same_document_navigation: false,+ iframe_sessions: HashSet::new(),+ main_document_response: None,+ response_capture: None,+ execution_contexts: HashMap::new(),+ attached: true,+ default_world: None,+ };+ if let Err(e) = page.initialize_attached() {+ page.close();+ return Err(e);}+ Ok(page)}/// Browser-reported capture environment, independent of page script overrides.@@ -349,6 +437,8 @@ impl Browser {main_document_response: None,response_capture: None,execution_contexts: HashMap::new(),+ attached: false,+ default_world: None,};page.initialize()?;Ok(page)@@ -357,12 +447,17 @@ impl Browser {impl Drop for Browser {fn drop(&mut self) {- // Belt and braces for the error paths that skip `close()`.- if let Ok(None) = self.child.try_wait() {- let _ = self.child.kill();- let _ = self.child.wait();+ // Belt and braces for the error paths that skip `close()`. A browser+ // this process did not launch is never touched.+ if let Some(child) = self.child.as_mut() {+ if let Ok(None) = child.try_wait() {+ let _ = child.kill();+ let _ = child.wait();+ }+ }+ if let Some(dir) = self.user_data_dir.as_ref() {+ let _ = std::fs::remove_dir_all(dir);}- let _ = std::fs::remove_dir_all(&self.user_data_dir);}}@@ -385,12 +480,15 @@ struct Connection {}impl Connection {- fn connect(ws_url: &str) -> CdpResult<Connection> {+ fn connect(ws_url: &str, timeout: Duration) -> CdpResult<Connection> {let parsed = url_host_port(ws_url).ok_or_else(|| CdpError::new(format!("Unexpected DevTools endpoint: {ws_url}")))?;- let stream = TcpStream::connect(&parsed).map_err(|e| {+ let stream = connect_tcp(&parsed, timeout).map_err(|e| {CdpError::new(format!("Could not connect to the browser at {ws_url}: {e}"))})?;+ // The handshake reads under a deadline too: a port that accepts and+ // never answers (not a DevTools server) fails instead of hanging.+ let _ = stream.set_read_timeout(Some(timeout));let _ = stream.set_nodelay(true);let request = ws_url.into_client_request()@@ -586,6 +684,20 @@ impl Connection {}}+/// `TcpStream::connect` over every address `host:port` resolves to, each+/// with a deadline.+pub(crate) fn connect_tcp(host_port: &str, timeout: Duration) -> std::io::Result<TcpStream> {+ use std::net::ToSocketAddrs;+ let mut last = std::io::Error::new(std::io::ErrorKind::NotFound, "no address");+ for addr in host_port.to_socket_addrs()? {+ match TcpStream::connect_timeout(&addr, timeout) {+ Ok(s) => return Ok(s),+ Err(e) => last = e,+ }+ }+ Err(last)+}+fn url_host_port(ws_url: &str) -> Option<String> {let rest = ws_url.strip_prefix("ws://")?;let host_port = rest.split('/').next()?;@@ -629,10 +741,18 @@ pub struct Page<'a> {main_document_response: Option<Value>,response_capture: Option<crate::response_capture::ResponseCapture>,execution_contexts: HashMap<i64, String>,+ /// A page this process attached to rather than opened+ /// ([`Browser::attach_page`]): screenshots never resize its view, no+ /// evaluation counts as a user gesture, and closing detaches.+ attached: bool,+ /// Where [`Page::evaluate`] runs when set: the isolated world an+ /// attached page is scanned in.+ default_world: Option<IsolatedWorld>,}/// An opaque, document-bound isolated execution context. Never falls back to/// the page world or a newly navigated document.+#[derive(Clone)]pub struct IsolatedWorld {unique_id: String,context_id: i64,@@ -650,11 +770,12 @@ pub enum EvalOutcome {impl<'a> Page<'a> {fn send(&mut self, method: &str, params: Value) -> CdpResult<Value> {+ self.send_with_timeout(method, params, PROTOCOL_TIMEOUT)+ }++ fn send_with_timeout(&mut self, method: &str, params: Value, timeout: Duration) -> CdpResult<Value> {let sid = self.session_id.clone();- let out = self- .browser- .conn- .send(Some(&sid), method, params, PROTOCOL_TIMEOUT);+ let out = self.browser.conn.send(Some(&sid), method, params, timeout);self.pump_events();out}@@ -749,6 +870,55 @@ impl<'a> Page<'a> {Ok(())}+ /// The non-owning setup [`Browser::attach_page`] does: the frame tree+ /// with the current document's loader, Runtime for execution contexts+ /// and the page's errors, then an isolated world on that document as the+ /// default for every evaluation. Domains enabled here are this session's+ /// and end with it.+ fn initialize_attached(&mut self) -> CdpResult<()> {+ self.send("Page.enable", json!({}))?;+ let tree = self.send("Page.getFrameTree", json!({}))?;+ let Some(ft) = tree.get("frameTree") else {+ return Err(CdpError::new("the page has no frame tree"));+ };+ self.handle_frame_tree(ft, None);+ let loader = ft.pointer("/frame/loaderId").and_then(Value::as_str).unwrap_or("").to_string();+ let main = self.main_frame_id.clone();+ if let Some(frame) = self.frames.get_mut(&main) {+ frame.loader_id = loader;+ }+ self.send("Runtime.enable", json!({}))?;+ let world = self.create_isolated_world()?;+ self.default_world = Some(world);+ Ok(())+ }++ /// Whether this page was attached to ([`Browser::attach_page`]) rather+ /// than opened.+ pub fn is_attached(&self) -> bool {+ self.attached+ }++ /// `Page.getLayoutMetrics`: the visual viewport's document position and+ /// size, `(x, y, width, height)` in CSS pixels, and the layout+ /// viewport's size.+ pub fn viewport_metrics(&mut self) -> CdpResult<((f64, f64, f64, f64), (f64, f64))> {+ let res = self.send("Page.getLayoutMetrics", json!({}))?;+ let num = |v: Option<&Value>, k: &str| v.and_then(|v| v.get(k)).and_then(Value::as_f64);+ let visual = res.get("cssVisualViewport").or_else(|| res.get("visualViewport"));+ let layout = res.get("cssLayoutViewport").or_else(|| res.get("layoutViewport"));+ let missing = || CdpError::new("Page.getLayoutMetrics returned no viewport");+ Ok((+ (+ num(visual, "pageX").ok_or_else(missing)?,+ num(visual, "pageY").ok_or_else(missing)?,+ num(visual, "clientWidth").ok_or_else(missing)?,+ num(visual, "clientHeight").ok_or_else(missing)?,+ ),+ (num(layout, "clientWidth").ok_or_else(missing)?, num(layout, "clientHeight").ok_or_else(missing)?),+ ))+ }+fn handle_frame_tree(&mut self, tree: &Value, parent: Option<String>) {let Some(frame) = tree.get("frame") else {return;@@ -1413,7 +1583,13 @@ impl<'a> Page<'a> {/// `page.evaluate(<expression string>)`: `Runtime.evaluate` with/// `awaitPromise` + `returnByValue`, in the main world.+ /// On an attached page it runs in the page's isolated world instead+ /// ([`Browser::attach_page`]).pub fn evaluate(&mut self, expression: &str) -> CdpResult<EvalOutcome> {+ if let Some(world) = self.default_world.clone() {+ self.validate_world(&world)?;+ return self.evaluate_with_context(expression, Some(&world.unique_id));+ }self.evaluate_with_context(expression, None)}@@ -1432,7 +1608,9 @@ impl<'a> Page<'a> {} else {expression};- let mut params = json!({"expression":expression,"returnByValue":true,"awaitPromise":true,"userGesture":true});+ // An attached page keeps its own user-activation state: a gesture+ // granted here would outlive the scan (autoplay, popups, fullscreen).+ let mut params = json!({"expression":expression,"returnByValue":true,"awaitPromise":true,"userGesture":!self.attached});if let Some(id) = unique_context {params["uniqueContextId"] = json!(id);}@@ -1515,15 +1693,20 @@ impl<'a> Page<'a> {(y, height)};let round = |v: f64| impeccable_core::js::math_round(v);- let res = self.send(+ let timeout = if self.attached { ATTACHED_SCREENSHOT_TIMEOUT } else { PROTOCOL_TIMEOUT };+ let res = self.send_with_timeout("Page.captureScreenshot",json!({"format": "png","optimizeForSpeed": false,"fromSurface": true,"clip": { "x": round(x), "y": round(y), "width": round(width), "height": round(height), "scale": 1 },- "captureBeyondViewport": true,+ // A beyond-viewport capture lays the page out at the size of+ // the clip for the shot, which an attached app's window would+ // show: it reads what is on screen instead.+ "captureBeyondViewport": !self.attached,}),+ timeout,)?;Ok(res.get("data")@@ -1556,7 +1739,7 @@ impl<'a> Page<'a> {"quality": quality.min(100),"fromSurface": true,"clip": { "x": x, "y": y, "width": width.round(), "height": height.round(), "scale": 1 },- "captureBeyondViewport": true,+ "captureBeyondViewport": !self.attached,}),)?;Ok(res@@ -1624,15 +1807,25 @@ impl<'a> Page<'a> {}/// `page.close()`: `Target.closeTarget`, errors swallowed like the JS- /// `page.close().catch(() => {})`.+ /// `page.close().catch(() => {})`. An attached page is detached from+ /// instead, and stays open.pub fn close(self) {- let target_id = self.target_id.clone();- let _ = self.browser.conn.send(- None,- "Target.closeTarget",- json!({ "targetId": target_id }),- Duration::from_secs(10),- );+ if self.attached {+ let _ = self.browser.conn.send(+ None,+ "Target.detachFromTarget",+ json!({ "sessionId": self.session_id }),+ Duration::from_secs(10),+ );+ } else {+ let target_id = self.target_id.clone();+ let _ = self.browser.conn.send(+ None,+ "Target.closeTarget",+ json!({ "targetId": target_id }),+ Duration::from_secs(10),+ );+ }// Detached sessions may keep queued events; drop anything stale.self.browser.conn.events.clear();// Interception (origin-scoped auth) dies with the page; a shareddiff --git a/crates/browser/src/lib.rs b/crates/browser/src/lib.rsindex 150f68d80..7e9940a68 100644--- a/crates/browser/src/lib.rs+++ b/crates/browser/src/lib.rs@@ -23,6 +23,10 @@//! ([`overlays`]), so every pass and the screenshot see the page a visitor//! sees once they dismiss them.//!+//! `detect --cdp` ([`attach`]) runs the same passes over a page of an app+//! that is already running, attached through its DevTools port instead of+//! loaded, and leaves that page as it found it.+//!//! Two entry points serve measurement work rather than the CLI.//! [`detect_url_evidence`] runs the same scan and also returns what a//! reviewer needs to check the findings (the captures and hit-test answers,@@ -30,6 +34,7 @@//! passes over a recorded capture with no browser, so a rule change can be//! measured against saved pages.+pub mod attach;pub mod cdp;pub mod consent;pub mod overlays;@@ -118,6 +123,15 @@ impl UrlEngine for BrowserEngine {detect_url_impl(self, url, options, "networkidle0", 0, None)}+ fn detect_cdp_scan(+ &self,+ endpoint: &impeccable_detect::cdp_endpoint::CdpEndpoint,+ target: Option<&str>,+ options: &ScanOptions,+ ) -> Result<UrlScan, EngineError> {+ attach::detect_cdp(endpoint, target, options)+ }+fn open_shared(&self) -> Option<Box<dyn SharedBrowser + '_>> {Some(Box::new(SharedBrowserHandle {engine: self,@@ -1107,7 +1121,7 @@ fn scan_page_inner(settle_ms: u64,viewport: Viewport,profile: Option<&DetectorProfile>,- mut evidence: Option<(&mut Evidence, &EvidenceRequest)>,+ evidence: Option<(&mut Evidence, &EvidenceRequest)>,consent: &mut ConsentReport,notes: &mut Vec<String>,overlays: &mut OverlayReport,@@ -1131,7 +1145,24 @@ fn scan_page_inner(std::thread::sleep(Duration::from_millis(settle_ms))});}+ scan_loaded(page, url, options, viewport, profile, evidence, consent, notes, overlays)+}+/// Every pass over a page that is already showing what is to be scanned: a+/// URL scan's freshly loaded page, or an attached app's page as it stands+/// ([`attach`]). `viewport` is the page's viewport size.+#[allow(clippy::too_many_arguments)]+fn scan_loaded(+ page: &mut Page<'_>,+ url: &str,+ options: &ScanOptions,+ viewport: Viewport,+ profile: Option<&DetectorProfile>,+ mut evidence: Option<(&mut Evidence, &EvidenceRequest)>,+ consent: &mut ConsentReport,+ notes: &mut Vec<String>,+ overlays: &mut OverlayReport,+) -> Result<Vec<RawResult>, EngineError> {// A challenge or error page is not the site: refuse to report on it. Nor// is a consent wall, unless the scan keeps the banners: then the banner// is what the caller asked to read.@@ -1361,8 +1392,27 @@ fn scan_page_inner()}).map_err(cdp_err)?;- let (mut visual, superseded) =- run_visual_contrast_fallback(page, &analyses, &serialized_groups, viewport, profile, url)?;+ // A hidden window paints no frames, and a screenshot of it can wait for+ // one that never comes: an attached page skips the pixel reads while it+ // is hidden, and they stop if one stalls. What they would have read+ // keeps the element pass's verdict, as advisory.+ let pixels_off = page.is_attached()+ && page+ .evaluate_value("document.visibilityState === 'hidden'")+ .ok()+ .and_then(|v| v.as_bool())+ .unwrap_or(false);+ let (mut visual, superseded, stalled) =+ run_visual_contrast_fallback(page, &analyses, &serialized_groups, viewport, profile, url, pixels_off)?;+ if pixels_off {+ notes.push(format!(+ "Capture note: {url} was hidden (minimized, or a background tab or window), so the pixel pass read nothing there. Bring it on screen, focused or not, and scan again for those contrast verdicts."+ ));+ } else if let Some(why) = stalled {+ notes.push(format!(+ "Capture note: the pixel pass on {url} stopped when a screenshot stalled ({why}). Bring the window on screen and scan again for the contrast verdicts it did not read."+ ));+ }settle_handed_over(&mut results, &superseded, |r| {repeated_match(&base, r.selector.as_deref()?, r.scan_el?)});@@ -1993,6 +2043,13 @@ fn analysis_findings(/// target)`: the JS post-processing of the analytic/canvas analyses/// (`analyzeVisualContrast`, computed natively in [`snapshot_engine`]) plus the/// screenshot pixel fallback for candidates the analyses left unresolved.+///+/// `skip_pixels` leaves out the screenshot reads (an attached page that is+/// hidden). On an attached page a screenshot that times out+/// ([`is_screenshot_stall`]) ends the reads instead of the scan, and the+/// third value says why; any other error (the document navigated, the+/// connection closed) still fails the scan.+#[allow(clippy::too_many_arguments)]fn run_visual_contrast_fallback(page: &mut Page<'_>,browser_analyses: &[Value],@@ -2000,7 +2057,8 @@ fn run_visual_contrast_fallback(viewport: Viewport,profile: Option<&DetectorProfile>,target: &str,-) -> Result<(Vec<RawResult>, Vec<CandidateKey>), EngineError> {+ skip_pixels: bool,+) -> Result<(Vec<RawResult>, Vec<CandidateKey>, Option<String>), EngineError> {// Text the element pass hands over rather than scores (see// `visual::routed_reason`): its element verdict does not keep the pixels// from reading it, and the pixels' verdict replaces that one.@@ -2046,6 +2104,7 @@ fn run_visual_contrast_fallback(.collect();let filtered: Vec<&Value> = candidates.iter()+ .filter(|_| !skip_pixels).filter(|c| {let sel = c.get("selector").and_then(Value::as_str);(!existing_low_contrast@@ -2065,13 +2124,18 @@ fn run_visual_contrast_fallback(// say nothing than measure that. Playing media is the one moving thing// a scan can hold still without changing what the page shows: a paused// video still paints the frame the visitor is looking at.- let _ = page.evaluate(- "document.querySelectorAll('video').forEach(v => { try { v.pause(); } catch (e) {} })",- );+ // An attached app's page gets back the videos this paused, and only+ // those ([`attach::RESTORE_JS`]).+ let _ = page.evaluate(if page.is_attached() {+ "(() => { const paused = globalThis.__impeccablePausedMedia || (globalThis.__impeccablePausedMedia = []); document.querySelectorAll('video').forEach(v => { try { if (!v.paused) { v.pause(); paused.push(v); } } catch (e) {} }); })()"+ } else {+ "document.querySelectorAll('video').forEach(v => { try { v.pause(); } catch (e) {} })"+ });}let mut routed_spent = std::time::Duration::ZERO;let mut routed_misses = 0usize;let mut pixel_pairs: Vec<String> = Vec::new();+ let mut stalled: Option<String> = None;for candidate in filtered {let sel = candidate.get("selector").and_then(Value::as_str);// A read the first budget's rules would not have made.@@ -2084,7 +2148,7 @@ fn run_visual_contrast_fallback(}let started = std::time::Instant::now();let mut measured = false;- let result = step_findings(profile, "visual-contrast", "pixel-diff", target, || {+ let read = step_findings(profile, "visual-contrast", "pixel-diff", target, || {let m = screenshot_contrast::measure_visual_contrast_candidate(page,candidate,@@ -2104,7 +2168,15 @@ fn run_visual_contrast_fallback(}).unwrap_or_default(),)- })?;+ });+ let result = match read {+ Ok(r) => r,+ Err(e) if page.is_attached() && is_screenshot_stall(&e.message) => {+ stalled = Some(e.message);+ break;+ }+ Err(e) => return Err(e),+ };if extra {let spent = started.elapsed();routed_spent += spent;@@ -2130,7 +2202,14 @@ fn run_visual_contrast_fallback(}),);}- Ok((findings, superseded))+ Ok((findings, superseded, stalled))+}++/// Whether a pixel read failed because its screenshot timed out (a window+/// that paints no frames), as opposed to a page that navigated or a+/// connection that closed.+fn is_screenshot_stall(message: &str) -> bool {+ message.starts_with("Page.captureScreenshot timed out")}/// The colour pair a pixel-pass finding reports: the candidate's ink, its@@ -2177,6 +2256,16 @@ fn truthy(v: Option<&Value>) -> bool {mod tests {use super::*;+ #[test]+ fn only_a_screenshot_timeout_is_a_stall() {+ assert!(is_screenshot_stall(+ "Page.captureScreenshot timed out. Increase the 'protocolTimeout' setting in launch/connect calls for a higher timeout if needed."+ ));+ assert!(!is_screenshot_stall("isolated capture context was destroyed or document changed"));+ assert!(!is_screenshot_stall("Protocol error: connection closed (IO error)"));+ assert!(!is_screenshot_stall("Runtime.evaluate timed out. Increase the 'protocolTimeout' setting"));+ }+#[test]fn a_routed_pixel_pair_reports_once_per_page() {let link = |text: &str| json!({"selector": "a", "text": text, "textColor": {"r": 51.0, "g": 51.0, "b": 51.0, "a": 1.0}});diff --git a/crates/browser/src/screenshot_contrast.rs b/crates/browser/src/screenshot_contrast.rsindex 5bc9854cc..21472e805 100644--- a/crates/browser/src/screenshot_contrast.rs+++ b/crates/browser/src/screenshot_contrast.rs@@ -438,6 +438,13 @@ pub fn clip_beyond_content(clip: &Clip, content: (f64, f64)) -> bool {clip.y + clip.height > height + 4.0 || clip.x >= width}+/// Whether `clip` lies inside `view` (`x, y, width, height`, capture+/// coordinates), allowing the rounding a clip carries.+fn clip_within(clip: &Clip, view: (f64, f64, f64, f64)) -> bool {+ let (x, y, w, h) = view;+ clip.x >= x - 1.0 && clip.y >= y - 1.0 && clip.x + clip.width <= x + w + 1.0 && clip.y + clip.height <= y + h + 1.0+}+/// For a clip past the content box, scroll its element into view and return/// the candidate with the clip measured there. `None` leaves the page as it/// was: nothing moved, or nothing to move.@@ -448,9 +455,18 @@ fn bring_into_view(viewport_width: f64,origin_x: f64,) -> Option<(Value, Clip)> {- let content = page.content_size().ok()?;- if !clip_beyond_content(clip, content) {- return None;+ // An attached page is read as it is on screen (no beyond-viewport+ // capture), so a clip outside the visual viewport needs bringing in too.+ let off_screen = page.is_attached()+ && page+ .viewport_metrics()+ .ok()+ .is_some_and(|((vx, vy, vw, vh), _)| !clip_within(clip, (vx - origin_x, vy, vw, vh)));+ if !off_screen {+ let content = page.content_size().ok()?;+ if !clip_beyond_content(clip, content) {+ return None;+ }}let selector = candidate.get("selector")diff --git a/crates/browser/tests/cdp_attach.rs b/crates/browser/tests/cdp_attach.rsnew file mode 100644index 000000000..6d6d67fd1--- /dev/null+++ b/crates/browser/tests/cdp_attach.rs@@ -0,0 +1,427 @@+//! `impeccable detect --cdp`: attach to a browser someone else runs, scan one+//! of its pages as it stands, and leave everything as found.+//!+//! Each test launches the engine's own headless Chrome (which listens on a+//! DevTools port, as a desktop app started with `--remote-debugging-port`+//! does), opens the fixture app in it as an outside client would, seeds some+//! state, then attaches through [`impeccable_browser::attach::detect_cdp`]+//! like the CLI. The checks read the page back over a raw CDP connection, in+//! the page's own world: same document (no navigation, no reload), same+//! scroll positions, no node or global the scan added, no user activation+//! granted, and the browser and both pages still alive.+//!+//! The fixture replaces the built-ins a capture uses (`Map`, `Array.from`),+//! so the scan must reach the page through its isolated world, and one copy+//! of it runs under a strict meta CSP (scripts and styles from its own+//! origin only).+//!+//! Skips cleanly with no installed browser.++#[path = "support/http.rs"]+mod http;++use std::collections::HashMap;+use std::net::TcpStream;+use std::time::{Duration, Instant};++use impeccable_browser::{attach, cdp::Browser, discovery};+use impeccable_detect::cdp_endpoint::CdpEndpoint;+use impeccable_detect::engines::ScanOptions;+use serde_json::{json, Value};+use tungstenite::stream::MaybeTlsStream;+use tungstenite::{Message, WebSocket};++const PAGE: &str = r##"<!doctype html>+<html lang="en"><head><meta charset="utf-8">+CSP+<title>Fixture App</title>+<link rel="stylesheet" href="/app.css">+<script src="/app.js"></script>+</head><body>+<main>+ <h1>Inbox</h1>+ <p class="tiny">Fine print set far too small for anyone to read comfortably.</p>+ <p class="faint">Faint grey copy on white that fails contrast for body text.</p>+ <div id="list">LIST<div class="vector-panel"><svg viewBox="0 0 420 96" aria-hidden="true"><rect width="420" height="96" fill="#f5f2ea"/></svg><p>Archived threads on pale artwork</p></div></div>+ <div class="spacer"></div>+ <div class="vector-panel"><svg viewBox="0 0 420 96" aria-hidden="true"><rect width="420" height="96" fill="#f5f2ea"/></svg><p>Office hours on pale artwork</p></div>+</main>+</body></html>+"##;++const CSS: &str = "body { margin: 0; font: 16px/1.5 Georgia, serif; color: #222; background: #fff; }+main { padding: 24px; }+.tiny { font-size: 8px; }+.faint { color: #d4d4d4; }+#list { height: 160px; overflow: auto; border: 1px solid #ccc; }+#list p { margin: 0; padding: 8px; }+.spacer { height: 2400px; }+/* Text over inline vector artwork: the element pass cannot read the paint+ under it, so the pixel pass measures it, once inside the list's scroller+ and once below the window's fold. */+.vector-panel { position: relative; isolation: isolate; width: 420px; height: 96px; margin: 24px 0 0; background: #1d2330 url(\"data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='16' height='16'><rect width='16' height='16' fill='%231d2330'/><circle cx='8' cy='8' r='3' fill='%23262d3b'/></svg>\") repeat; }+.vector-panel svg { position: absolute; left: 0; top: 0; z-index: 0; display: block; width: 420px; height: 96px; }+.vector-panel p { position: relative; z-index: 1; margin: 0; padding: 24px; width: 372px; font-size: 16px; line-height: 1.6; color: #fdfdfd; }+";++/// Counts loads (a reload would show), notes when the pixel pass's hide+/// style arrives (so a test knows the pass ran before it checks the style+/// is gone), and breaks the built-ins a capture in the page's own world+/// would use.+const JS: &str = "sessionStorage.loads = String(Number(sessionStorage.loads || 0) + 1);+new MutationObserver((records) => {+ for (const r of records) for (const n of r.addedNodes) {+ if (n.id === 'impeccable-visual-contrast-hide-style') document.documentElement.dataset.sawHideStyle = 'yes';+ }+}).observe(document.documentElement, { childList: true, subtree: true });+window.Map = function BrokenMap() { throw new Error('page Map'); };+Array.from = function () { return []; };+";++fn list_html() -> String {+ (1..=40).map(|i| format!("<p>Message {i}</p>")).collect()+}++/// The strict policy: scripts and styles from the page's own origin only,+/// so neither an inline script nor an inline style element the scan adds+/// can run or apply.+const STRICT_CSP: &str = r#"<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; style-src 'self'">"#;++/// The fixture at `/` with no policy, so the pixel pass's hide style+/// applies, and at `/strict` under [`STRICT_CSP`].+fn serve_app() -> String {+ let open = PAGE.replace("LIST", &list_html()).replace("CSP\n", "");+ let strict = PAGE.replace("LIST", &list_html()).replace("CSP", STRICT_CSP);+ http::serve(move |path| match path {+ "/" => Some(("text/html; charset=utf-8", open.clone().into_bytes())),+ "/strict" => Some(("text/html; charset=utf-8", strict.clone().into_bytes())),+ "/app.css" => Some(("text/css", CSS.as_bytes().to_vec())),+ "/app.js" => Some(("text/javascript", JS.as_bytes().to_vec())),+ _ => None,+ })+}++fn launch() -> Option<Browser> {+ let env: HashMap<String, String> = std::env::vars().collect();+ let Ok(exe) = discovery::find_browser(&env) else {+ eprintln!("skip: no installed browser found");+ return None;+ };+ match Browser::launch(&exe, &[], false) {+ Ok(b) => Some(b),+ Err(e) => {+ eprintln!("skip: could not launch browser: {}", e.message);+ None+ }+ }+}++fn port_of(browser: &Browser) -> u16 {+ let rest = browser.ws_url().strip_prefix("ws://127.0.0.1:").expect("ws url");+ rest.split('/').next().unwrap().parse().unwrap()+}++fn endpoint(port: u16) -> CdpEndpoint {+ CdpEndpoint { host: "127.0.0.1".into(), port, browser_path: None, page_id: None }+}++/// A plain CDP client: the test plays the app (and its owner), not the engine.+struct Raw {+ ws: WebSocket<MaybeTlsStream<TcpStream>>,+ next: u64,+}++impl Raw {+ fn connect(ws_url: &str) -> Raw {+ let (ws, _) = tungstenite::connect(ws_url).expect("raw connect");+ if let MaybeTlsStream::Plain(s) = ws.get_ref() {+ s.set_read_timeout(Some(Duration::from_secs(30))).unwrap();+ }+ Raw { ws, next: 0 }+ }++ fn call(&mut self, session: Option<&str>, method: &str, params: Value) -> Value {+ self.try_call(session, method, params).unwrap_or_else(|e| panic!("{method}: {e}"))+ }++ fn try_call(&mut self, session: Option<&str>, method: &str, params: Value) -> Result<Value, Value> {+ self.next += 1;+ let id = self.next;+ let mut msg = json!({ "id": id, "method": method, "params": params });+ if let Some(s) = session {+ msg["sessionId"] = json!(s);+ }+ self.ws.send(Message::Text(msg.to_string().into())).unwrap();+ loop {+ let Message::Text(text) = self.ws.read().expect("raw read") else { continue };+ let v: Value = serde_json::from_str(&text).unwrap();+ if v.get("id").and_then(Value::as_u64) == Some(id) {+ return match v.get("error") {+ Some(e) => Err(e.clone()),+ None => Ok(v["result"].clone()),+ };+ }+ }+ }++ /// Evaluate in the page's own world, without a user gesture.+ fn eval(&mut self, target: &str, expression: &str) -> Value {+ self.try_eval(target, expression).unwrap_or_else(|e| panic!("page threw: {e}"))+ }++ /// [`Raw::eval`], with a page exception or a lost context as an error.+ fn try_eval(&mut self, target: &str, expression: &str) -> Result<Value, Value> {+ let session = self.call(None, "Target.attachToTarget", json!({ "targetId": target, "flatten": true }));+ let session = session["sessionId"].as_str().unwrap().to_string();+ let out = self.try_call(+ Some(&session),+ "Runtime.evaluate",+ json!({ "expression": expression, "returnByValue": true, "awaitPromise": true }),+ );+ self.call(None, "Target.detachFromTarget", json!({ "sessionId": session }));+ let out = out?;+ match out.get("exceptionDetails") {+ Some(e) => Err(e.clone()),+ None => Ok(out["result"]["value"].clone()),+ }+ }++ fn pages(&mut self) -> Vec<Value> {+ let all = self.call(None, "Target.getTargets", json!({}));+ all["targetInfos"]+ .as_array()+ .unwrap()+ .iter()+ .filter(|t| t["type"] == "page")+ .cloned()+ .collect()+ }++ /// Open `url` in a new tab and wait until it has loaded. The tab starts+ /// on `about:blank`, which is already `complete`, so the wait also+ /// checks that the fixture is the document.+ fn open(&mut self, url: &str, background: bool) -> String {+ let created = self.call(None, "Target.createTarget", json!({ "url": url, "background": background }));+ let target = created["targetId"].as_str().unwrap().to_string();+ let started = Instant::now();+ let loaded = format!("location.href === {} && document.readyState === 'complete' && !!document.getElementById('list')", json!(url));+ while self.try_eval(&target, &loaded).ok() != Some(json!(true)) {+ assert!(started.elapsed() < Duration::from_secs(30), "page never loaded");+ std::thread::sleep(Duration::from_millis(100));+ }+ target+ }+}++/// What the checks compare before and after the scan, all read in the+/// page's own world.+const STATE_JS: &str = r#"(() => {+ const list = document.getElementById('list');+ return {+ href: location.href,+ loads: sessionStorage.loads,+ navigations: performance.getEntriesByType('navigation').length,+ scroll: [window.scrollX, window.scrollY],+ list: list.scrollTop,+ nodes: document.getElementsByTagName('*').length,+ injected: document.querySelectorAll('#impeccable-visual-contrast-hide-style, [data-impeccable-visual-contrast-target], [data-impeccable-bgclip-text], style:not([data-app])').length,+ globals: Object.getOwnPropertyNames(window).filter(k => /^__imp/i.test(k)),+ activated: navigator.userActivation ? navigator.userActivation.hasBeenActive : false,+ width: window.innerWidth,+ height: window.innerHeight,+ dpr: window.devicePixelRatio,+ };+})()"#;++const SEED_JS: &str =+ "(() => { document.getElementById('list').scrollTop = 137; window.scrollTo(0, 411); return [window.scrollY, document.getElementById('list').scrollTop]; })()";++/// Two muted videos fed from a canvas (no codec needed): `#app-paused`,+/// which the app paused before the scan, and `#playing`.+const MEDIA_JS: &str = r#"(async () => {+ const canvas = document.createElement('canvas');+ canvas.width = 32; canvas.height = 32;+ const ctx = canvas.getContext('2d');+ let n = 0;+ setInterval(() => { ctx.fillStyle = n++ % 2 ? '#123' : '#456'; ctx.fillRect(0, 0, 32, 32); }, 50);+ const make = (id) => {+ const v = document.createElement('video');+ v.id = id; v.muted = true; v.width = 32; v.height = 32;+ v.srcObject = canvas.captureStream(20);+ document.querySelector('main').prepend(v);+ return v;+ };+ const paused = make('app-paused');+ const playing = make('playing');+ await paused.play(); await playing.play();+ paused.pause();+ playing.addEventListener('pause', () => { document.documentElement.dataset.sawPause = 'yes'; });+ return [paused.paused, playing.paused];+})()"#;++const MEDIA_STATE_JS: &str =+ "[document.getElementById('app-paused').paused, document.getElementById('playing').paused]";++fn ids(findings: &[impeccable_core::findings::Finding]) -> Vec<&str> {+ findings.iter().map(|f| f.antipattern.as_str()).collect()+}++#[test]+fn attaches_scans_and_leaves_the_page_as_found() {+ let Some(browser) = launch() else { return };+ let port = port_of(&browser);+ let origin = serve_app();+ let url = format!("{origin}/");+ let mut raw = Raw::connect(browser.ws_url());+ let target = raw.open(&url, false);+ assert_eq!(raw.eval(&target, MEDIA_JS), json!([true, false]));+ assert_eq!(raw.eval(&target, SEED_JS), json!([411, 137]));+ let before = raw.eval(&target, STATE_JS);+ assert_eq!(before["globals"], json!([]));++ // The launch's own about:blank tab is open too, so a bare --cdp is+ // ambiguous and names both pages.+ let ambiguous = attach::detect_cdp(&endpoint(port), None, &ScanOptions::default()).unwrap_err();+ assert!(ambiguous.message.starts_with(&format!("2 pages are open on 127.0.0.1:{port}. Rerun with --target")), "{}", ambiguous.message);+ assert!(ambiguous.message.contains(&format!("\n {url} \"Fixture App\" (id {target})")), "{}", ambiguous.message);+ assert!(ambiguous.message.contains("\n about:blank"), "{}", ambiguous.message);+ let none = attach::detect_cdp(&endpoint(port), Some("billing"), &ScanOptions::default()).unwrap_err();+ assert!(none.message.contains("has a URL or title containing \"billing\""), "{}", none.message);++ let scan = attach::detect_cdp(&endpoint(port), Some("fixture app"), &ScanOptions::default())+ .unwrap_or_else(|e| panic!("scan failed: {}", e.message));+ let found = ids(&scan.findings);+ assert!(found.contains(&"tiny-text"), "{found:?}");+ assert!(found.contains(&"low-contrast"), "{found:?}");+ assert!(scan.findings.iter().all(|f| f.file == url), "every finding names the page");+ // The pixel pass read the text inside the list's scroller, which it had+ // to scroll into view: an attached page is read as it is on screen.+ assert!(+ scan.findings.iter().any(|f| f.snippet.starts_with("pixel contrast ")+ && f.extras.get("selector").and_then(Value::as_str) == Some("#list > div.vector-panel > p")),+ "{found:?}"+ );+ assert!(scan.notes.is_empty(), "{:?}", scan.notes);++ // Picking by id, as the listing offers, works too.+ let by_id = attach::detect_cdp(&endpoint(port), Some(&target), &ScanOptions::default()).unwrap();+ assert_eq!(ids(&by_id.findings), found);++ let after = raw.eval(&target, STATE_JS);+ assert_eq!(after, before, "the page is as the scan found it");+ // The pixel pass ran (it added its hide style, and paused the playing+ // video), and its style is gone. The video it paused plays again; the+ // one the app had paused stays paused.+ assert_eq!(raw.eval(&target, "document.documentElement.dataset.sawHideStyle"), json!("yes"));+ assert_eq!(raw.eval(&target, "document.documentElement.dataset.sawPause"), json!("yes"));+ assert_eq!(raw.eval(&target, MEDIA_STATE_JS), json!([true, false]));+ let pages: Vec<String> = raw.pages().iter().map(|p| p["targetId"].as_str().unwrap().to_string()).collect();+ assert_eq!(pages.len(), 2, "no page opened or closed: {pages:?}");+ assert!(pages.contains(&target));+ let version = raw.call(None, "Browser.getVersion", json!({}));+ assert!(version["product"].as_str().is_some_and(|p| !p.is_empty()), "browser still answers");+ browser.close();+}++/// An attached scan reports the rules a URL scan of the same page reports:+/// the attach mode runs the same passes.+#[test]+fn an_attached_scan_reports_what_a_url_scan_reports() {+ let Some(browser) = launch() else { return };+ let port = port_of(&browser);+ let origin = serve_app();+ let url = format!("{origin}/");+ let mut raw = Raw::connect(browser.ws_url());+ raw.open(&url, false);+ let attached = attach::detect_cdp(&endpoint(port), Some(&origin), &ScanOptions::default()).unwrap();+ browser.close();+ let engine = impeccable_browser::BrowserEngine::from_process_env();+ let options = ScanOptions { viewport: None, ..ScanOptions::default() };+ let loaded = impeccable_detect::engines::UrlEngine::detect_url_scan(&engine, &url, &options).unwrap();+ // The launch's headless window is smaller than a URL scan's 1280x800,+ // so compare the rules, not the geometry each one quotes.+ let mut a = ids(&attached.findings);+ let mut b = ids(&loaded.findings);+ a.sort();+ a.dedup();+ b.sort();+ b.dedup();+ assert_eq!(a, b);+}++/// A tab in the background is hidden: no frames, timers a second late. The+/// scan still finishes, in about the time a visible one takes, skips the+/// screenshot reads, and still leaves the page as found. This one also runs under the strict CSP, which+/// the capture is not subject to.+#[test]+fn a_hidden_page_still_scans() {+ let Some(browser) = launch() else { return };+ let port = port_of(&browser);+ let origin = serve_app();+ let url = format!("{origin}/strict");+ let mut raw = Raw::connect(browser.ws_url());+ let target = raw.open(&url, true);+ assert_eq!(raw.eval(&target, "document.visibilityState"), json!("hidden"));+ assert_eq!(raw.eval(&target, SEED_JS), json!([411, 137]));+ let before = raw.eval(&target, STATE_JS);+ let started = Instant::now();+ let scan = attach::detect_cdp(&endpoint(port), Some("fixture"), &ScanOptions::default())+ .unwrap_or_else(|e| panic!("scan failed: {}", e.message));+ let took = started.elapsed();+ assert!(took < Duration::from_secs(60), "hidden scan took {took:?}");+ assert!(ids(&scan.findings).contains(&"tiny-text"), "{:?}", ids(&scan.findings));+ // A hidden page paints no frames, and on Linux a screenshot of it waits+ // for one forever: the pixel pass skips it and says so.+ assert!(!scan.findings.iter().any(|f| f.snippet.starts_with("pixel contrast ")));+ assert_eq!(+ scan.notes,+ vec![format!("Capture note: {url} was hidden (minimized, or a background tab or window), so the pixel pass read nothing there. Bring it on screen, focused or not, and scan again for those contrast verdicts.")]+ );+ assert_eq!(raw.eval(&target, STATE_JS), before);+ assert_eq!(raw.eval(&target, "document.visibilityState"), json!("hidden"));+ browser.close();+}++/// An evaluation that outlives its protocol timeout keeps running in the+/// page. Restoring cancels the scan's waits first, so a pass still running+/// there stops at its next wait instead of scrolling the restored page.+#[test]+fn work_left_running_stops_when_the_page_is_restored() {+ let Some(browser) = launch() else { return };+ let origin = serve_app();+ let url = format!("{origin}/");+ let mut raw = Raw::connect(browser.ws_url());+ let target = raw.open(&url, false);+ assert_eq!(raw.eval(&target, SEED_JS), json!([411, 137]));++ let mut attached = Browser::connect(browser.ws_url()).expect("connect");+ let mut page = attached.attach_page(&target).expect("attach");+ page.evaluate_value(attach::PREPARE_JS).expect("prepare");+ // A sweep the client stopped waiting for: it scrolls on every wait.+ page.evaluate_value(+ "(() => { (async () => { for (let y = 0; y < 5000; y += 40) { window.scrollTo({ top: y, behavior: 'instant' }); await new Promise(r => setTimeout(r, 20)); } })(); return true; })()",+ )+ .expect("start sweep");+ std::thread::sleep(Duration::from_millis(150));+ assert_ne!(raw.eval(&target, "window.scrollY"), json!(411), "the sweep is running");+ let restored = page.evaluate_value(attach::RESTORE_JS).expect("restore");+ assert_eq!(restored["restored"], json!(true));+ page.close();+ attached.close();+ std::thread::sleep(Duration::from_millis(400));+ assert_eq!(raw.eval(&target, "[window.scrollY, document.getElementById('list').scrollTop]"), json!([411, 137]));+ browser.close();+}++#[test]+fn a_port_that_is_not_devtools_is_refused() {+ let origin = serve_app();+ let port: u16 = origin.rsplit(':').next().unwrap().parse().unwrap();+ let err = attach::detect_cdp(&endpoint(port), None, &ScanOptions::default()).unwrap_err();+ assert!(+ err.message.starts_with(&format!("127.0.0.1:{port} answered, but not as a DevTools endpoint (GET /json/version: HTTP 404)")),+ "{}",+ err.message+ );+ assert!(err.message.contains("--remote-debugging-port"), "{}", err.message);+}diff --git a/crates/detect/src/cdp_endpoint.rs b/crates/detect/src/cdp_endpoint.rsnew file mode 100644index 000000000..35195fe77--- /dev/null+++ b/crates/detect/src/cdp_endpoint.rs@@ -0,0 +1,189 @@+//! `impeccable detect --cdp <port|url>`: the DevTools endpoint of a running+//! Chromium-based app (Electron, NW.js, CEF, WebView2) to attach to.+//!+//! Parsed here, in the crate that owns the flag, so a bad value is refused+//! before any engine runs. Only loopback hosts are accepted: a DevTools port+//! hands whoever reaches it full control of the app, so the scan never asks+//! another machine for one.++use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};++/// Where to attach.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct CdpEndpoint {+ /// The host as it is dialled: `127.0.0.1`, `localhost`, `::1`, or another+ /// loopback address. Never bracketed.+ pub host: String,+ pub port: u16,+ /// The browser websocket path (`/devtools/browser/<id>`) when the value+ /// was that `ws://` URL; otherwise `/json/version` supplies it.+ pub browser_path: Option<String>,+ /// The target id when the value was a page's `ws://` URL+ /// (`/devtools/page/<id>`), which picks that page.+ pub page_id: Option<String>,+}++impl CdpEndpoint {+ /// `host:port`, bracketing an IPv6 host.+ pub fn authority(&self) -> String {+ if self.host.contains(':') {+ format!("[{}]:{}", self.host, self.port)+ } else {+ format!("{}:{}", self.host, self.port)+ }+ }+}++/// The error for a missing or unusable `--cdp` value.+pub const CDP_VALUE_ERROR: &str =+ "Error: --cdp requires a DevTools port or URL, e.g. --cdp 9222 or --cdp ws://127.0.0.1:9222/devtools/browser/<id>\n";++/// Parse a `--cdp` value: a port (`9222`), `host:port`, `http://host:port`,+/// or a DevTools websocket URL (`ws://host:port/devtools/browser/<id>` or+/// `.../devtools/page/<id>`). The host must be loopback. The error is the+/// line the CLI prints.+pub fn parse_cdp_endpoint(value: &str) -> Result<CdpEndpoint, String> {+ let value = value.trim();+ if value.is_empty() {+ return Err(CDP_VALUE_ERROR.to_string());+ }+ if value.bytes().all(|b| b.is_ascii_digit()) {+ let port = parse_port(value)?;+ return Ok(CdpEndpoint { host: "127.0.0.1".into(), port, browser_path: None, page_id: None });+ }+ let lower = value.to_ascii_lowercase();+ let (rest, websocket) = if let Some(r) = strip_prefix_ci(value, &lower, "ws://") {+ (r, true)+ } else if let Some(r) = strip_prefix_ci(value, &lower, "http://") {+ (r, false)+ } else if lower.contains("://") {+ return Err(format!(+ "Error: --cdp takes a port, host:port, http:// or ws:// URL; got {value}\n"+ ));+ } else {+ (value, false)+ };+ let (authority, path) = match rest.find('/') {+ Some(i) => (&rest[..i], &rest[i..]),+ None => (rest, ""),+ };+ let (host, port) = split_authority(authority).ok_or_else(|| CDP_VALUE_ERROR.to_string())?;+ if !is_loopback_host(&host) {+ return Err(format!(+ "Error: --cdp only attaches to a DevTools port on this machine (127.0.0.1, localhost or [::1]), not {host}\n"+ ));+ }+ let port = parse_port(&port)?;+ let mut endpoint = CdpEndpoint { host, port, browser_path: None, page_id: None };+ let path = path.split(['?', '#']).next().unwrap_or("");+ if path.is_empty() || path == "/" {+ return Ok(endpoint);+ }+ if websocket {+ if let Some(id) = path.strip_prefix("/devtools/page/").filter(|id| valid_id(id)) {+ endpoint.page_id = Some(id.to_string());+ return Ok(endpoint);+ }+ if path.strip_prefix("/devtools/browser/").is_some_and(valid_id) {+ endpoint.browser_path = Some(path.to_string());+ return Ok(endpoint);+ }+ }+ Err(format!(+ "Error: --cdp expects a DevTools port or a ws://.../devtools/browser/<id> or .../devtools/page/<id> URL; got {value}\n"+ ))+}++fn strip_prefix_ci<'a>(value: &'a str, lower: &str, prefix: &str) -> Option<&'a str> {+ lower.starts_with(prefix).then(|| &value[prefix.len()..])+}++fn valid_id(id: &str) -> bool {+ !id.is_empty() && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')+}++fn parse_port(s: &str) -> Result<u16, String> {+ match s.parse::<u32>() {+ Ok(p) if (1..=65535).contains(&p) => Ok(p as u16),+ _ => Err(format!("Error: --cdp port must be between 1 and 65535; got {s}\n")),+ }+}++/// `host:port`, `[v6]:port`. A missing port is not an endpoint.+fn split_authority(authority: &str) -> Option<(String, String)> {+ if let Some(rest) = authority.strip_prefix('[') {+ let end = rest.find(']')?;+ let host = &rest[..end];+ let port = rest[end + 1..].strip_prefix(':')?;+ return Some((host.to_string(), port.to_string()));+ }+ let (host, port) = authority.rsplit_once(':')?;+ if host.is_empty() || host.contains(':') {+ return None;+ }+ Some((host.to_string(), port.to_string()))+}++/// `localhost`, or a loopback IPv4 or IPv6 address.+pub fn is_loopback_host(host: &str) -> bool {+ if host.eq_ignore_ascii_case("localhost") {+ return true;+ }+ if let Ok(v4) = host.parse::<Ipv4Addr>() {+ return v4.is_loopback();+ }+ if let Ok(v6) = host.parse::<Ipv6Addr>() {+ return IpAddr::V6(v6).is_loopback()+ || v6.to_ipv4_mapped().is_some_and(|v4| v4.is_loopback());+ }+ false+}++#[cfg(test)]+mod tests {+ use super::*;++ fn ok(v: &str) -> CdpEndpoint {+ parse_cdp_endpoint(v).unwrap_or_else(|e| panic!("{v}: {e}"))+ }++ #[test]+ fn ports_and_hosts() {+ assert_eq!(ok("9222"), CdpEndpoint { host: "127.0.0.1".into(), port: 9222, browser_path: None, page_id: None });+ assert_eq!(ok("localhost:9333").authority(), "localhost:9333");+ assert_eq!(ok("http://127.0.0.1:9222/").authority(), "127.0.0.1:9222");+ assert_eq!(ok("127.1.2.3:9222").host, "127.1.2.3");+ let v6 = ok("[::1]:9222");+ assert_eq!((v6.host.as_str(), v6.authority()), ("::1", "[::1]:9222".to_string()));+ }++ #[test]+ fn websocket_urls_name_the_browser_or_a_page() {+ let b = ok("ws://127.0.0.1:9222/devtools/browser/0b5c-77");+ assert_eq!(b.browser_path.as_deref(), Some("/devtools/browser/0b5c-77"));+ assert_eq!(b.page_id, None);+ let p = ok("ws://localhost:9222/devtools/page/ABCDEF0123");+ assert_eq!(p.page_id.as_deref(), Some("ABCDEF0123"));+ }++ #[test]+ fn refuses_other_machines_and_shapes() {+ for (v, needle) in [+ ("10.0.0.5:9222", "not 10.0.0.5"),+ ("ws://example.com:9222/devtools/browser/x", "not example.com"),+ ("0.0.0.0:9222", "not 0.0.0.0"),+ ("[2001:db8::1]:9222", "not 2001:db8::1"),+ ("", "requires a DevTools port"),+ ("localhost", "requires a DevTools port"),+ ("0", "between 1 and 65535"),+ ("70000", "between 1 and 65535"),+ ("https://127.0.0.1:9222", "takes a port"),+ ("ws://127.0.0.1:9222/json", "expects a DevTools port"),+ ("ws://127.0.0.1:9222/devtools/page/", "expects a DevTools port"),+ ] {+ let err = parse_cdp_endpoint(v).expect_err(v);+ assert!(err.contains(needle), "{v}: {err}");+ assert!(err.starts_with("Error: ") && err.ends_with('\n'), "{err}");+ }+ }+}diff --git a/crates/detect/src/cli.rs b/crates/detect/src/cli.rsindex bc5c1be36..4221ec891 100644--- a/crates/detect/src/cli.rs+++ b/crates/detect/src/cli.rs@@ -45,6 +45,13 @@ Options:--no-overlay-hiding URL scans: keep product tours (driver.js) andpreloaders still covering the page instead of hidingthem before the scan+ --cdp <port|url> Scan a page of a running Chromium-based desktop app+ (Electron, NW.js, CEF, WebView2) through its local+ DevTools port instead of loading a URL. The page is+ scanned as shown and left as found: never navigated,+ resized or closed. Takes no file or URL targets+ --target <text> With --cdp: pick the page whose URL or title contains+ this text when the app has more than one--help Show this help messageAdvisory findings:@@ -80,15 +87,44 @@ Detection modes:Non-HTML files Regex pattern matching (CSS, JSX, TSX, etc.)URLs Puppeteer full browser rendering (auto-detected;http(s):// and file:// URLs; accessible linked CSS included)+ Running apps --cdp: a page of a Chromium-based app, attached through its+ DevTools port and scanned like a URLExamples:impeccable detect src/impeccable detect index.htmlimpeccable detect https://example.com+ impeccable detect --cdp 9222 --target \"My App\" --jsonimpeccable detect --json .impeccable detect --no-config src/";+/// Remove every `--name <value>` / `--name=<value>` from `args`. `None` when+/// the flag is absent, `Some(None)` when it has no value (the end of the+/// arguments, or another `--` flag next), else the last value given.+fn take_value_flag(args: &mut Vec<String>, name: &str) -> Option<Option<String>> {+ let inline_prefix = format!("{name}=");+ let mut found: Option<Option<String>> = None;+ let mut i = 0;+ while i < args.len() {+ if let Some(v) = args[i].strip_prefix(&inline_prefix) {+ found = Some(Some(v.to_string()).filter(|v| !v.is_empty()));+ args.remove(i);+ continue;+ }+ if args[i] != name {+ i += 1;+ continue;+ }+ args.remove(i);+ match args.get(i) {+ Some(v) if !v.starts_with("--") => found = Some(Some(args.remove(i))),+ _ => found = Some(None),+ }+ }+ found+}+fn format_finding_summary(count: usize) -> String {format!("{count} anti-pattern{} found.",@@ -535,6 +571,38 @@ fn detect_cli(args_in: &[String], io: &mut Io, engines: &Engines) -> Result<i32,));return Err(Exit(1));}+ let cdp_value = take_value_flag(&mut args, "--cdp");+ let target_filter = take_value_flag(&mut args, "--target");+ let cdp = match cdp_value {+ None => None,+ Some(None) => {+ io.err(crate::cdp_endpoint::CDP_VALUE_ERROR);+ return Err(Exit(1));+ }+ Some(Some(v)) => match crate::cdp_endpoint::parse_cdp_endpoint(&v) {+ Ok(endpoint) => Some(endpoint),+ Err(line) => {+ io.err(&line);+ return Err(Exit(1));+ }+ },+ };+ let target_filter = match target_filter {+ None => None,+ Some(Some(v)) if !impeccable_core::js::trim(&v).is_empty() => Some(v),+ Some(_) => {+ io.err("Error: --target requires a substring of the page's URL or title, e.g. --target localhost:5173\n");+ return Err(Exit(1));+ }+ };+ if target_filter.is_some() && cdp.is_none() {+ io.err("Error: --target picks a page of the app --cdp attaches to; pass --cdp <port> with it\n");+ return Err(Exit(1));+ }+ if cdp.is_some() && viewport.is_some() {+ io.err("Error: --viewport does not apply with --cdp: the attached window keeps its own size\n");+ return Err(Exit(1));+ }let design_system_enabled = config_enabled&& !has(&args, "--no-design-system")&& detection_config.design_system_not_disabled();@@ -562,6 +630,10 @@ fn detect_cli(args_in: &[String], io: &mut Io, engines: &Engines) -> Result<i32,io.out(USAGE);return Ok(0);}+ if cdp.is_some() && !targets.is_empty() {+ io.err("Error: --cdp scans the page of a running app and takes no file or URL targets\n");+ return Err(Exit(1));+ }let stdin_tty = io.stdin_is_tty;let stderr_tty = stderr_is_tty();@@ -589,7 +661,40 @@ fn detect_cli(args_in: &[String], io: &mut Io, engines: &Engines) -> Result<i32,};let mut all: Vec<Finding> = Vec::new();- if !stdin_tty && targets.is_empty() {+ if let Some(endpoint) = cdp.as_ref() {+ // http(s) URL scans never load a design system, and neither does an+ // attached page: its URL says nothing about which project it is.+ let options = ctx.base.clone();+ let result = match ctx.engines.url {+ Some(u) => u.detect_cdp_scan(endpoint, target_filter.as_deref(), &options),+ None => crate::engines::UrlEngine::detect_cdp_scan(+ &crate::engines::MissingUrlEngine,+ endpoint,+ target_filter.as_deref(),+ &options,+ ),+ };+ match result {+ Ok(scan) => {+ all.extend(scan.findings);+ for note in scan.notes {+ // JSON mode prints no notes, but an attached scan's capture+ // notes say which checks did not run (a hidden window skips+ // the pixel reads), so they go to stderr there and stdout+ // stays the JSON.+ if ctx.json_mode {+ ctx.io.err(&format!("{note}\n"));+ } else if !ctx.design_notes.contains(¬e) {+ ctx.design_notes.push(note);+ }+ }+ }+ Err(e) => {+ ctx.had_operational_failure = true;+ ctx.io.err(&format!("Error: {}\n", e.message));+ }+ }+ } else if !stdin_tty && targets.is_empty() {all = ctx.handle_stdin().map_err(|e| fatal(ctx.io, e))?;} else {let paths: Vec<String> = if targets.is_empty() {diff --git a/crates/detect/src/engines.rs b/crates/detect/src/engines.rsindex 7331a2864..f9b69f3ad 100644--- a/crates/detect/src/engines.rs+++ b/crates/detect/src/engines.rs@@ -97,6 +97,19 @@ pub trait UrlEngine {fn open_shared(&self) -> Option<Box<dyn SharedBrowser + '_>> {None}+ /// `--cdp`: scan a page of an app that is already running, through its+ /// DevTools endpoint, with the same passes and output as a URL scan. The+ /// engine attaches without launching, navigating, resizing or closing+ /// anything, and leaves the page as it found it. `target` is the+ /// `--target` substring of the page's URL or title.+ fn detect_cdp_scan(+ &self,+ _endpoint: &crate::cdp_endpoint::CdpEndpoint,+ _target: Option<&str>,+ _options: &ScanOptions,+ ) -> Result<UrlScan, EngineError> {+ Err(EngineError::new("this build cannot attach to a running app (--cdp)"))+ }}/// A `createBrowserDetector()` handle: `detectUrl` per target, `close()` at the end.diff --git a/crates/detect/src/lib.rs b/crates/detect/src/lib.rsindex b8d1eb669..174ccca32 100644--- a/crates/detect/src/lib.rs+++ b/crates/detect/src/lib.rs@@ -10,6 +10,7 @@//! [`engines::Engines`]. crates/html depends on this crate for the design//! system types and helpers ([`design_system`]).+pub mod cdp_endpoint;pub mod cli;pub mod config;pub mod design_system;diff --git a/docs/CLI-CONTRACT.md b/docs/CLI-CONTRACT.mdindex ec5a38f3f..2825117b2 100644--- a/docs/CLI-CONTRACT.md+++ b/docs/CLI-CONTRACT.md@@ -105,6 +105,8 @@ Notation: `stdout>` / `stderr>` are literal writes; `exit N`; template strings u| `--no-design-system` | `designSystemEnabled = configEnabled && !flag && detectionConfig.designSystem?.enabled !== false` || `--scope <v>` / `--scope=<v>` | comma-split, trimmed, filtered; repeated occurrences accumulate; the flag+value are spliced out of `args`. Value missing or starting with `--` → `stderr> Error: --scope requires a value. Valid scopes: ${[...RULE_SCOPES].join(', ')}\n`, `exit 1`. Unknown → `stderr> Error: unknown --scope value(s): ${unknown.join(', ')}. Valid scopes: ...\n`, `exit 1`. `RULE_SCOPES` = union of rules' `scopes` = `type`, `layout` (in insertion order: `type` first from `overused-font`, then `layout` from `nested-cards`). || `--viewport <WxH>` / `--viewport=WxH` | regex `/^(\d{2,5})x(\d{2,5})$/i`; failure → `stderr> Error: --viewport requires a WxH value, e.g. --viewport 390x844\n`, `exit 1`. Sets `baseScanOptions.viewport = {width,height}` (browser scans only). Spliced out. |+| `--cdp <v>` / `--cdp=<v>` | Rust engine only. Scan a page of a running Chromium-based app through its DevTools endpoint instead of any target (see **Attached pages** below). Spliced out with its value (the last one given wins). Value missing (end of args, or the next arg starts with `--`) → `stderr> Error: --cdp requires a DevTools port or URL, e.g. --cdp 9222 or --cdp ws://127.0.0.1:9222/devtools/browser/<id>\n`, `exit 1`. Accepted values: a port (`9222`, host `127.0.0.1`), `host:port`, `[v6]:port`, `http://host:port[/]`, `ws://host:port[/]`, `ws://host:port/devtools/browser/<id>`, `ws://host:port/devtools/page/<id>` (that page is the target). A host that is not `localhost` or a loopback address → `stderr> Error: --cdp only attaches to a DevTools port on this machine (127.0.0.1, localhost or [::1]), not <host>\n`; a port outside 1 to 65535 → `stderr> Error: --cdp port must be between 1 and 65535; got <v>\n`; another scheme → `stderr> Error: --cdp takes a port, host:port, http:// or ws:// URL; got <v>\n`; another path → `stderr> Error: --cdp expects a DevTools port or a ws://.../devtools/browser/<id> or .../devtools/page/<id> URL; got <v>\n`; each `exit 1`. With `--viewport` → `stderr> Error: --viewport does not apply with --cdp: the attached window keeps its own size\n`, `exit 1`. With positional targets (checked after `--help`) → `stderr> Error: --cdp scans the page of a running app and takes no file or URL targets\n`, `exit 1`. Stdin is never read under `--cdp`. |+| `--target <s>` / `--target=<s>` | With `--cdp`: picks the page (below). Spliced out with its value. Missing or blank value → `stderr> Error: --target requires a substring of the page's URL or title, e.g. --target localhost:5173\n`, `exit 1`. Without `--cdp` → `stderr> Error: --target picks a page of the app --cdp attaches to; pass --cdp <port> with it\n`, `exit 1`. || positional | `targets = args.filter(a => !a.startsWith('--'))` (so a bare `-x` single-dash arg is a *target*, except `-json`/`-fast` which were rewritten) |**Usage text** (`printUsage`, stdout, verbatim):@@ -131,6 +133,13 @@ Options:--no-overlay-hiding URL scans: keep product tours (driver.js) andpreloaders still covering the page instead of hidingthem before the scan+ --cdp <port|url> Scan a page of a running Chromium-based desktop app+ (Electron, NW.js, CEF, WebView2) through its local+ DevTools port instead of loading a URL. The page is+ scanned as shown and left as found: never navigated,+ resized or closed. Takes no file or URL targets+ --target <text> With --cdp: pick the page whose URL or title contains+ this text when the app has more than one--help Show this help messageAdvisory findings:@@ -166,11 +175,14 @@ Detection modes:Non-HTML files Regex pattern matching (CSS, JSX, TSX, etc.)URLs Puppeteer full browser rendering (auto-detected;http(s):// and file:// URLs; accessible linked CSS included)+ Running apps --cdp: a page of a Chromium-based app, attached through its+ DevTools port and scanned like a URLExamples:impeccable detect src/impeccable detect index.htmlimpeccable detect https://example.com+ impeccable detect --cdp 9222 --target "My App" --jsonimpeccable detect --json .impeccable detect --no-config src/```@@ -378,6 +390,26 @@ Optional keys added later by engines (appended after the above): `ignoreValue` (- `createBrowserDetector(options)`: shared browser, defaults `waitUntil:'load'`, `settleMs:100`, `viewport 1280x800`; `close()` closes only an owned browser.- Tests: `tests/detect-url-launch.test.mjs`, `tests/detect-antipatterns-browser.test.mjs`.+#### Attached pages: `impeccable detect --cdp` (Rust engine, `crates/browser/src/attach.rs`)++Scans a page of an app that is already running (Electron, NW.js, CEF, WebView2, or a Chrome started with `--remote-debugging-port`) and prints exactly what a URL scan prints: the same findings array under `--json`, the same text format, notes and exit codes, with every finding's `file` the page's URL (`cdp-target:<id>` when it has none). One difference: under `--json` its capture notes (the hidden-window and stalled-screenshot lines below) go to stderr, one per line, since they say which contrast reads did not run; stdout is still only the JSON. Issue #951.++- **Endpoint.** `GET http://<host>:<port>/json/version` (5 s timeouts) gives `webSocketDebuggerUrl`; its path is dialled at the host and port given, whatever host the endpoint writes into the URL. A `ws://.../devtools/browser/<id>` value skips that request. Before connecting, a host that resolves to any address that is not loopback is refused. Failures, each `stderr> Error: <message>\n` and `exit 1` (no findings; `[]` on stdout under `--json`):+ - unreachable: `could not reach a DevTools endpoint at <host:port> (<os error>). Start the app with --remote-debugging-port=<port> (Electron, NW.js, CEF; for WebView2 set WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS=--remote-debugging-port=<port>), then run this again.`+ - not DevTools: `<host:port> answered, but not as a DevTools endpoint (GET /json/version: HTTP <status>|no webSocketDebuggerUrl). <the same hint>`+- **Picking the page.** Candidates are `Target.getTargets` entries of type `page` whose URL does not start with `devtools://`, in the browser's order. A `ws://.../devtools/page/<id>` value picks that id (`no page with id <id> is open on <host:port>. Open pages:<list>` otherwise). Else `--target` keeps the pages whose URL or title contains it, case-insensitively, or whose id it is; without `--target` every candidate is kept. Exactly one left is scanned. Otherwise:+ - none open: `no pages are open on <host:port> to scan.`+ - `--target` matched none: `no page on <host:port> has a URL or title containing "<t>". Open pages:<list>`+ - `--target` matched several: `<n> pages on <host:port> match "<t>". Rerun with a --target that names one of them (a longer part of its URL or title, or its id):<list>`+ - several and no `--target`: `<n> pages are open on <host:port>. Rerun with --target and part of the URL or title of the one to scan (or its id):<list>`+ - `<list>` is one line per page, `\n <url> "<title>" (id <targetId>)`, the title part left out when empty, `(no URL)` for an empty URL.+- **A session that owns nothing.** The engine never launches or closes the browser, never navigates or reloads, never calls `Emulation.*` (no viewport, device scale or media override), and detaches (`Target.detachFromTarget`) instead of closing the page. It enables `Page` and `Runtime` on its own session only (no `Network`, no auto-attach, no new-document scripts). No evaluation is a user gesture (`userGesture: false`), so the page's user activation is unchanged.+- **An isolated world.** Every evaluation runs in an isolated world created on the page's current document (`Page.createIsolatedWorld`): the page's scripts never see the scan's globals, and the capture reads untouched built-ins whatever the page did to `Map` or `Array.from` (the new-document natives stash URL scans rely on cannot apply to a document that is already loaded). A navigation during the scan destroys the world and the scan fails (`Error: isolated capture context was destroyed or document changed`) instead of reading another document. `Runtime.evaluate` is not subject to the page's CSP, so a strict CSP does not stop the capture; a `style-src` without `'unsafe-inline'` does block the pixel pass's hide style there as on a URL scan, and that pass then gives no pixel verdicts.+- **Hidden windows.** In that world `requestAnimationFrame` fires on the next frame or after 100 ms, whichever comes first, and while `document.visibilityState` is `hidden` (a window behind others, minimized, or a background tab) `setTimeout` waits by posting messages until its time is up, since a hidden page's timers fire a second or more late. The page's own timers and frames are not touched. A hidden page paints no frames, and a screenshot of it can wait for one indefinitely (it does on Linux), so when the page is hidden at the visual pass the pixel reads are skipped: the analyses that read no screenshot still run, the element pass's verdicts on text it handed to the pixels stand as advisory (as for any unread pixel verdict), and the text output adds `Capture note: <url> was hidden (minimized, or a background tab or window), so the pixel pass read nothing there. Bring it on screen, focused or not, and scan again for those contrast verdicts.` A screenshot of an attached page that takes over 15 s ends the pixel reads instead of the scan (any other error during them, a navigation included, still fails the scan), with `Capture note: the pixel pass on <url> stopped when a screenshot stalled (<error>). Bring the window on screen and scan again for the contrast verdicts it did not read.`+- **The same passes, with three differences.** The page is scanned as it stands: no `goto`, no settle, and the viewport is the page's own (`Page.getLayoutMetrics` layout viewport). Consent and overlay hiding are off (as with `--no-consent-hiding --no-overlay-hiding`): the person seeded the state under review. The pixel pass reads what is on screen (`captureBeyondViewport: false`, which never lays the window out at another size), so a candidate whose clip is outside the visual viewport is scrolled into view first, as one past the content box is in a URL scan, and scrolled back; that also reaches text inside an inner scroller, which a URL scan's beyond-viewport capture leaves unread. Design systems: like an `http(s)` URL scan, none is loaded.+- **Left as found.** Before the passes the engine records the window's scroll position and every element (open shadow roots included) scrolled off 0, and the pixel pass records each `video` it pauses. After them, on success and on error, it first cancels the scan's waits in the isolated world (so an evaluation that outlived its protocol timeout cannot scroll the page again), then scrolls each recorded element back, any other element the scan moved off 0 back to 0, the window last, plays again each video the pixel pass paused that has not ended, removes the pixel pass's `#impeccable-visual-contrast-hide-style` (unless the page already had one) and its marker attributes, and deletes the scan's globals from the isolated world. If that step fails the scan fails, findings and all: `stderr> Error: scanned <url> but could not put it back as it was (<why>); check its scroll position and any video it was playing.\n`, `exit 1`. The reveal sweep and the scroll probe still scroll the window through the document during the scan, so the page's scroll handlers run.+- Tests: `crates/browser/tests/cdp_attach.rs` (a headless Chrome the test launches, attached to as an outside client).+#### Static and regex engines (only what affects the contract)- **`flat-type-hierarchy` is advisory when weight separates the roles** (Rust engine, corpus decision r4-p23-flat-type-hierarchy-commerce; static HTML and URL engines, which read computed weights). The rule reads each sampled element's computed `font-weight` (`normal` 400, `bold` 700, a number as itself); when at least four in five heading samples are set at least 200 heavier than the body samples' most common weight, the finding keeps reporting with `severity: 'advisory'` and its snippet's parenthesis ends `; weight separates headings from body text)`. Otherwise it reports as before. The static engine's cascade has no user-agent stylesheet, so a heading with no declared weight reads 400 there, where the URL engine reads the browser's bold.diff --git a/skill/reference/audit.md b/skill/reference/audit.mdindex 11f035a44..25bc07787 100644--- a/skill/reference/audit.md+++ b/skill/reference/audit.md@@ -59,6 +59,8 @@ Run comprehensive checks across 5 dimensions. Score each dimension 0-4 using theRun the bundled detector and verify each finding in context. Look for repeated implementation shortcuts, design-system drift, misleading or decorative content, and structure that is interchangeable with an unrelated product. Keep deterministic findings separate from visual judgment and call out false positives.+**Desktop apps** (Electron, NW.js, CEF, WebView2): launch the app with a local DevTools port (`--remote-debugging-port=9222`, or `WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS=--remote-debugging-port=9222` for WebView2; keep it on 127.0.0.1, never exposed), seed the state to audit, keep the window on screen (a hidden one skips the pixel contrast reads), then run `{{scripts_path}}/impeccable detect --cdp 9222 --target <part of the page URL or title> --json`. It returns the same JSON as a URL scan and leaves the window as found. Take screenshots through the harness's CDP tooling, and leave the window as you found it too. Tauri on macOS (WKWebView) and on Linux (WebKitGTK) expose no CDP: scan the source and say the rendered check did not run.+**Score 0-4**: 0=systemic drift, 1=major repeated failures, 2=several verified issues, 3=minor isolated issues, 4=coherent and intentional## Generate Reportdiff --git a/skill/reference/critique.md b/skill/reference/critique.mdindex 9b60004ab..a437df269 100644--- a/skill/reference/critique.md+++ b/skill/reference/critique.md@@ -36,6 +36,7 @@ Delegate Assessment A and Assessment B to separate sub-agents. They must not seeSub-agent gate (all harnesses):- Unless a harness-specific gate below overrides this, spawn A and B as two isolated, parallel sub-agents whenever a sub-agent/Task tool is exposed. This is the default and is mandatory; do not run them inline because it is faster.+- Desktop apps (see **Desktop apps** under Assessment B) are the one exception to parallel: both sub-agents would drive the app's single window at once. Seed the window, spawn A, wait until it has finished and put the window back, then spawn B. They are still two isolated sub-agents, so this is not the degraded path.- "Unavailable" means exactly one thing: no sub-agent/Task tool is exposed in this session (or, on harnesses that ask, the user declined). It does not mean inconvenient.- If and only if sub-agents are unavailable, fall back sequentially: finish and record Assessment A, then run Assessment B, then synthesize, and emit the degraded banner.- Whichever path you take, declare it in the report header (see Report header provenance). Skipping sub-agents without the banner is the most common failure of this command.@@ -43,15 +44,15 @@ Sub-agent gate (all harnesses):<codex>Codex sub-agent gate (overrides the default above; Codex's permission model requires asking before spawning):- Asking is the normal path, not a degradation. Approving and spawning is the dual-agent path; do not emit the degraded banner just for asking.-- If `spawn_agent` is exposed and the user explicitly allowed sub-agents, delegation, or parallel agent work, spawn A and B immediately.+- If `spawn_agent` is exposed and the user explicitly allowed sub-agents, delegation, or parallel agent work, spawn A and B immediately (for a desktop app, A first and B once A has finished, as the default gate above says).- If `spawn_agent` is exposed but the user did not explicitly allow sub-agents, ask exactly once: "Impeccable critique is designed to run two independent sub-agents for an unanchored assessment. May I use sub-agents for this critique?" Then stop until the user answers.-- If allowed, spawn A and B. If declined, run sequentially and lead the report with `⚠️ DEGRADED: single-context (sub-agents declined by user)`.+- If allowed, spawn A and B (in sequence for a desktop app). If declined, run sequentially and lead the report with `⚠️ DEGRADED: single-context (sub-agents declined by user)`.- If `spawn_agent` is not exposed, do not ask; run sequentially and lead with `⚠️ DEGRADED: single-context (spawn_agent unavailable in this session)`.- If spawning fails after permission, run sequentially and lead with `⚠️ DEGRADED: single-context (sub-agent spawn failed: <exact error>)`.Prefer `fork_context: false` with self-contained prompts containing cwd, target, live URL, references, product context, and output contract. If using `fork_context: true`, omit `agent_type`, `model`, and `reasoning_effort`.</codex>-If browser automation is available, each assessment creates its own new tab. Never reuse an existing tab, even if it is already at the right URL.+If browser automation is available, each assessment creates its own new tab. Never reuse an existing tab, even if it is already at the right URL. Desktop apps are the exception (see **Desktop apps** under Assessment B).### Assessment A: Design Review@@ -89,6 +90,15 @@ Browser visualization is required for a viewable target when browser automation4. If mutation is available, start `{{scripts_path}}/impeccable live-server --background`, present the browser if supported, label `[Human]`, scroll top, inject `http://localhost:PORT/detect.js`, wait 2-3 seconds, read `impeccable` console messages, then run `{{scripts_path}}/impeccable live-server stop --keep-inject`. The overlay went in through the browser, so the project's HTML has no script tag to strip; a bare `stop` also runs `live-inject --remove` against the project's entry file, an edit a read-only critique should not make.5. For multi-view targets, inject on 3-5 representative pages.+**Desktop apps** (Electron, NW.js, CEF, WebView2): there is no URL to open, so Assessment B attaches to the running app instead.++1. Launch the app with a local DevTools port: `--remote-debugging-port=9222` (Electron, NW.js, CEF), or `WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS=--remote-debugging-port=9222` for WebView2. Keep the port on 127.0.0.1 and never expose it beyond this machine; prefer a test profile and test data.+2. Seed the state under review (route, open panel, theme, data). The scan reads the window as it stands. Keep the window on screen: a minimized or hidden window scans without the pixel contrast reads.+3. Run `{{scripts_path}}/impeccable detect --cdp 9222 --target <part of the page URL or title> --json`. It returns the same JSON as a URL scan and leaves the page as found. With several pages open it fails and lists them; rerun with a `--target` that names one.+4. Take screenshots through the harness's CDP tooling (`Page.captureScreenshot` on the same target). Skip the live-server overlay: there is no `[Human]` tab.++The app has one window, so the assessments take turns in it instead of opening tabs (A, then B; see the sub-agent gate), and each must leave it as found: put back any route, scroll, theme, or panel it changed. Tauri on macOS (WKWebView) and on Linux (WebKitGTK) expose no CDP: run Assessment A and the source scan only, and say so in Run Notes.+<codex>Codex Browser note: Use the Browser skill. Do not spend a Browser attempt on `file://`. Only call `visibility.set(true)` after mutable script injection is confirmed for the `[Human]` overlay path; verify with `get()`. Use `tab.dev.logs({ filter: "impeccable" })` for console results. Its Playwright `evaluate(...)` surface is read-only; do not rely on it for mutation.</codex>diff --git a/tests/oracle/DELTAS.md b/tests/oracle/DELTAS.mdindex 973d43d80..da1ae8da1 100644--- a/tests/oracle/DELTAS.md+++ b/tests/oracle/DELTAS.md@@ -7080,3 +7080,7 @@ Re-recorded from the binary and reviewed by hand, 55 goldens. A script check conA variants wrapper with no `data-impeccable-variant="original"` element (the hand-written fallback scaffold `live.md` used to show) made discard restore nothing: the element was deleted and the result said `handled: true`. `live-accept --discard` now refuses such a wrapper with `Original not found: ...` and writes nothing, while `--variant N` still accepts it: accept writes the chosen variant and uses the original only to prune buffered manual edits; an insert wrapper (`data-impeccable-mode="insert"`) has no slot by design and still discards to nothing. New cases, recorded from the binary and reviewed by hand: `live-accept-html-no-original-discard` (handled false, `index.html` byte-identical to the staged wrapper, no receipt), `live-accept-html-no-original-accept` (handled, variant 1 carbonized into `index.html`) and `live-accept-html-insert-discard` (live-insert, then discard: the page is back to the fixture, receipt written). No existing accept golden moved.`live-server stop` ran `live-inject --remove` even with no live config, which echoed `config_missing` and then `Note: could not remove live script tag (...)` though nothing had been injected. With no config it now skips the removal and says nothing about the tag. Re-recorded `live-server-stop-no-config`: stderr goes from those two lines to empty; stdout and exit are unchanged.++## Recorded 2026-10-16: detect attaches to a running desktop app (#951)++`impeccable detect --cdp <port|url> [--target <text>]` scans a page of a running Chromium-based app (Electron, NW.js, CEF, WebView2) through its local DevTools endpoint, with the URL scan's passes and output, and leaves the page as found (`docs/CLI-CONTRACT.md`, "Attached pages"). `detect-help` gains the two flags, a `Running apps` line under Detection modes and one example. New cases pin the flag surface, each an `Error:` line on stderr and exit 1 before any engine runs: `detect-cdp-missing-value`, `detect-cdp-remote-host` (a host that is not loopback is refused), `detect-cdp-bad-port`, `detect-cdp-bad-path`, `detect-cdp-with-targets`, `detect-cdp-with-viewport`, `detect-target-without-cdp` and `detect-target-missing-value`. The scan itself needs a running browser, which the oracle does not host; `crates/browser/tests/cdp_attach.rs` covers it. Recorded from the binary and reviewed by hand; no golden other than `detect-help` moved.diff --git a/tests/oracle/cases/detect.mjs b/tests/oracle/cases/detect.mjsindex e5b752df2..01790a551 100644--- a/tests/oracle/cases/detect.mjs+++ b/tests/oracle/cases/detect.mjs@@ -162,6 +162,17 @@ function Thumb({ url }: { url?: string }) {},{ id: 'detect-unknown-flag', verb: 'detect', args: ['--bogus', `<REPO>/tests/fixtures/antipatterns/blinking-cursor.html`], isolateHome: false },{ id: 'detect-bad-viewport', verb: 'detect', args: ['--viewport', 'wide', `<REPO>/tests/fixtures/antipatterns/blinking-cursor.html`], isolateHome: false },+ // --cdp / --target (#951): the flag surface only. Attaching needs a+ // running browser, which the oracle cannot host; crates/browser/tests/+ // cdp_attach.rs covers the scan.+ { id: 'detect-cdp-missing-value', verb: 'detect', args: ['--cdp', '--json'] },+ { id: 'detect-cdp-remote-host', verb: 'detect', args: ['--cdp', '10.0.0.5:9222', '--json'] },+ { id: 'detect-cdp-bad-port', verb: 'detect', args: ['--cdp=70000'] },+ { id: 'detect-cdp-bad-path', verb: 'detect', args: ['--cdp', 'ws://127.0.0.1:9222/json/list'] },+ { id: 'detect-cdp-with-targets', verb: 'detect', args: ['--cdp', '9222', `<REPO>/tests/fixtures/antipatterns/blinking-cursor.html`], isolateHome: false },+ { id: 'detect-cdp-with-viewport', verb: 'detect', args: ['--cdp', '9222', '--viewport', '390x844'] },+ { id: 'detect-target-without-cdp', verb: 'detect', args: ['--target', 'app', `<REPO>/tests/fixtures/antipatterns/blinking-cursor.html`], isolateHome: false },+ { id: 'detect-target-missing-value', verb: 'detect', args: ['--cdp', '9222', '--target'] },{ id: 'cli-help', verb: 'cli-help', args: [] },{id: 'cli-version', verb: 'cli-version', args: [],diff --git a/tests/oracle/golden/detect-cdp-bad-path.json b/tests/oracle/golden/detect-cdp-bad-path.jsonnew file mode 100644index 000000000..06a5512d2--- /dev/null+++ b/tests/oracle/golden/detect-cdp-bad-path.json@@ -0,0 +1,7 @@+{+ "stdout": "",+ "stderr": "Error: --cdp expects a DevTools port or a ws://.../devtools/browser/<id> or .../devtools/page/<id> URL; got ws://127.0.0.1:9222/json/list\n",+ "exit": 1,+ "signal": null,+ "files": {}+}diff --git a/tests/oracle/golden/detect-cdp-bad-port.json b/tests/oracle/golden/detect-cdp-bad-port.jsonnew file mode 100644index 000000000..bd7b7d714--- /dev/null+++ b/tests/oracle/golden/detect-cdp-bad-port.json@@ -0,0 +1,7 @@+{+ "stdout": "",+ "stderr": "Error: --cdp port must be between 1 and 65535; got 70000\n",+ "exit": 1,+ "signal": null,+ "files": {}+}diff --git a/tests/oracle/golden/detect-cdp-missing-value.json b/tests/oracle/golden/detect-cdp-missing-value.jsonnew file mode 100644index 000000000..a55f39920--- /dev/null+++ b/tests/oracle/golden/detect-cdp-missing-value.json@@ -0,0 +1,7 @@+{+ "stdout": "",+ "stderr": "Error: --cdp requires a DevTools port or URL, e.g. --cdp 9222 or --cdp ws://127.0.0.1:9222/devtools/browser/<id>\n",+ "exit": 1,+ "signal": null,+ "files": {}+}diff --git a/tests/oracle/golden/detect-cdp-remote-host.json b/tests/oracle/golden/detect-cdp-remote-host.jsonnew file mode 100644index 000000000..67cbfab38--- /dev/null+++ b/tests/oracle/golden/detect-cdp-remote-host.json@@ -0,0 +1,7 @@+{+ "stdout": "",+ "stderr": "Error: --cdp only attaches to a DevTools port on this machine (127.0.0.1, localhost or [::1]), not 10.0.0.5\n",+ "exit": 1,+ "signal": null,+ "files": {}+}diff --git a/tests/oracle/golden/detect-cdp-with-targets.json b/tests/oracle/golden/detect-cdp-with-targets.jsonnew file mode 100644index 000000000..70977132c--- /dev/null+++ b/tests/oracle/golden/detect-cdp-with-targets.json@@ -0,0 +1,7 @@+{+ "stdout": "",+ "stderr": "Error: --cdp scans the page of a running app and takes no file or URL targets\n",+ "exit": 1,+ "signal": null,+ "files": {}+}diff --git a/tests/oracle/golden/detect-cdp-with-viewport.json b/tests/oracle/golden/detect-cdp-with-viewport.jsonnew file mode 100644index 000000000..5333aa519--- /dev/null+++ b/tests/oracle/golden/detect-cdp-with-viewport.json@@ -0,0 +1,7 @@+{+ "stdout": "",+ "stderr": "Error: --viewport does not apply with --cdp: the attached window keeps its own size\n",+ "exit": 1,+ "signal": null,+ "files": {}+}diff --git a/tests/oracle/golden/detect-help.json b/tests/oracle/golden/detect-help.jsonindex 8d1c1abdd..b9489ae7b 100644--- a/tests/oracle/golden/detect-help.json+++ b/tests/oracle/golden/detect-help.json@@ -1,5 +1,5 @@{- "stdout": "Usage: impeccable detect [options] [file-or-dir-or-url...]\n\nScan files or URLs for UI anti-patterns and design quality issues.\n\nOptions:\n --json Output results as JSON\n --quiet In text mode, only print the final findings count\n --scope <name> Only report rules in the given design domain\n (type, layout). Comma-separated.\n --viewport <WxH> Browser viewport for URL scans (default 1280x800),\n e.g. --viewport 390x844 for a mobile-width pass\n --no-config Do not apply project config, detector ignores, inline\n ignore comments, or DESIGN.md\n --no-inline-ignores Do not honor in-file impeccable-disable* ignore comments\n --no-design-system Do not load local DESIGN.md / .impeccable/design.json context\n --no-advisory Suppress advisory findings entirely (e.g. em-dash overuse)\n --no-consent-hiding URL scans: keep known consent managers' banners\n (OneTrust, Cookiebot, ...) on the page instead of hiding\n them before the scan\n --no-overlay-hiding URL scans: keep product tours (driver.js) and\n preloaders still covering the page instead of hiding\n them before the scan\n --help Show this help message\n\nAdvisory findings:\n Some rules are advisory: detected and listed in a separate section, but never\n counted as failures and never changing the exit code. They stay out of the\n failure count so they never block automation. --no-advisory hides them.\n\nOutput streams:\n Human-readable findings go to stderr so stdout stays available for structured\n output. Use --json for JSON on stdout, or redirect text with 2> findings.txt.\n\nExit status:\n 0 Scan completed with no primary findings (advisories may still be listed)\n 1 At least one requested target could not be scanned\n 2 Scan completed with primary findings\n Operational failure takes precedence when a multi-target scan is partial.\n\nProject config:\n Respects .impeccable/config.json and .impeccable/config.local.json detector\n settings: detector.ignoreRules, detector.ignoreFiles, detector.ignoreValues,\n and detector.designSystem.enabled.\n\nInline ignores:\n In-file comments waive a finding where it lives and travel with the file:\n <!-- impeccable-disable overused-font -- exported brand doc -->\n .brand { font-family: Inter } /* impeccable-disable-line overused-font */\n // impeccable-disable-next-line bounce-easing: intentional bounce\n impeccable-disable applies to the whole file; -line / -next-line are scoped.\n List one or more rule ids (comma-separated), or omit them / use * for all.\n\nDetection modes:\n HTML files Static HTML/CSS analysis (default, catches linked CSS)\n Non-HTML files Regex pattern matching (CSS, JSX, TSX, etc.)\n URLs Puppeteer full browser rendering (auto-detected;\n http(s):// and file:// URLs; accessible linked CSS included)\n\nExamples:\n impeccable detect src/\n impeccable detect index.html\n impeccable detect https://example.com\n impeccable detect --json .\n impeccable detect --no-config src/\n",+ "stdout": "Usage: impeccable detect [options] [file-or-dir-or-url...]\n\nScan files or URLs for UI anti-patterns and design quality issues.\n\nOptions:\n --json Output results as JSON\n --quiet In text mode, only print the final findings count\n --scope <name> Only report rules in the given design domain\n (type, layout). Comma-separated.\n --viewport <WxH> Browser viewport for URL scans (default 1280x800),\n e.g. --viewport 390x844 for a mobile-width pass\n --no-config Do not apply project config, detector ignores, inline\n ignore comments, or DESIGN.md\n --no-inline-ignores Do not honor in-file impeccable-disable* ignore comments\n --no-design-system Do not load local DESIGN.md / .impeccable/design.json context\n --no-advisory Suppress advisory findings entirely (e.g. em-dash overuse)\n --no-consent-hiding URL scans: keep known consent managers' banners\n (OneTrust, Cookiebot, ...) on the page instead of hiding\n them before the scan\n --no-overlay-hiding URL scans: keep product tours (driver.js) and\n preloaders still covering the page instead of hiding\n them before the scan\n --cdp <port|url> Scan a page of a running Chromium-based desktop app\n (Electron, NW.js, CEF, WebView2) through its local\n DevTools port instead of loading a URL. The page is\n scanned as shown and left as found: never navigated,\n resized or closed. Takes no file or URL targets\n --target <text> With --cdp: pick the page whose URL or title contains\n this text when the app has more than one\n --help Show this help message\n\nAdvisory findings:\n Some rules are advisory: detected and listed in a separate section, but never\n counted as failures and never changing the exit code. They stay out of the\n failure count so they never block automation. --no-advisory hides them.\n\nOutput streams:\n Human-readable findings go to stderr so stdout stays available for structured\n output. Use --json for JSON on stdout, or redirect text with 2> findings.txt.\n\nExit status:\n 0 Scan completed with no primary findings (advisories may still be listed)\n 1 At least one requested target could not be scanned\n 2 Scan completed with primary findings\n Operational failure takes precedence when a multi-target scan is partial.\n\nProject config:\n Respects .impeccable/config.json and .impeccable/config.local.json detector\n settings: detector.ignoreRules, detector.ignoreFiles, detector.ignoreValues,\n and detector.designSystem.enabled.\n\nInline ignores:\n In-file comments waive a finding where it lives and travel with the file:\n <!-- impeccable-disable overused-font -- exported brand doc -->\n .brand { font-family: Inter } /* impeccable-disable-line overused-font */\n // impeccable-disable-next-line bounce-easing: intentional bounce\n impeccable-disable applies to the whole file; -line / -next-line are scoped.\n List one or more rule ids (comma-separated), or omit them / use * for all.\n\nDetection modes:\n HTML files Static HTML/CSS analysis (default, catches linked CSS)\n Non-HTML files Regex pattern matching (CSS, JSX, TSX, etc.)\n URLs Puppeteer full browser rendering (auto-detected;\n http(s):// and file:// URLs; accessible linked CSS included)\n Running apps --cdp: a page of a Chromium-based app, attached through its\n DevTools port and scanned like a URL\n\nExamples:\n impeccable detect src/\n impeccable detect index.html\n impeccable detect https://example.com\n impeccable detect --cdp 9222 --target \"My App\" --json\n impeccable detect --json .\n impeccable detect --no-config src/\n","stderr": "","exit": 0,"signal": null,diff --git a/tests/oracle/golden/detect-target-missing-value.json b/tests/oracle/golden/detect-target-missing-value.jsonnew file mode 100644index 000000000..b24a994fa--- /dev/null+++ b/tests/oracle/golden/detect-target-missing-value.json@@ -0,0 +1,7 @@+{+ "stdout": "",+ "stderr": "Error: --target requires a substring of the page's URL or title, e.g. --target localhost:5173\n",+ "exit": 1,+ "signal": null,+ "files": {}+}diff --git a/tests/oracle/golden/detect-target-without-cdp.json b/tests/oracle/golden/detect-target-without-cdp.jsonnew file mode 100644index 000000000..da5484f71--- /dev/null+++ b/tests/oracle/golden/detect-target-without-cdp.json@@ -0,0 +1,7 @@+{+ "stdout": "",+ "stderr": "Error: --target picks a page of the app --cdp attaches to; pass --cdp <port> with it\n",+ "exit": 1,+ "signal": null,+ "files": {}+}