Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
fix(events): validate and normalize InputEvent live ranges
ldm0ac1d63b5f331
diff --git a/moli-renderer-v8/src/context_bootstrap/range/object.rs b/moli-renderer-v8/src/context_bootstrap/range/object.rsindex 7134a6c84..e938fff4b 100644--- a/moli-renderer-v8/src/context_bootstrap/range/object.rs+++ b/moli-renderer-v8/src/context_bootstrap/range/object.rs@@ -58,8 +58,20 @@ pub(in crate::context_bootstrap) fn live_range_from_static_range<'s>(super::super::exposed_interfaces::build_intrinsic_interface_instance(scope, "Range").ok()?;initialize_range_object(scope, range, document);- set_range_boundary(scope, range, RangeBoundarySide::Start, start, start_offset);- set_range_boundary(scope, range, RangeBoundarySide::End, end, end_offset);+ super::super::range_surface::set_range_boundary_checked(+ scope,+ range,+ RangeBoundarySide::Start,+ start,+ start_offset,+ )?;+ super::super::range_surface::set_range_boundary_checked(+ scope,+ range,+ RangeBoundarySide::End,+ end,+ end_offset,+ )?;crate::web_api_interfaces::initialize(scope, range, "Range").ok()?;Some(range)}diff --git a/moli-renderer-v8/src/context_bootstrap/range_surface.rs b/moli-renderer-v8/src/context_bootstrap/range_surface.rsindex bb5362b80..25956b408 100644--- a/moli-renderer-v8/src/context_bootstrap/range_surface.rs+++ b/moli-renderer-v8/src/context_bootstrap/range_surface.rs@@ -2,8 +2,8 @@ use super::range::{RANGE_WRAPPER_INTERNAL_FIELD_COUNT, RangeBoundarySide, StaticRangeInitMembers, child_index,current_document_object, initialize_range_object, initialize_static_range_object,new_range_for_document, range_boundary_container_object, range_boundary_offset,- range_is_collapsed, range_node_length, range_validate_boundary_point, set_range_boundary,- throw_named_dom_exception, webidl_node_arg,+ range_is_collapsed, range_node_length, set_range_boundary, throw_named_dom_exception,+ webidl_node_arg,};use super::range_algorithms::{create_contextual_fragment_internal, native_boundary_point_from_node,@@ -25,6 +25,7 @@ mod geometry;mod install;mod template;+pub(super) use boundaries::set_range_boundary_checked;pub(super) use install::install_range_template_bindings;pub(super) use template::{build_abstract_range_template, build_range_constructor_template,diff --git a/moli-renderer-v8/src/context_bootstrap/range_surface/boundaries.rs b/moli-renderer-v8/src/context_bootstrap/range_surface/boundaries.rsindex 319296b8b..bd6031989 100644--- a/moli-renderer-v8/src/context_bootstrap/range_surface/boundaries.rs+++ b/moli-renderer-v8/src/context_bootstrap/range_surface/boundaries.rs@@ -8,7 +8,7 @@ use crate::webidl;#[derive(webidl::WebIdlArgs)]#[webidl(prefix = "Range.setStart")]struct RangeSetStartArgs<'s> {- #[webidl(with = range_set_start_node_arg)]+ #[webidl(required, interface = crate::web_api_interfaces::Node)]container: v8::Local<'s, v8::Object>,#[webidl(required)]offset: u32,@@ -17,7 +17,7 @@ struct RangeSetStartArgs<'s> {#[derive(webidl::WebIdlArgs)]#[webidl(prefix = "Range.setEnd")]struct RangeSetEndArgs<'s> {- #[webidl(with = range_set_end_node_arg)]+ #[webidl(required, interface = crate::web_api_interfaces::Node)]container: v8::Local<'s, v8::Object>,#[webidl(required)]offset: u32,@@ -44,22 +44,6 @@ struct RangeCollapseArgs {to_start: bool,}-fn range_set_start_node_arg<'s>(- scope: &mut v8::PinScope<'s, '_>,- args: &v8::FunctionCallbackArguments<'s>,- index: i32,-) -> Result<v8::Local<'s, v8::Object>, webidl::WebIdlError> {- webidl_node_arg(scope, args, index, "Range.setStart requires a Node")-}--fn range_set_end_node_arg<'s>(- scope: &mut v8::PinScope<'s, '_>,- args: &v8::FunctionCallbackArguments<'s>,- index: i32,-) -> Result<v8::Local<'s, v8::Object>, webidl::WebIdlError> {- webidl_node_arg(scope, args, index, "Range.setEnd requires a Node")-}-fn range_select_node_contents_node_arg<'s>(scope: &mut v8::PinScope<'s, '_>,args: &v8::FunctionCallbackArguments<'s>,@@ -89,34 +73,17 @@ pub(super) fn range_set_start_callback<'s>(let Some(parsed) = webidl::parse_args::<RangeSetStartArgs<'s>>(scope, &args) else {return;};- let container = parsed.container;- let offset = parsed.offset;- // Spec Range.setStart(node, offset):- // 1. If node is a doctype, throw InvalidNodeTypeError.- // 2. If offset > node.length, throw IndexSizeError.- if node_is_doctype(scope, container) {- throw_named_dom_exception(- scope,- "InvalidNodeTypeError",- "Range.setStart cannot target a DocumentType.",- );- return;- }- if !range_validate_boundary_point(scope, container, offset) {- throw_named_dom_exception(- scope,- "IndexSizeError",- "Index or size is negative or greater than the allowed amount.",- );- return;- }- range_set_boundary_and_sync_selection(+ if set_range_boundary_checked(scope,args.this(),RangeBoundarySide::Start,- container,- offset,- );+ parsed.container,+ parsed.offset,+ )+ .is_none()+ {+ return;+ }rv.set_undefined();}@@ -128,32 +95,51 @@ pub(super) fn range_set_end_callback<'s>(let Some(parsed) = webidl::parse_args::<RangeSetEndArgs<'s>>(scope, &args) else {return;};- let container = parsed.container;- let offset = parsed.offset;- if node_is_doctype(scope, container) {+ if set_range_boundary_checked(+ scope,+ args.this(),+ RangeBoundarySide::End,+ parsed.container,+ parsed.offset,+ )+ .is_none()+ {+ return;+ }+ rv.set_undefined();+}++// Shared by public setters and native StaticRange-to-Range conversion. Inspect+// native nodes, not author-overridable nodeType/length/parentNode properties.+pub(in crate::context_bootstrap) fn set_range_boundary_checked<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ range: v8::Local<'s, v8::Object>,+ side: RangeBoundarySide,+ container: v8::Local<'s, v8::Object>,+ offset: u32,+) -> Option<()> {+ let point = native_boundary_point_from_node(scope, container, offset);+ if point.is_some_and(|point| native_boundary_point_is_doctype(scope, point)) {throw_named_dom_exception(scope,"InvalidNodeTypeError",- "Range.setEnd cannot target a DocumentType.",+ match side {+ RangeBoundarySide::Start => "Range.setStart cannot target a DocumentType.",+ RangeBoundarySide::End => "Range.setEnd cannot target a DocumentType.",+ },);- return;+ return None;}- if !range_validate_boundary_point(scope, container, offset) {+ if !point.is_some_and(|point| native_boundary_point_is_valid(scope, point)) {throw_named_dom_exception(scope,"IndexSizeError","Index or size is negative or greater than the allowed amount.",);- return;+ return None;}- range_set_boundary_and_sync_selection(- scope,- args.this(),- RangeBoundarySide::End,- container,- offset,- );- rv.set_undefined();+ range_set_boundary_and_sync_selection(scope, range, side, container, offset);+ Some(())}pub(super) fn range_select_node_contents_callback<'s>(@@ -387,18 +373,14 @@ fn range_set_boundary_and_sync_selection<'s>(RangeBoundarySide::Start => RangeBoundarySide::End,RangeBoundarySide::End => RangeBoundarySide::Start,};- let Some(other_container) = range_boundary_container_object(scope, range, other_side) else {- return;- };- let other_offset = range_boundary_offset(scope, range, other_side) as u32;- let order = match side {- RangeBoundarySide::Start => {- point_order(scope, container, offset, other_container, other_offset)- }- RangeBoundarySide::End => {- point_order(scope, other_container, other_offset, container, offset)- }- };+ let order = native_boundary_point_from_node(scope, container, offset)+ .zip(native_boundary_point_from_range_boundary(+ scope, range, other_side,+ ))+ .and_then(|(point, other)| match side {+ RangeBoundarySide::Start => native_boundary_point_order(scope, point, other),+ RangeBoundarySide::End => native_boundary_point_order(scope, other, point),+ });if order.is_none_or(|order| order == std::cmp::Ordering::Greater) {set_range_boundary(scope, range, other_side, container, offset);}diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/input_event_init.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/input_event_init.rsindex 411f6f7f8..61e61e696 100644--- a/moli-renderer-v8/src/script_vm/tests/browser_api/input_event_init.rs+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/input_event_init.rs@@ -1,5 +1,17 @@use super::*;+#[test]+fn input_event_live_ranges_validate_and_normalize_native_boundaries() {+ let mut vm = new_storage_html_test_vm("https://input-range-boundaries.test/");+ assert_eq!(+ vm.eval(include_str!(+ "../../../../tests/fixtures/input-range-boundaries.js"+ ))+ .unwrap(),+ "true"+ );+}+#[test]fn input_and_touch_dictionaries_convert_before_native_sequences_and_range_state() {let mut vm = new_storage_html_test_vm("https://input-touch-dictionary.test/");diff --git a/moli-renderer-v8/tests/fixtures/input-range-boundaries.js b/moli-renderer-v8/tests/fixtures/input-range-boundaries.jsnew file mode 100644index 000000000..b3a561b05--- /dev/null+++ b/moli-renderer-v8/tests/fixtures/input-range-boundaries.js@@ -0,0 +1,68 @@+(() => {+ const assert = (value, label) => { if (!value) throw Error(label); };+ const failure = (operation, name, label) => {+ let caught;+ try { operation(); } catch (error) { caught = error; }+ assert(caught?.name === name, label + ': ' + caught);+ };+ const source = (start, first, end, last) => new StaticRange({+ startContainer: start, startOffset: first, endContainer: end, endOffset: last,+ });+ const convert = range => new InputEvent('beforeinput', {targetRanges: [range]}).getTargetRanges()[0];+ const host = document.createElement('div'); document.body.append(host);+ const text = document.createTextNode('abc'), comment = document.createComment('abc');+ host.append(text, comment);+ for (const node of [text, comment, host]) {+ const length = node === host ? 2 : 3;+ for (const offset of [length + 1, 0xffffffff]) {+ failure(() => convert(source(node, offset, node, 0)), 'IndexSizeError', 'invalid start');+ failure(() => convert(source(node, 0, node, offset)), 'IndexSizeError', 'invalid end');+ }+ }+ const staleText = source(text, 2, text, 3);+ text.deleteData(0, 2);+ failure(() => convert(staleText), 'IndexSizeError', 'offset invalidated by character edit');+ const staleChildren = source(host, 0, host, 2);+ comment.remove();+ failure(() => convert(staleChildren), 'IndexSizeError', 'offset invalidated by child removal');+ text.data = 'abc';+ const reversed = convert(source(text, 2, text, 1));+ assert(reversed.startContainer === text && reversed.endContainer === text && reversed.startOffset === 1 && reversed.endOffset === 1, 'reversed offsets collapse at end');+ const first = document.createTextNode('first'), last = document.createTextNode('last'); host.append(first, last);+ const reversedNodes = convert(source(last, 2, first, 1));+ assert(reversedNodes.startContainer === first && reversedNodes.endContainer === first && reversedNodes.startOffset === 1 && reversedNodes.endOffset === 1, 'reversed nodes collapse at end');+ const detached = document.createTextNode('detached');+ const roots = convert(source(text, 1, detached, 2));+ assert(roots.startContainer === detached && roots.endContainer === detached && roots.startOffset === 2 && roots.endOffset === 2, 'different roots collapse at end');+ const live = new Range(); live.setStart(text, 2); live.setEnd(text, 1);+ assert(live.collapsed && live.startOffset === 1 && live.endOffset === 1, 'public setters share collapse algorithm');+ live.setEnd(detached, 2);+ assert(live.collapsed && live.startContainer === detached && live.startOffset === 2, 'public setters share root handling');+ failure(() => live.setStart(text, 99), 'IndexSizeError', 'public setter length validation');+ failure(() => live.setEnd(document.implementation.createDocumentType('html', '', ''), 0), 'InvalidNodeTypeError', 'doctype rejected before offset');+ const invalid = source(text, 99, text, 99);+ failure(() => new InputEvent('beforeinput', {targetRanges: [invalid, {}]}), 'TypeError', 'complete IDL conversion precedes live range algorithm');+ const protectedSource = source(text, 0, text, 2);+ const NativeRange = Range, NativeStaticRange = StaticRange;+ const setStart = Range.prototype.setStart, setEnd = Range.prototype.setEnd;+ const protectedLive = new Range();+ for (const key of ['nodeType', 'length', 'childNodes', 'parentNode', 'previousSibling'])+ Object.defineProperty(text, key, {configurable: true, get() {throw Error('author node property ' + key);}});+ for (const key of ['startContainer', 'startOffset', 'endContainer', 'endOffset'])+ Object.defineProperty(protectedSource, key, {get() {throw Error('author range boundary');}});+ try {+ globalThis.Range = function() {throw Error('author Range');};+ globalThis.StaticRange = function() {throw Error('author StaticRange');};+ NativeRange.prototype.setStart = NativeRange.prototype.setEnd = function() {throw Error('author setter');};+ const snapshot = convert(protectedSource);+ assert(snapshot.startContainer === text && snapshot.startOffset === 0 && snapshot.endOffset === 2, 'intrinsic native conversion');+ setStart.call(protectedLive, text, 2); setEnd.call(protectedLive, text, 1);+ assert(protectedLive.collapsed && protectedLive.startOffset === 1, 'public algorithm ignores author node properties');+ } finally {+ globalThis.Range = NativeRange; globalThis.StaticRange = NativeStaticRange;+ NativeRange.prototype.setStart = setStart; NativeRange.prototype.setEnd = setEnd;+ for (const key of ['nodeType', 'length', 'childNodes', 'parentNode', 'previousSibling']) delete text[key];+ host.remove();+ }+ return true;+})()