The headless browser for AI agents and web scraping
fix(input): bypass author accessors during native activation
Jørgen Sandhaugd88df745ec19
diff --git a/crates/obscura-cdp/src/domains/input.rs b/crates/obscura-cdp/src/domains/input.rsindex 382d8e98..bb7d4ddf 100644--- a/crates/obscura-cdp/src/domains/input.rs+++ b/crates/obscura-cdp/src/domains/input.rs@@ -203,8 +203,8 @@ pub async fn handle(var type = (clickTarget.getAttribute && clickTarget.getAttribute('type') || '').toLowerCase();\if (globalThis.__obscura_isDisabled(clickTarget)) return;\var checkable = tag === 'INPUT' && (type === 'checkbox' || type === 'radio');\- var oldChecked = checkable ? !!clickTarget.checked : false;\- var oldIndeterminate = checkable ? !!clickTarget.indeterminate : false;\+ var oldChecked = checkable ? globalThis.__obscura_inputChecked(clickTarget) : false;\+ var oldIndeterminate = checkable ? globalThis.__obscura_inputIndeterminate(clickTarget) : false;\var radioStates = null;\if (checkable && type === 'radio') {{\var radioName = clickTarget.getAttribute('name') || '';\@@ -214,24 +214,24 @@ pub async fn handle(for (var ri = 0; ri < candidates.length; ri++) {{\var radio = candidates[ri];\if ((radio.getAttribute('type') || '').toLowerCase() !== 'radio' || (radio.getAttribute('name') || '') !== radioName || radio.form !== clickTarget.form) continue;\- radioStates.push([radio, !!radio.checked]);\- if (radio !== clickTarget) radio.checked = false;\+ radioStates.push([radio, globalThis.__obscura_inputChecked(radio)]);\+ if (radio !== clickTarget) globalThis.__obscura_setInputChecked(radio, false);\}}\}}\- clickTarget.checked = true;\+ globalThis.__obscura_setInputChecked(clickTarget, true);\}} else if (checkable) {{\- clickTarget.checked = !oldChecked;\- clickTarget.indeterminate = false;\+ globalThis.__obscura_setInputChecked(clickTarget, !oldChecked);\+ globalThis.__obscura_setInputIndeterminate(clickTarget, false);\}}\var click = globalThis.__obscura_markTrusted(new MouseEvent('click', {{bubbles:true,cancelable:true,composed:true,view:globalThis,clientX:{x},clientY:{y},button:0,buttons:0,detail:{click_count},altKey:{alt_key},ctrlKey:{ctrl_key},metaKey:{meta_key},shiftKey:{shift_key}}}));\var cancelled = !clickTarget.dispatchEvent(click);\if (cancelled) {{\if (radioStates) {{\- for (var rr = 0; rr < radioStates.length; rr++) radioStates[rr][0].checked = radioStates[rr][1];\- }} else if (checkable) {{ clickTarget.checked = oldChecked; clickTarget.indeterminate = oldIndeterminate; }}\+ for (var rr = 0; rr < radioStates.length; rr++) globalThis.__obscura_setInputChecked(radioStates[rr][0], radioStates[rr][1]);\+ }} else if (checkable) {{ globalThis.__obscura_setInputChecked(clickTarget, oldChecked); globalThis.__obscura_setInputIndeterminate(clickTarget, oldIndeterminate); }}\return;\}}\- if (checkable && clickTarget.checked !== oldChecked) {{\+ if (checkable && globalThis.__obscura_inputChecked(clickTarget) !== oldChecked) {{\try {{ clickTarget.dispatchEvent(globalThis.__obscura_markTrusted(new Event('input', {{bubbles:true}}))); }} catch(e) {{}}\try {{ clickTarget.dispatchEvent(globalThis.__obscura_markTrusted(new Event('change', {{bubbles:true}}))); }} catch(e) {{}}\return;\diff --git a/crates/obscura-cdp/tests/input_activation_author_accessors.rs b/crates/obscura-cdp/tests/input_activation_author_accessors.rsnew file mode 100644index 00000000..87777d51--- /dev/null+++ b/crates/obscura-cdp/tests/input_activation_author_accessors.rs@@ -0,0 +1,186 @@+#![cfg(feature = "render")]++use obscura_cdp::dispatch::{dispatch, CdpContext};+use obscura_cdp::types::CdpRequest;+use serde_json::{json, Value};+use tokio::io::{AsyncReadExt, AsyncWriteExt};+use tokio::net::TcpListener;++async fn serve_fixture() -> String {+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();+ let addr = listener.local_addr().unwrap();+ tokio::spawn(async move {+ let (mut socket, _) = listener.accept().await.unwrap();+ let mut buf = [0u8; 2048];+ let _ = socket.read(&mut buf).await.unwrap();+ let body = r#"<!doctype html><html><head><style>+ input { display: block; width: 40px; height: 40px; margin: 10px }+ </style></head><body>+ <input id="box" type="checkbox">+ <input id="first" type="radio" name="choice" checked>+ <input id="second" type="radio" name="choice">+ <script>+ window.writes = []; window.events = []; window.cancel = false;+ for (const id of ['box', 'first', 'second']) {+ const el = document.getElementById(id);+ if (id === 'box') el.indeterminate = true;+ for (const key of ['checked', 'indeterminate']) {+ let proto = Object.getPrototypeOf(el), descriptor;+ while (proto && !(descriptor = Object.getOwnPropertyDescriptor(proto, key))) {+ proto = Object.getPrototypeOf(proto);+ }+ Object.defineProperty(el, key, {+ configurable: true,+ get() { return descriptor.get.call(this); },+ set(value) { writes.push(id + ':' + key); descriptor.set.call(this, value); }+ });+ }+ for (const kind of ['click', 'input', 'change']) {+ el.addEventListener(kind, e => {+ events.push([id, kind, el.checked, el.indeterminate]);+ if (kind === 'click' && cancel) e.preventDefault();+ });+ }+ }+ </script>+ </body></html>"#;+ let response = format!(+ "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",+ body.len()+ );+ let _ = socket.write_all(response.as_bytes()).await;+ });+ format!("http://{addr}/")+}++async fn cdp(ctx: &mut CdpContext, id: u64, method: &str, params: Value, sid: &str) -> Value {+ let response = dispatch(+ &CdpRequest {+ id,+ method: method.to_string(),+ params,+ session_id: Some(sid.to_string()),+ },+ ctx,+ )+ .await;+ assert!(response.error.is_none(), "CDP {method} failed: {:?}", response.error);+ response.result.unwrap_or_else(|| json!({}))+}++async fn evaluate(ctx: &mut CdpContext, id: u64, expression: &str, sid: &str) -> Value {+ cdp(+ ctx,+ id,+ "Runtime.evaluate",+ json!({"expression": expression, "returnByValue": true, "awaitPromise": true}),+ sid,+ )+ .await+}++async fn setup() -> (CdpContext, String) {+ std::env::set_var("OBSCURA_ALLOW_PRIVATE_NETWORK", "1");+ let url = serve_fixture().await;+ let mut ctx = CdpContext::new();+ let page_id = ctx.create_page();+ let sid = "author-accessors-session";+ ctx.sessions.insert(sid.to_string(), page_id);+ cdp(&mut ctx, 1, "Page.navigate", json!({"url": url, "waitUntil": "load"}), sid).await;+ (ctx, sid.to_string())+}++/// Click the centre of `selector` the way a real pointer would.+async fn click_element(ctx: &mut CdpContext, id: u64, sid: &str, selector: &str) {+ let rect = evaluate(+ ctx,+ id,+ &format!(+ "JSON.stringify(document.querySelector('{selector}').getBoundingClientRect().toJSON())"+ ),+ sid,+ )+ .await;+ let rect: Value = serde_json::from_str(rect["result"]["value"].as_str().unwrap()).unwrap();+ let x = rect["x"].as_f64().unwrap() + rect["width"].as_f64().unwrap() / 2.0;+ let y = rect["y"].as_f64().unwrap() + rect["height"].as_f64().unwrap() / 2.0;+ for kind in ["mousePressed", "mouseReleased"] {+ cdp(+ ctx,+ id + 1,+ "Input.dispatchMouseEvent",+ json!({"type": kind, "x": x, "y": y, "button": "left", "clickCount": 1}),+ sid,+ )+ .await;+ }+}++async fn snapshot(ctx: &mut CdpContext, sid: &str) -> Value {+ let value = evaluate(ctx, 90, r#"JSON.stringify({+ box: document.getElementById('box').checked,+ indeterminate: document.getElementById('box').indeterminate,+ first: document.getElementById('first').checked,+ second: document.getElementById('second').checked,+ writes, events+ })"#, sid).await;+ serde_json::from_str(value["result"]["value"].as_str().unwrap()).unwrap()+}++async fn activate(ctx: &mut CdpContext, sid: &str, id: &str, pointer: bool) {+ if pointer {+ click_element(ctx, 20, sid, &format!("#{id}")).await;+ } else {+ evaluate(ctx, 20, &format!("document.getElementById('{id}').click()"), sid).await;+ }+}++async fn verify_activation(pointer: bool) {+ let (mut ctx, sid) = setup().await;+ activate(&mut ctx, &sid, "box", pointer).await;+ let s = snapshot(&mut ctx, &sid).await;+ assert_eq!(s["writes"], json!([]), "native activation must bypass author setters: {s}");+ assert_eq!(s["box"], true);+ assert_eq!(s["indeterminate"], false);+ assert_eq!(s["events"], json!([+ ["box", "click", true, false], ["box", "input", true, false], ["box", "change", true, false]+ ]));+ evaluate(&mut ctx, 30, "events = []", &sid).await;+ activate(&mut ctx, &sid, "second", pointer).await;+ let s = snapshot(&mut ctx, &sid).await;+ assert_eq!(s["writes"], json!([]), "radio peers must bypass author setters: {s}");+ assert_eq!(s["first"], false);+ assert_eq!(s["second"], true);+ assert_eq!(s["events"], json!([+ ["second", "click", true, false], ["second", "input", true, false], ["second", "change", true, false]+ ]));+ evaluate(&mut ctx, 40, "document.getElementById('box').checked = false", &sid).await;+ let s = snapshot(&mut ctx, &sid).await;+ assert_eq!(s["writes"], json!(["box:checked"]), "script assignment still invokes author setter");+ assert_eq!(s["box"], false);+}++async fn verify_cancellation(pointer: bool) {+ let (mut ctx, sid) = setup().await;+ evaluate(&mut ctx, 10, "cancel = true", &sid).await;+ activate(&mut ctx, &sid, "box", pointer).await;+ activate(&mut ctx, &sid, "second", pointer).await;+ let s = snapshot(&mut ctx, &sid).await;+ assert_eq!(s["writes"], json!([]), "activation and rollback bypass author setters: {s}");+ assert_eq!(s["box"], false);+ assert_eq!(s["indeterminate"], true);+ assert_eq!(s["first"], true);+ assert_eq!(s["second"], false);+ assert_eq!(s["events"], json!([+ ["box", "click", true, false], ["second", "click", true, false]+ ]), "canceled clicks expose pre-activation state but emit no input/change");+}++#[tokio::test(flavor = "current_thread")]+async fn native_pointer_activation_bypasses_author_setters() { verify_activation(true).await; }+#[tokio::test(flavor = "current_thread")]+async fn element_click_activation_bypasses_author_setters() { verify_activation(false).await; }+#[tokio::test(flavor = "current_thread")]+async fn native_pointer_cancellation_restores_internal_state() { verify_cancellation(true).await; }+#[tokio::test(flavor = "current_thread")]+async fn element_click_cancellation_restores_internal_state() { verify_cancellation(false).await; }diff --git a/crates/obscura-js/js/bootstrap.js b/crates/obscura-js/js/bootstrap.jsindex e18d4da4..148d6bff 100644--- a/crates/obscura-js/js/bootstrap.js+++ b/crates/obscura-js/js/bootstrap.js@@ -27,6 +27,8 @@ const __obscuraCore = globalThis.Deno.core;'__obscura_liveFrameIds', '__obscura_forgetFrame','__obscura_registerLinkedStylesheet', '__obscura_activateLabel','__obscura_isDisabled', '__obscura_labeledControl', '__obscura_interactiveHost',+ '__obscura_inputChecked', '__obscura_setInputChecked',+ '__obscura_inputIndeterminate', '__obscura_setInputIndeterminate','__markParserScripts', '__obscura_hasPendingDynamicScripts','__obscura_hasPendingLoadDelayingScripts', '__obscura_hasPendingParserBlockingScripts','__obscura_nextPendingTimeoutDelay',@@ -759,6 +761,32 @@ function _loadFormState(nid) {_formStateLoaded.add(nid);}+// Native activation changes checkedness without invoking author-defined IDL+// accessors. Frameworks may wrap those accessors to track script assignments.+function _inputChecked(el) {+ if (_formChecked[el._nid] === undefined) _loadFormState(el._nid);+ if (_formChecked[el._nid] !== undefined) return _formChecked[el._nid];+ return el.hasAttribute("checked");+}+function _setInputChecked(el, value) {+ const checked = !!value;+ _formChecked[el._nid] = checked;+ _dom("set_form_checked", el._nid, String(checked));+}+function _inputIndeterminate(el) {+ if (_formIndeterminate[el._nid] === undefined) _loadFormState(el._nid);+ return _formIndeterminate[el._nid] === true;+}+function _setInputIndeterminate(el, value) {+ const indeterminate = !!value;+ _formIndeterminate[el._nid] = indeterminate;+ _dom("set_form_indeterminate", el._nid, String(indeterminate));+}+globalThis.__obscura_inputChecked = _inputChecked;+globalThis.__obscura_setInputChecked = _setInputChecked;+globalThis.__obscura_inputIndeterminate = _inputIndeterminate;+globalThis.__obscura_setInputIndeterminate = _setInputIndeterminate;+// HTML "ASCII whitespace": U+0009 TAB, U+000A LF, U+000C FF, U+000D CR, U+0020 SPACE.// Class token splitting (classList, getElementsByClassName) uses exactly this set.// JS \s is wider (U+000B, U+00A0, U+2028, etc.), so it must not be used here.@@ -3912,8 +3940,8 @@ class Element extends Node {}let _oldChecked = false, _oldIndeterminate = false, _radioStates = null;if (_checkable) {- _oldChecked = !!this.checked;- _oldIndeterminate = !!this.indeterminate;+ _oldChecked = _inputChecked(this);+ _oldIndeterminate = _inputIndeterminate(this);if (_type === 'radio') {const _name = this.getAttribute('name') || '';if (_name) {@@ -3923,29 +3951,29 @@ class Element extends Node {const r = _all[i];if (((r.getAttribute('type') || '').toLowerCase()) !== 'radio') continue;if ((r.getAttribute('name') || '') !== _name || r.form !== this.form) continue;- _radioStates.push([r, !!r.checked]);- if (r !== this) r.checked = false;+ _radioStates.push([r, _inputChecked(r)]);+ if (r !== this) _setInputChecked(r, false);}}- this.checked = true;+ _setInputChecked(this, true);} else {// Legacy-pre-activation behaviour (HTML spec): a checkbox toggles its// checkedness *and* drops indeterminateness. Clearing it here, not on// `change`, is what lets the cancelled-activation path put the old// flag back instead of leaving it stuck off.- this.checked = !_oldChecked;- this.indeterminate = false;+ _setInputChecked(this, !_oldChecked);+ _setInputIndeterminate(this, false);}}const _clickEvent = new MouseEvent("click", {bubbles: true, cancelable: true});if (_trusted) globalThis.__obscura_markTrusted(_clickEvent);const cancelled = !this.dispatchEvent(_clickEvent);if (cancelled) {- if (_radioStates) { for (let i = 0; i < _radioStates.length; i++) _radioStates[i][0].checked = _radioStates[i][1]; }- else if (_checkable) { this.checked = _oldChecked; this.indeterminate = _oldIndeterminate; }+ if (_radioStates) { for (let i = 0; i < _radioStates.length; i++) _setInputChecked(_radioStates[i][0], _radioStates[i][1]); }+ else if (_checkable) { _setInputChecked(this, _oldChecked); _setInputIndeterminate(this, _oldIndeterminate); }return;}- if (_checkable && this.checked !== _oldChecked) {+ if (_checkable && _inputChecked(this) !== _oldChecked) {for (const _type of ['input', 'change']) {const _e = new Event(_type, {bubbles: true});if (_trusted) globalThis.__obscura_markTrusted(_e);@@ -4304,27 +4332,20 @@ class Element extends Node {this.value = _inputFormatNumber(t, value);}get checked() {- if (_formChecked[this._nid] === undefined) _loadFormState(this._nid);- if (_formChecked[this._nid] !== undefined) return _formChecked[this._nid];- return this.hasAttribute("checked");+ return _inputChecked(this);}set checked(v) {- const checked = !!v;- _formChecked[this._nid] = checked;- _dom("set_form_checked", this._nid, String(checked));+ _setInputChecked(this, v);}// `indeterminate` is IDL-only: it has no content attribute to reflect, so// the property itself must exist on the prototype for `'indeterminate' in// el` to be true on a freshly created element. Native node-keyed state// keeps IDL access and rendering consistent without changing attributes.get indeterminate() {- if (_formIndeterminate[this._nid] === undefined) _loadFormState(this._nid);- return _formIndeterminate[this._nid] === true;+ return _inputIndeterminate(this);}set indeterminate(v) {- const indeterminate = !!v;- _formIndeterminate[this._nid] = indeterminate;- _dom("set_form_indeterminate", this._nid, String(indeterminate));+ _setInputIndeterminate(this, v);}get selected() {if (this._selected !== undefined) return this._selected;