Skip to content

The design language that makes your AI harness better at design.

JavaScript

URL scans keep their own built-ins when a page replaces `Map` (#1011)

Paul Bakausabf5779cabc2
diff --git a/browser-bundle/05-natives.js b/browser-bundle/05-natives.js
new file mode 100644
index 000000000..0d79515a6
--- /dev/null
+++ b/browser-bundle/05-natives.js
@@ -0,0 +1,127 @@
+// --- browser-bundle/05-natives.js ---
+// The JavaScript built-ins the page JS uses, held where page script cannot
+// replace them. This code runs in the page's own world (the URL engine and
+// the live /detect.js script), where a site may declare `var Map = ...` or
+// assign `Array.from = ...` (work24.go.kr ships its own global `Map`, which
+// failed every capture with `states.set is not a function`).
+//
+// The URL engine runs this file once more, as a script on every new document
+// before any page script (`Page::initialize` in crates/browser), and that run
+// stashes what it built on `window.__impeccableNatives`, read-only and
+// non-enumerable. Later runs take the stash. Without one (the live script
+// tag) the current globals are used as they are: live mode sees the user's
+// own app.
+//
+// The extension does not ship this file: its content scripts already have
+// their own globals, and in Firefox `window` there is an Xray view of the
+// page's window, so natives built from it throw (crates/bundle EXT_SNAPSHOT).
+// The builder reads `globalThis`, never `window`, for the same reason: in the
+// page's own world the two are one object.
+//
+// `performance` is the page's own Performance object, shared with the page:
+// a page that replaces the global is covered, one that assigns
+// `performance.now` or patches `Performance.prototype` is not.
+//
+// The stash is page-visible: `Object.getOwnPropertyNames(window)` lists
+// `__impeccableNatives` on every document the URL engine loads, and a page
+// that declares its own global `let __impeccableNatives` fails to load that
+// script. Both are vanishingly rare.
+//
+// The `const` at the end shadows the globals for everything after it in the
+// same function scope, which every consumer of this file provides (the
+// in-page bundle's IIFE, the URL engine's wrapper and prelude).
+// Statics (`Array.from`, `JSON.stringify`, `Object.keys`, ...) are copied at
+// capture time, so a later assignment to the shared object reaches nothing
+// here. Prototype methods (`Map.prototype.set`) are not copied: a page that
+// rewrites those is out of reach.
+//
+// The builder must reach every built-in through `g`, never by bare name:
+// while it runs, the bare names are the `const` below, not yet initialized.
+
+function __impeccableBuildNatives(g) {
+ const O = g.Object;
+ const R = g.Reflect;
+ const freeze = O.freeze;
+ // Held now, so a page that later replaces `Reflect.construct` or
+ // `Reflect.apply` on the shared object cannot reach the facades below.
+ const construct = R.construct;
+ const apply = R.apply;
+ // Own properties of `owner`, functions bound to it (`Array.from` and
+ // `Promise.resolve` read `this`), onto `target`.
+ const copyStatics = (owner, target) => {
+ if (owner == null) return target;
+ for (const name of O.getOwnPropertyNames(owner)) {
+ if (name === 'length' || name === 'name' || name === 'prototype' || name === 'caller' || name === 'arguments') continue;
+ let value;
+ try { value = owner[name]; } catch { continue; }
+ O.defineProperty(target, name, {
+ value: typeof value === 'function' ? R.apply(g.Function.prototype.bind, value, [owner]) : value,
+ enumerable: false, writable: false, configurable: false,
+ });
+ }
+ return target;
+ };
+ const namespace = (owner) => (owner == null ? owner : freeze(copyStatics(owner, O.create(null))));
+ // A constructor whose statics the page JS reads: calls and `new` reach the
+ // native, `instanceof` still works, the statics are the copies.
+ const callable = (native) => {
+ if (typeof native !== 'function') return native;
+ const facade = function (...args) {
+ return new.target ? construct(native, args) : apply(native, undefined, args);
+ };
+ O.defineProperty(facade, 'prototype', { value: native.prototype, writable: false });
+ return freeze(copyStatics(native, facade));
+ };
+ const bound = (name) => {
+ const fn = g[name];
+ return typeof fn === 'function' ? R.apply(g.Function.prototype.bind, fn, [g]) : undefined;
+ };
+ return freeze({
+ // Constructors used for `new` or calls only, and objects whose methods
+ // live on their prototype: the natives themselves.
+ Map: g.Map, Set: g.Set, WeakMap: g.WeakMap, WeakSet: g.WeakSet,
+ Error: g.Error, URL: g.URL, Image: g.Image, ResizeObserver: g.ResizeObserver,
+ String: g.String, Boolean: g.Boolean,
+ // Constructors whose statics are read.
+ Array: callable(g.Array), Object: callable(g.Object), Number: callable(g.Number),
+ Promise: callable(g.Promise),
+ // Namespaces.
+ JSON: namespace(g.JSON), Math: namespace(g.Math), Reflect: namespace(g.Reflect),
+ CSS: namespace(g.CSS),
+ // The page's own Performance object: its methods (`now`,
+ // `getEntriesByType`, ...) live on its prototype, like Map's.
+ performance: g.performance,
+ // Window functions.
+ getComputedStyle: bound('getComputedStyle'), matchMedia: bound('matchMedia'),
+ setTimeout: bound('setTimeout'), clearTimeout: bound('clearTimeout'),
+ requestAnimationFrame: bound('requestAnimationFrame'),
+ // Global functions that do not read `this`.
+ parseFloat: g.parseFloat,
+ });
+}
+
+const __impeccableNatives = (() => {
+ const g = globalThis;
+ try {
+ const stash = g.__impeccableNatives;
+ if (stash && typeof stash === 'object') return stash;
+ } catch { /* fall through */ }
+ try { return __impeccableBuildNatives(g); } catch { /* fall through */ }
+ return {
+ Map: g.Map, Set: g.Set, WeakMap: g.WeakMap, WeakSet: g.WeakSet,
+ Error: g.Error, URL: g.URL, Image: g.Image, ResizeObserver: g.ResizeObserver,
+ String: g.String, Boolean: g.Boolean, Array: g.Array, Object: g.Object,
+ Number: g.Number, Promise: g.Promise, JSON: g.JSON, Math: g.Math,
+ Reflect: g.Reflect, CSS: g.CSS, performance: g.performance,
+ getComputedStyle: g.getComputedStyle, matchMedia: g.matchMedia,
+ setTimeout: g.setTimeout, clearTimeout: g.clearTimeout,
+ requestAnimationFrame: g.requestAnimationFrame, parseFloat: g.parseFloat,
+ };
+})();
+
+const {
+ Map, Set, WeakMap, WeakSet, Error, URL, Image, ResizeObserver, String, Boolean,
+ Array, Object, Number, Promise, JSON, Math, Reflect, CSS, performance,
+ getComputedStyle, matchMedia, setTimeout, clearTimeout, requestAnimationFrame,
+ parseFloat,
+} = __impeccableNatives;
diff --git a/browser-bundle/15-snapshot.js b/browser-bundle/15-snapshot.js
index 76b74124f..91983200b 100644
--- a/browser-bundle/15-snapshot.js
+++ b/browser-bundle/15-snapshot.js
@@ -231,8 +231,8 @@ function __snapConditionalCssRuleIsActive(rule) {
const constructorName = rule?.constructor?.name || '';
if (constructorName === 'CSSMediaRule' || type === 4) {
const condition = rule.conditionText || rule.media?.mediaText || '';
- if (!condition || typeof window.matchMedia !== 'function') return true;
- try { return window.matchMedia(condition).matches; }
+ if (!condition || typeof matchMedia !== 'function') return true;
+ try { return matchMedia(condition).matches; }
catch { return true; }
}
if (constructorName === 'CSSSupportsRule' || type === 12) {
diff --git a/browser-bundle/README.md b/browser-bundle/README.md
index 460ef3f96..20edab972 100644
--- a/browser-bundle/README.md
+++ b/browser-bundle/README.md
@@ -8,8 +8,11 @@ is a call into the wasm rule core built from `crates/core` (`docs/ENGINE.md`).
Two consumers:
-- `crates/browser` embeds `15-snapshot.js` (the snapshot producer the URL
- engine injects; no WebAssembly runs in the page).
+- `crates/browser` embeds `05-natives.js` and `15-snapshot.js` (the snapshot
+ producer the URL engine injects; no WebAssembly runs in the page). It also
+ runs `05-natives.js` on every new document before the page's own scripts,
+ which stashes the built-ins where a site's own global `Map` or a reassigned
+ `Array.from` cannot reach them.
- `crates/bundle` (the `impeccable-bundle` library) embeds every file here
with `include_str!` and concatenates them, in filename order, with the wasm
core into the in-page bundle plus the extension's `extension/detector/`
@@ -25,3 +28,8 @@ in); a test fails when the two lists disagree.
`15-snapshot.js` lists the computed-style properties the rules read; the
bundle build checks that list against the core's and fails when they drift.
+
+Page JS runs in the page's world, so it names built-ins (`Map`, `Set`,
+`Array.from`, `JSON`, `Math`, `getComputedStyle`, ...) only through the
+bindings `05-natives.js` declares. A new built-in a file starts using goes
+into that file's list too.
diff --git a/crates/browser/src/cdp.rs b/crates/browser/src/cdp.rs
index 22b257e5e..68ac8b14f 100644
--- a/crates/browser/src/cdp.rs
+++ b/crates/browser/src/cdp.rs
@@ -727,6 +727,10 @@ impl<'a> Page<'a> {
self.handle_frame_tree(ft, None);
}
self.send("Page.setLifecycleEventsEnabled", json!({ "enabled": true }))?;
+ // Before any page script on every document this page loads: keep the
+ // built-ins the snapshot producer uses where page script cannot
+ // replace them (`natives_prelude_script`).
+ self.send("Page.addScriptToEvaluateOnNewDocument", json!({ "source": natives_prelude_script() }))?;
// URL mode injects only the snapshot producer (plain JS) and runs the
// rules natively in this process over `SnapshotDom` (triage D2; see
// WASM-BUNDLE.md in the detector repo): no WebAssembly is compiled next
@@ -1418,6 +1422,16 @@ impl<'a> Page<'a> {
expression: &str,
unique_context: Option<&str>,
) -> CdpResult<EvalOutcome> {
+ // The main world is the page's: run the expression with the
+ // built-ins the prelude stashed (`in_natives_scope`). An isolated
+ // world has its own untouched globals.
+ let scoped;
+ let expression = if unique_context.is_none() {
+ scoped = in_natives_scope(expression);
+ scoped.as_str()
+ } else {
+ expression
+ };
let mut params = json!({"expression":expression,"returnByValue":true,"awaitPromise":true,"userGesture":true});
if let Some(id) = unique_context {
params["uniqueContextId"] = json!(id);
@@ -2263,6 +2277,54 @@ mod tests {
}
}
+/// `browser-bundle/05-natives.js`: binds the built-ins the page JS uses
+/// (`Map`, `Set`, `Array.from`, `JSON.stringify`, ...) from
+/// `window.__impeccableNatives` when that stash exists, else from the
+/// current globals.
+pub const NATIVES_JS: &str = include_str!("../../../browser-bundle/05-natives.js");
+
+/// The new-document script [`Page`] registers for every document, which runs
+/// before the page's own scripts: it builds the natives from the untouched
+/// globals and stashes them on `window.__impeccableNatives`, non-enumerable
+/// and read-only, so a page that declares its own global `Map` (work24.go.kr)
+/// or reassigns `Array.from` cannot reach the capture.
+pub fn natives_prelude_script() -> String {
+ format!(
+ "(function(){{\n{NATIVES_JS}\ntry {{ Reflect.defineProperty(window, '__impeccableNatives', {{ value: __impeccableNatives, enumerable: false, writable: false, configurable: false }}); }} catch (e) {{}}\n}})()"
+ )
+}
+
+/// The names `browser-bundle/05-natives.js` binds, in its order. A unit test
+/// keeps the two lists equal.
+pub const NATIVE_NAMES: &[&str] = &[
+ "Map", "Set", "WeakMap", "WeakSet", "Error", "URL", "Image", "ResizeObserver", "String",
+ "Boolean", "Array", "Object", "Number", "Promise", "JSON", "Math", "Reflect", "CSS",
+ "performance", "getComputedStyle", "matchMedia", "setTimeout", "clearTimeout",
+ "requestAnimationFrame", "parseFloat",
+];
+
+/// `expression` inside a block whose `const`s shadow the built-ins with the
+/// ones the new-document prelude stashed, so the engine's own page scripts
+/// (the scroll probe, the full-page screenshot, consent and overlay
+/// handling) build a native `Map` on a page that declared its own
+/// (work24.go.kr). Without a stash (a document loaded before the prelude was
+/// registered) the names read the page's globals as before.
+///
+/// A block's completion value is its last statement's, so an expression and
+/// a statement list ending in one both return what they did unwrapped. The
+/// prefix shares the expression's first line, so reported line numbers do
+/// not move, and the closing brace has its own line, so a trailing `//`
+/// comment cannot swallow it.
+pub fn in_natives_scope(expression: &str) -> String {
+ let mut out = String::with_capacity(expression.len() + 320);
+ out.push_str("{ const { ");
+ out.push_str(&NATIVE_NAMES.join(", "));
+ out.push_str(" } = (window.__impeccableNatives || window); ");
+ out.push_str(expression);
+ out.push_str("\n}");
+ out
+}
+
/// The page-side half of [`Page::pin_clock`].
pub fn pinned_clock_script(epoch_ms: f64) -> String {
format!(r#"(()=>{{const T={epoch},P=performance.now(),N=Date;const now=()=>Math.floor(T+performance.now()-P);
@@ -2273,3 +2335,28 @@ const F=Intl.DateTimeFormat.prototype,g=Object.getOwnPropertyDescriptor(F,"forma
Object.defineProperty(F,"format",{{configurable:true,get(){{const f=g.call(this);return d=>f(d===undefined?now():d)}}}});
F.formatToParts=function(d){{return p.call(this,d===undefined?now():d)}};}})()"#, epoch = epoch_ms.floor() as i64)
}
+
+#[cfg(test)]
+mod natives_tests {
+ use super::*;
+
+ #[test]
+ fn native_names_match_the_natives_file() {
+ let start = NATIVES_JS.rfind("const {").expect("05-natives.js ends with a destructure");
+ let end = start + NATIVES_JS[start..].find('}').expect("closing brace");
+ let names: Vec<&str> = NATIVES_JS[start + "const {".len()..end]
+ .split(',')
+ .map(str::trim)
+ .filter(|n| !n.is_empty())
+ .collect();
+ assert_eq!(names, NATIVE_NAMES, "browser-bundle/05-natives.js and NATIVE_NAMES differ");
+ }
+
+ #[test]
+ fn natives_scope_keeps_the_first_line_and_closes_after_a_comment() {
+ let scoped = in_natives_scope("(() => 1)() // trailing");
+ assert_eq!(scoped.lines().count(), 2);
+ assert!(scoped.lines().next().unwrap().ends_with("(() => 1)() // trailing"));
+ assert_eq!(scoped.lines().last(), Some("}"));
+ }
+}
diff --git a/crates/browser/src/snapshot_engine.rs b/crates/browser/src/snapshot_engine.rs
index cc988a568..fc1014bbb 100644
--- a/crates/browser/src/snapshot_engine.rs
+++ b/crates/browser/src/snapshot_engine.rs
@@ -31,7 +31,7 @@ use impeccable_core::browser::{BrowserConfig, ElId};
use impeccable_core::color::Rgba;
use serde_json::{json, Value};
-use crate::cdp::{CdpError, CdpResult, Page};
+use crate::cdp::{CdpError, CdpResult, Page, NATIVES_JS};
/// `browser-bundle/15-snapshot.js` — the page-measurement producer. It defines
/// `const __impeccableSnapshot = {...}` plus its helpers; [`ensure_snapshot_js`]
@@ -39,9 +39,12 @@ use crate::cdp::{CdpError, CdpResult, Page};
const SNAPSHOT_JS: &str = include_str!("../../../browser-bundle/15-snapshot.js");
/// Install `window.__impeccableSnapshot` from [`SNAPSHOT_JS`] (idempotent).
+/// [`NATIVES_JS`] goes first in the same function, so the producer reaches
+/// the built-ins the new-document prelude stashed before the page's scripts
+/// ran, not whatever the page left on `window` (a site's own global `Map`).
pub fn ensure_snapshot_js(page: &mut Page<'_>) -> CdpResult<()> {
let expr = format!(
- "(function(){{ if (window.__impeccableSnapshot) return true;\n{SNAPSHOT_JS}\nwindow.__impeccableSnapshot = __impeccableSnapshot; return true; }})()"
+ "(function(){{ if (window.__impeccableSnapshot) return true;\n{NATIVES_JS}\n{SNAPSHOT_JS}\nwindow.__impeccableSnapshot = __impeccableSnapshot; return true; }})()"
);
page.evaluate_value(&expr)?;
Ok(())
diff --git a/crates/browser/tests/page_globals.rs b/crates/browser/tests/page_globals.rs
new file mode 100644
index 000000000..b1b013b82
--- /dev/null
+++ b/crates/browser/tests/page_globals.rs
@@ -0,0 +1,260 @@
+//! A page that replaces the JavaScript built-ins with its own still captures,
+//! and captures exactly as it would have without them.
+//!
+//! work24.go.kr declares a global `var Map = function () {...}`, so the
+//! snapshot producer's `new Map()` built the page's object and the capture
+//! failed with `states.set is not a function` (corpus observations-1004,
+//! round 11). Two servers hand out the same HTML, and only the classic script
+//! it loads differs, so the two captures must be equal byte for byte.
+//!
+//! - The capture test replaces or breaks every built-in the snapshot producer
+//! (`browser-bundle/05-natives.js` + `15-snapshot.js`) reaches for.
+//! - The scan test runs the whole URL engine, whose own page scripts (the
+//! visual pass's scroll-into-view, the scroll probe, consent and overlay
+//! handling) build Maps and Sets too, over two scripts: the class legacy
+//! sites ship (their own collection constructors, statics reassigned on
+//! the shared objects) and the full replacement set above.
+//!
+//! Skips cleanly when no browser is installed.
+
+use std::collections::HashMap;
+use std::io::{Read, Write};
+use std::net::{TcpListener, TcpStream};
+use std::time::Duration;
+
+use impeccable_browser::{
+ cdp::Browser, detect_url_evidence, discovery, snapshot_engine, BrowserEngine, EvidenceRequest,
+};
+use impeccable_detect::engines::ScanOptions;
+use serde_json::Value;
+
+/// Exercises every part of the capture: a linked stylesheet (with a media
+/// rule, a supports rule and keyframes), recorded states, a running
+/// animation, a shadow tree, a placeholder and an image. The faint text on a
+/// gradient below the first viewport sends the scan's visual-contrast pass
+/// through its scroll-into-view script, which keeps a `Map` of the scroll
+/// offsets it moved.
+const PAGE: &str = r#"<!doctype html><html><head>
+<meta charset="utf-8">
+<title>Globals</title>
+<script src="/globals.js"></script>
+<link rel="stylesheet" href="/site.css">
+</head><body>
+<header class="masthead"><h1 class="title">Employment services</h1></header>
+<main>
+ <p class="lede">Find work, training and benefits in one place.</p>
+ <form>
+ <input type="checkbox" checked> <label>Remember me</label>
+ <input type="text" placeholder="Search jobs">
+ <button disabled>Search</button>
+ </form>
+ <div class="pulse">New</div>
+ <img alt="" width="40" height="40" src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='40' height='40'%3E%3Crect width='40' height='40' fill='%23345'/%3E%3C/svg%3E">
+ <div id="host"></div>
+ <section class="band"><p class="faint">Office hours and holiday closures</p></section>
+</main>
+<script>
+ document.getElementById('host').attachShadow({ mode: 'open' }).innerHTML = '<button disabled>Inside</button>';
+</script>
+</body></html>"#;
+
+const CSS: &str = r#"body { font-family: Georgia, serif; margin: 0; color: #222; }
+.masthead { padding: 24px; background: #f4f1ea; }
+.title { font-size: 40px; }
+@media (min-width: 600px) { .lede { font-size: 20px; } }
+@supports (display: grid) { main { display: grid; gap: 12px; padding: 24px; } }
+@keyframes pulse { from { opacity: 0.4; } to { opacity: 1; } }
+.pulse { animation: pulse 600s steps(1, end) infinite; width: 60px; }
+.band { margin-top: 1400px; padding: 24px; background: linear-gradient(90deg, #6d6d6d, #7a7a7a); }
+.faint { color: #5f5f5f; font-size: 16px; }
+"#;
+
+/// What work24.go.kr does (a global `Map` constructor with its own API), and
+/// then every other built-in the snapshot producer and the URL engine's page
+/// scripts name, each replaced the way a legacy library or a careless global
+/// would replace it.
+const HOSTILE: &str = r#"
+var Map = function () { this.map = {}; };
+Map.prototype.put = function (k, v) { this.map[k] = v; };
+var Set = function () { this.items = []; };
+var WeakMap = function () {};
+var WeakSet = function () {};
+var Promise = function () { throw new Error('page Promise'); };
+var URL = function () { throw new Error('page URL'); };
+var Image = function () { throw new Error('page Image'); };
+var JSON = { stringify: function () { return '"page JSON"'; }, parse: function () { return null; } };
+var Math = { min: function () { return 0; }, max: function () { return 0; }, round: function () { return 0; } };
+var String = function () { return 'page String'; };
+var Number = function () { return 0; };
+var Boolean = function () { return false; };
+var CSS = {};
+var performance = {};
+var getComputedStyle = function () { return {}; };
+var matchMedia = function () { return { matches: false }; };
+var setTimeout = function () { return 0; };
+var clearTimeout = function () {};
+var requestAnimationFrame = function () { return 0; };
+var parseFloat = function () { return 0; };
+Reflect.construct = function () { throw new Error('page Reflect.construct'); };
+Reflect.apply = function () { throw new Error('page Reflect.apply'); };
+Array.from = function () { return []; };
+Array.isArray = function () { return false; };
+Object.keys = function () { return []; };
+Object.entries = function () { return []; };
+Object.assign = function (t) { return t; };
+"#;
+
+/// The class legacy sites ship: their own collection constructors and
+/// replaced statics on the built-in objects.
+const LEGACY: &str = r#"
+var Map = function () { this.map = {}; };
+Map.prototype.put = function (k, v) { this.map[k] = v; };
+var Set = function () { this.items = []; };
+var WeakMap = function () {};
+var WeakSet = function () {};
+Array.from = function () { return []; };
+Array.isArray = function () { return false; };
+Object.keys = function () { return []; };
+Object.entries = function () { return []; };
+Object.assign = function (t) { return t; };
+JSON.stringify = function () { return '"page JSON"'; };
+JSON.parse = function () { return null; };
+"#;
+
+/// The control: a script that touches nothing.
+const BENIGN: &str = "var pageReady = true;\n";
+
+fn serve(script: &'static str) -> u16 {
+ let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
+ let port = listener.local_addr().unwrap().port();
+ std::thread::spawn(move || {
+ for stream in listener.incoming().flatten() {
+ std::thread::spawn(move || handle(stream, script));
+ }
+ });
+ port
+}
+
+fn handle(mut stream: TcpStream, script: &str) {
+ let mut buf = [0u8; 8192];
+ let n = stream.read(&mut buf).unwrap_or(0);
+ let request = String::from_utf8_lossy(&buf[..n]);
+ let path = request.split_whitespace().nth(1).unwrap_or("/");
+ let (kind, body) = match path {
+ "/globals.js" => ("text/javascript", script),
+ "/site.css" => ("text/css", CSS),
+ _ => ("text/html; charset=utf-8", PAGE),
+ };
+ let head = format!(
+ "HTTP/1.0 200 OK\r\nContent-Type: {kind}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
+ body.len()
+ );
+ let _ = stream.write_all(head.as_bytes());
+ let _ = stream.write_all(body.as_bytes());
+ let _ = stream.flush();
+}
+
+fn browser() -> 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;
+ };
+ // A browser that is installed but will not start is a failure, not a skip.
+ Some(Browser::launch(&exe, &[], false).unwrap_or_else(|e| panic!("launch: {}", e.message)))
+}
+
+/// Load the page from `port`, capture it, and hand back the capture's JSON
+/// plus what the page's visual IO answers for the image.
+fn capture(browser: &mut Browser, port: u16) -> (Value, Value) {
+ let mut page = browser.new_page().unwrap();
+ page.goto(&format!("http://127.0.0.1:{port}/"), "load", Duration::from_secs(15))
+ .unwrap();
+ snapshot_engine::ensure_snapshot_js(&mut page).unwrap();
+ let json = snapshot_engine::capture_snapshot_json(&mut page).expect("capture");
+ let image = page
+ .evaluate_value(
+ "window.__impIO.loadImage(document.querySelector('img').src).then(r => r && { w: r.w, h: r.h })",
+ )
+ .expect("visual IO");
+ // The engine's own scripts (the CLI's asset capture reads resource
+ // timings) still reach every Performance method through the stash.
+ let entries = page
+ .evaluate_value("performance.getEntriesByType('navigation').length")
+ .expect("performance entries");
+ assert_eq!(entries, serde_json::json!(1));
+ // The global functions and the constructor facades the engine's own
+ // scripts reach (the scroll probe's and the validity probe's opacity
+ // reads, `new Array(n)`), even with the page's `parseFloat`,
+ // `Reflect.construct` and `Reflect.apply` replaced.
+ let scoped = page
+ .evaluate_value("[parseFloat('0.5'), new Array(3).length, Number('7'), Array.from('ab').length]")
+ .expect("scoped natives");
+ assert_eq!(scoped, serde_json::json!([0.5, 3, 7, 2]));
+ page.close();
+ (serde_json::from_str(&json).expect("capture json"), image)
+}
+
+#[test]
+fn page_replaced_builtins_do_not_change_the_capture() {
+ let Some(mut browser) = browser() else { return };
+ let hostile = serve(HOSTILE);
+ let benign = serve(BENIGN);
+
+ let (hostile_snap, hostile_image) = capture(&mut browser, hostile);
+ let (benign_snap, benign_image) = capture(&mut browser, benign);
+ browser.close();
+
+ // Every part of the capture that builds a Map, a Set or an array ran.
+ let els = hostile_snap["els"].as_array().expect("els");
+ assert!(els.len() > 10);
+ assert!(els.iter().any(|e| e.get("an").is_some()), "running animation recorded");
+ assert!(els.iter().any(|e| e.get("st").is_some()), "states recorded");
+ assert!(els.iter().any(|e| e.get("sh").is_some()), "shadow tree captured");
+ let linked = hostile_snap["linkedCss"].as_str().unwrap_or("");
+ assert!(linked.contains(".lede") && linked.contains("@keyframes pulse"), "{linked}");
+ assert_eq!(benign_image, serde_json::json!({ "w": 40, "h": 40 }));
+ assert_eq!(hostile_image, benign_image);
+ assert_eq!(hostile_snap, benign_snap);
+}
+
+#[test]
+fn page_replaced_builtins_do_not_change_the_scan() {
+ let env: HashMap<String, String> = std::env::vars().collect();
+ if discovery::find_browser(&env).is_err() {
+ eprintln!("skip: no installed browser found");
+ return;
+ }
+ let legacy = serve(LEGACY);
+ let hostile = serve(HOSTILE);
+ let benign = serve(BENIGN);
+ let scan = |port: u16| {
+ let engine = BrowserEngine::new(env.clone());
+ let mut browser = engine.launch().expect("launch");
+ let options = ScanOptions { viewport: Some((1280, 800)), ..Default::default() };
+ let request = EvidenceRequest { screenshot: false, ..Default::default() };
+ let (findings, evidence) = detect_url_evidence(
+ &mut browser,
+ &format!("http://127.0.0.1:{port}/"),
+ &options,
+ "load",
+ 100,
+ &request,
+ )
+ .expect("scan");
+ browser.close();
+ let ids: Vec<String> = findings.iter().map(|f| format!("{}|{}", f.antipattern, f.snippet)).collect();
+ (ids, evidence.scan_snapshot.is_some())
+ };
+ let (benign_findings, benign_captured) = scan(benign);
+ assert!(benign_captured);
+ assert!(
+ benign_findings.iter().any(|f| f.starts_with("low-contrast|")),
+ "the faint band reaches the visual pass: {benign_findings:?}"
+ );
+ for (name, port) in [("legacy", legacy), ("hostile", hostile)] {
+ let (findings, captured) = scan(port);
+ assert!(captured, "{name}");
+ assert_eq!(findings, benign_findings, "{name}");
+ }
+}
diff --git a/crates/bundle/src/lib.rs b/crates/bundle/src/lib.rs
index 229966031..e58c9b21e 100644
--- a/crates/bundle/src/lib.rs
+++ b/crates/bundle/src/lib.rs
@@ -49,6 +49,7 @@ macro_rules! page_js {
page_js![
"00-header.js",
+ "05-natives.js",
"10-probe.js",
"15-snapshot.js",
"30-scan-common.js",
@@ -77,6 +78,7 @@ fn src(name: &str) -> Cow<'static, str> {
/// `@@WASM@@` the embedded module + synchronous instantiation.
const ORDER: &[&str] = &[
"00-header.js",
+ "05-natives.js",
"10-probe.js",
"15-snapshot.js",
"@@GLUE@@",
@@ -93,6 +95,9 @@ const ORDER: &[&str] = &[
/// (the module ships beside it as `core_bg.wasm`; no base64: the offscreen
/// document fetches it) + the scan plumbing and visual-contrast orchestration
/// + the offscreen session protocol.
+/// `05-natives.js` is left out of the snapshot piece on purpose: a content
+/// script already has its own globals, and in Firefox its `window` is an Xray
+/// view of the page's, so natives built there throw on every capture.
const EXT_SNAPSHOT: &[&str] = &["15-snapshot.js"];
const EXT_OVERLAY: &[&str] = &["40-overlay.js"];
const EXT_CORE: &[&str] = &["@@GLUE@@", "@@LOADER@@", "30-scan-common.js", "35-visual.js", "60-offscreen.js"];
@@ -420,6 +425,26 @@ mod tests {
assert_eq!(ext.antipatterns_json, "[]\n");
}
+ /// The extension's content scripts already run with their own globals,
+ /// and in Firefox a content script's `window` is an Xray wrapper of the
+ /// page's: natives built from it throw (`Permission denied to access
+ /// property Symbol.iterator`) and every extension capture failed. So the
+ /// page-world natives file stays out of every extension piece.
+ #[test]
+ fn extension_pieces_leave_out_the_page_world_natives() {
+ let natives = page_js("05-natives.js").unwrap();
+ for parts in [EXT_SNAPSHOT, EXT_OVERLAY, EXT_CORE] {
+ assert!(!parts.contains(&"05-natives.js"), "{parts:?}");
+ }
+ let ext = extension_pieces("const glue = 1;\n", &[0, 97, 115, 109], "[]\n");
+ for js in [&ext.snapshot_js, &ext.overlay_js, &ext.core_js] {
+ assert!(!js.contains(natives));
+ assert!(!js.contains("__impeccableBuildNatives"));
+ }
+ // The in-page bundle still carries it.
+ assert!(in_page_bundle("const glue = 1;\n", &[0, 97, 115, 109]).contains(natives));
+ }
+
#[test]
fn capture_contract_holds() {
check_capture_contract().unwrap();
diff --git a/crates/live/assets/detect-antipatterns-browser.js b/crates/live/assets/detect-antipatterns-browser.js
index c29abac69..022dfdedb 100644
--- a/crates/live/assets/detect-antipatterns-browser.js
+++ b/crates/live/assets/detect-antipatterns-browser.js
@@ -11,6 +11,133 @@
*/
(function () {
if (typeof window === 'undefined') return;
+// --- browser-bundle/05-natives.js ---
+// The JavaScript built-ins the page JS uses, held where page script cannot
+// replace them. This code runs in the page's own world (the URL engine and
+// the live /detect.js script), where a site may declare `var Map = ...` or
+// assign `Array.from = ...` (work24.go.kr ships its own global `Map`, which
+// failed every capture with `states.set is not a function`).
+//
+// The URL engine runs this file once more, as a script on every new document
+// before any page script (`Page::initialize` in crates/browser), and that run
+// stashes what it built on `window.__impeccableNatives`, read-only and
+// non-enumerable. Later runs take the stash. Without one (the live script
+// tag) the current globals are used as they are: live mode sees the user's
+// own app.
+//
+// The extension does not ship this file: its content scripts already have
+// their own globals, and in Firefox `window` there is an Xray view of the
+// page's window, so natives built from it throw (crates/bundle EXT_SNAPSHOT).
+// The builder reads `globalThis`, never `window`, for the same reason: in the
+// page's own world the two are one object.
+//
+// `performance` is the page's own Performance object, shared with the page:
+// a page that replaces the global is covered, one that assigns
+// `performance.now` or patches `Performance.prototype` is not.
+//
+// The stash is page-visible: `Object.getOwnPropertyNames(window)` lists
+// `__impeccableNatives` on every document the URL engine loads, and a page
+// that declares its own global `let __impeccableNatives` fails to load that
+// script. Both are vanishingly rare.
+//
+// The `const` at the end shadows the globals for everything after it in the
+// same function scope, which every consumer of this file provides (the
+// in-page bundle's IIFE, the URL engine's wrapper and prelude).
+// Statics (`Array.from`, `JSON.stringify`, `Object.keys`, ...) are copied at
+// capture time, so a later assignment to the shared object reaches nothing
+// here. Prototype methods (`Map.prototype.set`) are not copied: a page that
+// rewrites those is out of reach.
+//
+// The builder must reach every built-in through `g`, never by bare name:
+// while it runs, the bare names are the `const` below, not yet initialized.
+
+function __impeccableBuildNatives(g) {
+ const O = g.Object;
+ const R = g.Reflect;
+ const freeze = O.freeze;
+ // Held now, so a page that later replaces `Reflect.construct` or
+ // `Reflect.apply` on the shared object cannot reach the facades below.
+ const construct = R.construct;
+ const apply = R.apply;
+ // Own properties of `owner`, functions bound to it (`Array.from` and
+ // `Promise.resolve` read `this`), onto `target`.
+ const copyStatics = (owner, target) => {
+ if (owner == null) return target;
+ for (const name of O.getOwnPropertyNames(owner)) {
+ if (name === 'length' || name === 'name' || name === 'prototype' || name === 'caller' || name === 'arguments') continue;
+ let value;
+ try { value = owner[name]; } catch { continue; }
+ O.defineProperty(target, name, {
+ value: typeof value === 'function' ? R.apply(g.Function.prototype.bind, value, [owner]) : value,
+ enumerable: false, writable: false, configurable: false,
+ });
+ }
+ return target;
+ };
+ const namespace = (owner) => (owner == null ? owner : freeze(copyStatics(owner, O.create(null))));
+ // A constructor whose statics the page JS reads: calls and `new` reach the
+ // native, `instanceof` still works, the statics are the copies.
+ const callable = (native) => {
+ if (typeof native !== 'function') return native;
+ const facade = function (...args) {
+ return new.target ? construct(native, args) : apply(native, undefined, args);
+ };
+ O.defineProperty(facade, 'prototype', { value: native.prototype, writable: false });
+ return freeze(copyStatics(native, facade));
+ };
+ const bound = (name) => {
+ const fn = g[name];
+ return typeof fn === 'function' ? R.apply(g.Function.prototype.bind, fn, [g]) : undefined;
+ };
+ return freeze({
+ // Constructors used for `new` or calls only, and objects whose methods
+ // live on their prototype: the natives themselves.
+ Map: g.Map, Set: g.Set, WeakMap: g.WeakMap, WeakSet: g.WeakSet,
+ Error: g.Error, URL: g.URL, Image: g.Image, ResizeObserver: g.ResizeObserver,
+ String: g.String, Boolean: g.Boolean,
+ // Constructors whose statics are read.
+ Array: callable(g.Array), Object: callable(g.Object), Number: callable(g.Number),
+ Promise: callable(g.Promise),
+ // Namespaces.
+ JSON: namespace(g.JSON), Math: namespace(g.Math), Reflect: namespace(g.Reflect),
+ CSS: namespace(g.CSS),
+ // The page's own Performance object: its methods (`now`,
+ // `getEntriesByType`, ...) live on its prototype, like Map's.
+ performance: g.performance,
+ // Window functions.
+ getComputedStyle: bound('getComputedStyle'), matchMedia: bound('matchMedia'),
+ setTimeout: bound('setTimeout'), clearTimeout: bound('clearTimeout'),
+ requestAnimationFrame: bound('requestAnimationFrame'),
+ // Global functions that do not read `this`.
+ parseFloat: g.parseFloat,
+ });
+}
+
+const __impeccableNatives = (() => {
+ const g = globalThis;
+ try {
+ const stash = g.__impeccableNatives;
+ if (stash && typeof stash === 'object') return stash;
+ } catch { /* fall through */ }
+ try { return __impeccableBuildNatives(g); } catch { /* fall through */ }
+ return {
+ Map: g.Map, Set: g.Set, WeakMap: g.WeakMap, WeakSet: g.WeakSet,
+ Error: g.Error, URL: g.URL, Image: g.Image, ResizeObserver: g.ResizeObserver,
+ String: g.String, Boolean: g.Boolean, Array: g.Array, Object: g.Object,
+ Number: g.Number, Promise: g.Promise, JSON: g.JSON, Math: g.Math,
+ Reflect: g.Reflect, CSS: g.CSS, performance: g.performance,
+ getComputedStyle: g.getComputedStyle, matchMedia: g.matchMedia,
+ setTimeout: g.setTimeout, clearTimeout: g.clearTimeout,
+ requestAnimationFrame: g.requestAnimationFrame, parseFloat: g.parseFloat,
+ };
+})();
+
+const {
+ Map, Set, WeakMap, WeakSet, Error, URL, Image, ResizeObserver, String, Boolean,
+ Array, Object, Number, Promise, JSON, Math, Reflect, CSS, performance,
+ getComputedStyle, matchMedia, setTimeout, clearTimeout, requestAnimationFrame,
+ parseFloat,
+} = __impeccableNatives;
// --- browser-bundle/10-probe.js ---
// The DOM probe the WASM rule core calls back into. Pure measurement: one
// function per DOM API the rules read (see crates/core/src/browser/dom.rs for
@@ -605,8 +732,8 @@ function __snapConditionalCssRuleIsActive(rule) {
const constructorName = rule?.constructor?.name || '';
if (constructorName === 'CSSMediaRule' || type === 4) {
const condition = rule.conditionText || rule.media?.mediaText || '';
- if (!condition || typeof window.matchMedia !== 'function') return true;
- try { return window.matchMedia(condition).matches; }
+ if (!condition || typeof matchMedia !== 'function') return true;
+ try { return matchMedia(condition).matches; }
catch { return true; }
}
if (constructorName === 'CSSSupportsRule' || type === 12) {
diff --git a/docs/CLI-CONTRACT.md b/docs/CLI-CONTRACT.md
index ead3aecc3..885d73609 100644
--- a/docs/CLI-CONTRACT.md
+++ b/docs/CLI-CONTRACT.md
@@ -374,6 +374,7 @@ Optional keys added later by engines (appended after the above): `ignoreValue` (
- **Round 8 text and CSS-text forms** (corpus run 35). `line-length` divides the characters that reached the element's rendered lines, not the UTF-16 length of its `textContent`: the text of a `style`, `script`, `noscript` or `template` descendant and of a `display: none` one is left out, runs of collapsible white space (space, tab, line feed, carriage return, form feed) count once and none at either end unless the element computes `white-space: pre`, `pre-wrap` or `break-spaces`, and combining marks (Unicode `M*`) and format characters (`Cf`) are not counted. The gate that decides whether the element is long enough to measure still reads the raw length. `overused-font` (URL engine) keeps its element-count decision and snippet, and stands down when the face it would name sets under 5% of the characters in text that has a box (each element in its selector list weighs the characters of its own text nodes, white space collapsed; text that is or sits under `hidden`, `display: none`, `visibility: hidden` or `collapse`, or `content-visibility: hidden` is not weighed, opacity is not read); with no such text the element count stands; the static engine's form is unchanged. `side-tab`: the stylesheet scan for pseudo-element stripes (both engines) skips a stripe whose background has a `url()` layer and no token that parses as a colour or is a `var()`; in the URL engine the stylesheet form does not stand when an element its selector resolves to already carries the element form for the same pseudo-element. `marquee` (URL engine): the stylesheet form stands only when an element its selector resolves to carries something to read or look at: text, an `img`, `picture`, `video`, `canvas`, `iframe`, `object`, `embed` or `marquee` element (itself or inside it), an `svg`, `image` or `use` inside it, a `url()` background on it or under it, or generated content that is not empty; a selector that resolves to nothing stands as before. `bounce-easing` by animation name (both engines, element and stylesheet forms; the class and `cubic-bezier` forms are unchanged): the name does not report when the keyframes for every bounce-named animation are readable (the page's `@keyframes` in the URL engine's element form, the stylesheet text elsewhere) and only pulse: every declaration is `opacity`, a `transform` made only of `scale*()` functions with factors from 0 to 1 (or `none`), a `scale` with factors from 0 to 1, or an `animation-timing-function` with no `linear()`, no `var()` and no `cubic-bezier` whose y values leave 0 to 1. Any other property or value, an empty set of keyframes, or keyframes that cannot be found keeps the finding. The stylesheet form reads on past a pulse to the next declaration that names a bounce.
- **Round 10 contrast surfaces** (corpus run 47; URL engine unless noted). A box at an opacity of 0.02 or less that a scroll or view timeline holds there (its computed `animation-timeline` is `scroll()`, `view()` or a named timeline, an animation moving its `opacity` was running at capture, and it is the box's only animation that sets `opacity`) counts at the opacity its end keyframe sets (the first keyframe for `reverse`) in `low-contrast`'s opacity gate and fold and wherever the painted-at-capture predicate counts an element's own opacity: the Text and Box paint gates, `painted_at_capture` (and the page checks that ask it), the text-box test and the shown-across test behind the colour-pair claim (`content-hidden-at-rest` is ungated and unchanged); a composition other than `replace`, a direction other than `normal` or `reverse`, or an end keyframe that sets no opacity keeps the captured value. A `filter` on the box that paints the text's surface, or on a box around it, repaints the ink, the surface, the gradient stops and the element's own fill alike, and `low-contrast` and `gray-on-color` read the painted colours (the snippet prints them); a filter below the surface's box that moves the ink, a filter the engine cannot model, a filter a running animation is moving, a colour-moving filter that also blurs, and SVG text with no readable fill still take no verdict. The structural layer climb follows children that each cover the whole text run past its usual six levels, up to 24, under the same node budget, so a picture nested deep in a sibling is found before the sibling's own fill. Ink in exactly the colour of the page ground (`body` or `html`) over a `body` or `html` that paints a raster image other than a small repeating texture takes no `1.0:1` verdict, as where the hit-test stacks are silent. A positioned `::before` or `::after` that covers the run, sits at a negative `z-index` that the capture says paints over its box (at `auto` or above it paints over the text, not under it), has no colour of its own (or one that an opaque layer filling the face hides), is not at an explicit `opacity` under 0.9, `visibility: hidden`, or moved, scaled or turned by a `transform`, `translate`, `scale` or `rotate` other than the identity, and paints only gradient layers whose bottom layer is opaque and fills the face, is the text's surface: the stops of the topmost layer that is opaque at every stop and fills the face (as the computed `background` names it: tiled with `repeat` or `round` on both axes at a size with no zero, or a size of `auto`, `cover`, `100% 100%`, `100% auto` or `auto 100%`, which for a gradient is the whole positioning area, at a percentage, keyword or zero position; a size or position holding any function such as `calc()` or `var()`, a `space` tile, or anything unparsed does not fill; the layers beneath a filling layer are hidden and not read), else the bottom layer's stops, plus each of them under every translucent stop above, printed as `gradient on <box>::after`. Where that face has a `filter` of its own, or its layers combine into more than 256 colours, it is still the surface (the box's own background is not scored in its place) but the verdict is withheld. A fade that the element pass's opacity fold scores (every faded box below the surface's box, the surface resolved and not a pseudo-element's, not on a page ground that paints a picture, the fold not giving up) is no longer a visual-contrast reason, so such text is not read from pixels on that account. A pixel-pass finding on routed text does not report a colour pair (ink, severity, ratio, median, bar and reasons) the page's pixel pass already reported.
- **Round 10 labels, cards and colour tests** (corpus run 47; both engines unless noted). *Demo windows on landmarks.* A `section`, `article`, `header`, `footer` or `nav` is still never a demo frame by its scale, tilt, size, preview caption or sample caption, but it is a demo window by its traffic lights: its first child is a title bar (at least 60% of the box's width, within 24px of its top, 12px to 72px tall, the box at least twice that and at least 120px wide) holding a trio of dots that ends in the bar's leading half, and the box, the bar and every dot have rects. A landmark that holds the page's `h1`, or at least half the page's rendered text (`script`, `style`, `noscript` and `template` text left out; a walk past 2,000 nodes counts as holding the page), is the page's own content and is not a window. Text in such a window takes the framed-demo treatment (r5-p26). *gray-on-color.* A background that clears the channel-spread bar reads as colour only when its OKLCH lightness is under 0.9 or its OKLCH chroma is 0.09 or more, so cream `#feeed4` (L 0.955, C 0.038) and amber-100 `#fef3c7` (C 0.058) carry gray ink as an off-white does, while amber-300 `#fcd34d` (C 0.153) still reads as colour. The class form (both engines and the text engine's markup matcher) no longer counts a `bg-<hue>-50` or `bg-<hue>-100` utility as the coloured fill, since every Tailwind hue at those shades sits on the pale side of that line; `-200` and darker still count, and the side-tab stripe-child reader still sees the pale shades. *gradient-text.* The element form (both engines) and, in the URL engine, the ramp test behind it do not report a gradient whose colour stops all lie within 12 of the first stop on each channel and on alpha (scaled to 255), with at least two stops, and every stop readable: a hex colour or a colour function the parser resolves, after an optional first argument that sets direction, shape, position or colour space, with bare lengths read as transition hints. A `var()`, a named colour or a colour function the parser cannot read makes the value unread, and it reports as before. The stylesheet form stands down only when every gradient function read whole inside its 200-character window is one colour and no `)` in the window closes a function opened before it. The clipped-ancestor test (both engines) and the visual pass (URL engine) read a per-layer `background-clip: text, text` as clipped text; gradient-text's element form still reads only a single `text` clip (taste call r9-t4). *nested-cards* (URL engine). A box with no element child whose text renders on one recorded line, at most three line-heights tall, is a single-line label, whatever its padding; with no recorded lines it is read as before. A card's border side counts as an edge only when the border, composited over the box's own fill over the painted surface under the box, sits at least 8 from that surface on some channel. That surface is used only when the text the box holds reads on it at 3:1 or better (the box's own ink and up to eight elements with painted text of their own, in a 64-node walk that skips subtrees at `display: none`, `content-visibility: hidden` or opacity 0.01 and below, and own text at `visibility: hidden` or `collapse`); otherwise, and where no surface is read, every drawn border counts as before. Whether an inner box shows a border at all (r4-p16) is still read from its computed style. *Vanishing ink* (URL engine). When an element's `low-contrast` finding prints a ratio under 1.25:1 (`VANISHING_INK_RATIO`; one decimal at that range, so a printed `1.2` is a measured ratio under 1.25), its `tiny-text` and `undersized-ui-text` findings are dropped and `low-contrast` reports alone. Size findings stand when that `low-contrast` finding is turned off (`disabledRules`), ignored inline, handed to the pixel pass, withdrawn when a colour claim moves to a copy wholly on screen, or removed by the CLI after the scan: `ignoreRules`, or any `--scope` (`low-contrast` declares none). The CLI passes those rules to the engine for this one test; nothing else reads them. *Also:* class markers of page furniture (`label`, `nav`, `badge` and the rest) are not read off `html`, which holds script state flags, and are still read on `body` and below; a heading inside a `blockquote` or `q` sets no rhythm and counts toward no page minimum (URL engine); a heading level other than `h1` whose second most frequent size is a 1.25 step or more above its most frequent one and within 25% of it in count has no settled size and leaves the flat-type-hierarchy ladder; `organic-clip-path` reads a polygon whose vertices take two to four values on one axis and step evenly on the other, swinging back and forth by one amount at least three times, as a zigzag edge, and a `path()` whose straight sides lie on all four edges of the box its points and sampled curves span, joined by curves that each turn a corner, as a rounded rectangle, and reports the same snippet under the same selector once (inline styles report under `body`, so two inline shapes with the same vertex count report once); `wide-tracking` does not report text whose own letters, or whole run when it has none of its own, are at least half Han, kana or Hangul; and `overused-font` (URL engine) does not name a face that heads the stack of a page whose letters are mostly CJK when it sets under 5% of those letters.
+ - **The page's own built-ins** (Rust engine). Before any page script runs, every document the URL engine loads gets the built-ins the engine's page scripts use (`Map`, `Set`, `Array.from`, `JSON.stringify`, ...) captured from its untouched globals, so a page that declares its own global `Map` or reassigns `Array.from` still scans. The stash is a page-visible, non-enumerable `window.__impeccableNatives`, so a page can detect the scan, and a page script declaring `let __impeccableNatives` throws.
- `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`.