The headless browser for AI agents and web scraping
fix(cdp): embed inserted text as a JSON literal so newlines survive
aleekaz524f2a9dd4e6
diff --git a/crates/obscura-cdp/src/domains/input.rs b/crates/obscura-cdp/src/domains/input.rsindex 857aa130..ca8e2f38 100644--- a/crates/obscura-cdp/src/domains/input.rs+++ b/crates/obscura-cdp/src/domains/input.rs@@ -2,30 +2,39 @@ use serde_json::{json, Value};use crate::dispatch::CdpContext;-// Insert `escaped_text` at the caret, replacing any non-collapsed selection-// the way a real browser does when you type over selected text (for example-// after a triple-click select-all). selectionStart is null during ordinary-// typing, so the legacy append path is kept when no selection is tracked.-fn insert_text_js(escaped_text: &str) -> String {+// Insert `text` at the caret, replacing any non-collapsed selection the way a+// real browser does when you type over selected text (for example after a+// triple-click select-all). selectionStart is null during ordinary typing, so+// the legacy append path is kept when no selection is tracked.+//+// The text is embedded as a JSON string literal rather than escaped by hand+// into single quotes. JSON string syntax is a subset of JavaScript's, so this+// covers the quote and the backslash of issue #433 and the control characters+// they left out: a newline inside a single-quoted literal is a syntax error,+// so the whole snippet was dropped and nothing was inserted. obscura-mcp+// already builds its typing snippet this way.+fn insert_text_js(text: &str) -> String {+ let literal = serde_json::to_string(text).unwrap_or_else(|_| "\"\"".to_string());format!("(function() {{\var t = document.activeElement;\if (!t || (t.localName !== 'input' && t.localName !== 'textarea')) return;\+ var ins = {text};\var v = t.value || '';\var s = t.selectionStart, e = t.selectionEnd;\if (s == null) {{\- globalThis.__obscura_setFieldValue(t, 'value', v + '{text}');\+ globalThis.__obscura_setFieldValue(t, 'value', v + ins);\}} else {{\s = Math.max(0, Math.min(s, v.length));\e = (e == null) ? s : Math.max(0, Math.min(e, v.length));\var lo = Math.min(s, e), hi = Math.max(s, e);\- globalThis.__obscura_setFieldValue(t, 'value', v.slice(0, lo) + '{text}' + v.slice(hi));\- var caret = lo + ('{text}').length;\+ globalThis.__obscura_setFieldValue(t, 'value', v.slice(0, lo) + ins + v.slice(hi));\+ var caret = lo + ins.length;\t.setSelectionRange(caret, caret);\}}\t.dispatchEvent(globalThis.__obscura_markTrusted(new Event('input', {{bubbles:true}})));\}})()",- text = escaped_text,+ text = literal,)}@@ -312,10 +321,7 @@ pub async fn handle(page.evaluate(&js);if !text.is_empty() && text != "\r" && text != "\n" {- // Need to escape backslash BEFORE single-quote so the new- // backslashes from quote escaping don't get double-escaped.- let escaped_text = text.replace('\\', "\\\\").replace('\'', "\\'");- page.evaluate(&insert_text_js(&escaped_text));+ page.evaluate(&insert_text_js(text));}if key == "Enter" {@@ -356,8 +362,7 @@ pub async fn handle(}"char" => {if !text.is_empty() {- let escaped_text = text.replace('\\', "\\\\").replace('\'', "\\'");- page.evaluate(&insert_text_js(&escaped_text));+ page.evaluate(&insert_text_js(text));// Pump event loop so Angular change detection picks up the inputpage.settle(50).await;}diff --git a/crates/obscura-cdp/tests/input_key_event_escaping.rs b/crates/obscura-cdp/tests/input_key_event_escaping.rsindex ba0cfebb..b95649fc 100644--- a/crates/obscura-cdp/tests/input_key_event_escaping.rs+++ b/crates/obscura-cdp/tests/input_key_event_escaping.rs@@ -23,6 +23,7 @@ async fn serve_page() -> String {let _ = socket.read(&mut buf).await.unwrap();let body = r#"<html><body><input id="i">+<textarea id="a"></textarea><script>window.__keys = [];document.body.addEventListener('keydown', function (e) { window.__keys.push(e.key + '|' + e.code); });@@ -102,3 +103,64 @@ async fn dispatch_key_event_escapes_backslash_in_key_and_code() {"the backslash key must be dispatched, not dropped by a malformed snippet");}++// The same hazard one layer over: on the inserted *text* rather than on the key+// name. `insert_text_js` interpolates the text into the same kind of+// single-quoted literal. #433 escaped the backslash and the quote and stopped+// there, but a raw newline ends a JS string literal just as a stray quote does,+// so the snippet is a syntax error and the character is silently dropped.+//+// The `char` type is the path that reaches it with a newline: the `keyDown`+// branch skips insertion for "\r" and "\n" because `key == "Enter"` handles+// those, and `char` has no such guard, so a client entering a line break in a+// textarea this way loses it with no error reported anywhere.+#[tokio::test(flavor = "current_thread")]+async fn dispatch_key_event_char_carries_a_newline_into_a_textarea() {+ std::env::set_var("OBSCURA_ALLOW_PRIVATE_NETWORK", "1");+ let url = serve_page().await;+ let mut ctx = CdpContext::new();+ let page_id = ctx.create_page();+ let session_id = "session-1";+ ctx.sessions.insert(session_id.to_string(), page_id.clone());++ cdp(&mut ctx, 1, "Page.navigate", json!({"url": url, "waitUntil": "load"}), session_id).await;+ cdp(+ &mut ctx,+ 2,+ "Runtime.evaluate",+ json!({+ "expression": "(function () { document.getElementById('a').focus(); return 'ok'; })()",+ "returnByValue": true,+ }),+ session_id,+ )+ .await;++ for (id, ch) in [(3u64, "a"), (4, "\n"), (5, "b")] {+ cdp(+ &mut ctx,+ id,+ "Input.dispatchKeyEvent",+ json!({"type": "char", "text": ch}),+ session_id,+ )+ .await;+ }++ let v = cdp(+ &mut ctx,+ 6,+ "Runtime.evaluate",+ json!({+ "expression": "JSON.stringify(document.getElementById('a').value)",+ "returnByValue": true,+ }),+ session_id,+ )+ .await;+ assert_eq!(+ v["result"]["value"].as_str().unwrap_or_default(),+ r#""a\nb""#,+ "a newline sent as a char must reach the field, not be dropped by a malformed snippet"+ );+}