diff --git a/moli-renderer-v8/src/document_runtime/query_facade.rs b/moli-renderer-v8/src/document_runtime/query_facade.rs index 74c2b52837d..61a6b60ac5e 100644 --- a/moli-renderer-v8/src/document_runtime/query_facade.rs +++ b/moli-renderer-v8/src/document_runtime/query_facade.rs @@ -33,7 +33,7 @@ impl DocumentRuntime { self.query_selector_with_optional_validity_states(root, selector, Some(validity_states)) } - fn query_selector_with_optional_validity_states( + pub(crate) fn query_selector_with_optional_validity_states( &self, root: Option, selector: &str, @@ -106,7 +106,7 @@ impl DocumentRuntime { self.query_selector_all_with_optional_validity_states(root, selector, Some(validity_states)) } - fn query_selector_all_with_optional_validity_states( + pub(crate) fn query_selector_all_with_optional_validity_states( &self, root: Option, selector: &str, @@ -153,7 +153,7 @@ impl DocumentRuntime { self.matches_with_optional_validity_states(node, selector, Some(validity_states)) } - fn matches_with_optional_validity_states( + pub(crate) fn matches_with_optional_validity_states( &self, node: DomHandle, selector: &str, diff --git a/moli-renderer-v8/src/native_bridge/document/queries/detached_selectors.rs b/moli-renderer-v8/src/native_bridge/document/queries/detached_selectors.rs index 2b616ea6b92..38af7a53a3f 100644 --- a/moli-renderer-v8/src/native_bridge/document/queries/detached_selectors.rs +++ b/moli-renderer-v8/src/native_bridge/document/queries/detached_selectors.rs @@ -13,6 +13,7 @@ use crate::native_bridge::document::{ detached_native_handle_for_runtime, detached_native_object_for_handle, detached_node_type, detached_owner_document_object, detached_parent_node_object, }; +use crate::native_bridge::element::selector_validity_states; use crate::native_bridge::node::throw_native_selector_error_for_selector; use crate::native_bridge::{ collections, @@ -330,14 +331,7 @@ fn detached_native_query_selector_objects<'s>( find_all: bool, ) -> Option>, crate::selector::SelectorError>> { let runtime_ptr = context_host_ptr_from_global_bridge(scope)?; - let root_handle = detached_native_handle_for_runtime(scope, runtime_ptr, root)?; - let handles = if find_all { - unsafe { &*runtime_ptr }.query_selector_all(Some(root_handle), selector) - } else { - unsafe { &*runtime_ptr } - .query_selector(Some(root_handle), selector) - .map(|handle| handle.into_iter().collect()) - }; + let handles = detached_native_query_selector_handles(scope, root, selector, find_all)?; Some(handles.map(|handles: Vec| { handles .into_iter() @@ -350,10 +344,27 @@ fn detached_native_query_selector_handles<'s>( scope: &mut v8::PinScope<'s, '_>, root: v8::Local<'s, v8::Object>, selector: &str, + find_all: bool, ) -> Option, crate::selector::SelectorError>> { let runtime_ptr = context_host_ptr_from_global_bridge(scope)?; let root_handle = detached_native_handle_for_runtime(scope, runtime_ptr, root)?; - Some(unsafe { &*runtime_ptr }.query_selector_all(Some(root_handle), selector)) + let validity_states = selector_validity_states(scope, runtime_ptr, selector); + let runtime = unsafe { &*runtime_ptr }; + Some(if find_all { + runtime.query_selector_all_with_optional_validity_states( + Some(root_handle), + selector, + validity_states.as_ref(), + ) + } else { + runtime + .query_selector_with_optional_validity_states( + Some(root_handle), + selector, + validity_states.as_ref(), + ) + .map(|handle| handle.into_iter().collect()) + }) } fn detached_native_matches_selector<'s>( @@ -363,7 +374,14 @@ fn detached_native_matches_selector<'s>( ) -> Option> { let runtime_ptr = context_host_ptr_from_global_bridge(scope)?; let handle = detached_native_handle_for_runtime(scope, runtime_ptr, node)?; - Some(unsafe { &*runtime_ptr }.matches(handle, selector)) + let validity_states = selector_validity_states(scope, runtime_ptr, selector); + Some( + unsafe { &*runtime_ptr }.matches_with_optional_validity_states( + handle, + selector, + validity_states.as_ref(), + ), + ) } fn detached_native_element_by_id_object<'s>( @@ -539,7 +557,9 @@ pub(in crate::native_bridge) fn bridge_detached_query_selector_all_callback<'a>( else { return; }; - if let Some(result) = detached_native_query_selector_handles(scope, root, &parsed.selectors) { + if let Some(result) = + detached_native_query_selector_handles(scope, root, &parsed.selectors, true) + { match result { Ok(handles) => { let context = root @@ -606,6 +626,17 @@ pub(in crate::native_bridge) fn bridge_detached_matches_callback<'a>( rv.set(value); return; } + // Native nodes use the same computed state for every selector, including + // combinations of :defined with constraint-validation pseudo-classes. + if let Some(result) = detached_native_matches_selector(scope, node, &parsed.selectors) { + match result { + Ok(is_match) => rv.set_bool(is_match), + Err(error) => { + throw_native_selector_error_for_selector(scope, &parsed.selectors, &error) + } + } + return; + } match detached_stylo_matches_selector_if_uses_defined_pseudo(scope, node, &parsed.selectors) { Ok(Some(is_match)) => { rv.set_bool(is_match); @@ -617,15 +648,6 @@ pub(in crate::native_bridge) fn bridge_detached_matches_callback<'a>( return; } } - if let Some(result) = detached_native_matches_selector(scope, node, &parsed.selectors) { - match result { - Ok(is_match) => rv.set_bool(is_match), - Err(error) => { - throw_native_selector_error_for_selector(scope, &parsed.selectors, &error) - } - } - return; - } match detached_stylo_matches_selector(scope, node, &parsed.selectors) { Ok(is_match) => rv.set_bool(is_match), Err(error) => throw_native_selector_error_for_selector(scope, &parsed.selectors, &error), diff --git a/moli-renderer-v8/src/native_bridge/element.rs b/moli-renderer-v8/src/native_bridge/element.rs index 57c44035f90..de28a373ab7 100644 --- a/moli-renderer-v8/src/native_bridge/element.rs +++ b/moli-renderer-v8/src/native_bridge/element.rs @@ -649,6 +649,7 @@ pub(super) use popover::{ node_hide_popover_callback, node_popover_getter_function, node_popover_setter_function, node_show_popover_callback, node_toggle_popover_callback, }; +pub(in crate::native_bridge) use query::selector_validity_states; pub(super) use query::{ node_closest_callback, node_get_elements_by_class_name_callback, node_get_elements_by_name_callback, node_get_elements_by_tag_name_callback, diff --git a/moli-renderer-v8/src/native_bridge/element/forms/validation.rs b/moli-renderer-v8/src/native_bridge/element/forms/validation.rs index d61c59c87a8..ecbb6de7b78 100644 --- a/moli-renderer-v8/src/native_bridge/element/forms/validation.rs +++ b/moli-renderer-v8/src/native_bridge/element/forms/validation.rs @@ -11,6 +11,7 @@ use moli_dom::forms::{ text_control_suffers_too_long as form_text_control_suffers_too_long, text_control_suffers_too_short as form_text_control_suffers_too_short, }; +use moli_v8_util::NativeRegExp; use moli_webapi::validity_state::ValidityStateDeclaration; use super::super::{ @@ -362,7 +363,7 @@ fn control_validity( ControlValidity { value_missing: control_suffers_required_value_missing(runtime, handle, element), type_mismatch: control_suffers_type_mismatch(runtime, handle, element), - pattern_mismatch: control_suffers_pattern_mismatch(scope, runtime, handle, element), + pattern_mismatch: control_suffers_pattern_mismatch(scope, element), too_long: control_suffers_too_long(runtime, handle, element), too_short: control_suffers_too_short(runtime, handle, element), range_underflow: control_suffers_range_underflow(runtime, handle, element), @@ -539,12 +540,7 @@ fn control_suffers_type_mismatch( ) } -fn control_suffers_pattern_mismatch( - scope: &mut v8::PinScope<'_, '_>, - _runtime: &PageScriptHost, - _handle: DomHandle, - element: &Element, -) -> bool { +fn control_suffers_pattern_mismatch(scope: &mut v8::PinScope<'_, '_>, element: &Element) -> bool { if !element.is_html_input() || !element_type_supports_intrinsic_validation(element) || !element.input_type().supports_pattern() @@ -558,58 +554,43 @@ fn control_suffers_pattern_mismatch( if value.is_empty() { return false; } + let Some(pattern) = compile_html_pattern(scope, pattern) else { + return false; + }; if element.input_type() == InputType::Email && element.has_attribute("multiple") { - return v8_pattern_is_usable(scope, pattern).is_some_and(|()| { - value - .split(',') - .map(str::trim) - .any(|part| !v8_pattern_matches_entire_value(scope, pattern, part).unwrap_or(true)) - }); + return value + .split(',') + .map(str::trim) + .any(|part| pattern_mismatches_value(scope, &pattern, part)); } - v8_pattern_is_usable(scope, pattern).is_some_and(|()| { - v8_pattern_matches_entire_value(scope, pattern, &value).is_some_and(|matched| !matched) - }) + pattern_mismatches_value(scope, &pattern, &value) } pub(crate) fn v8_pattern_is_usable(scope: &mut v8::PinScope<'_, '_>, pattern: &str) -> Option<()> { - let try_catch = std::pin::pin!(v8::TryCatch::new(scope)); - let mut scope = try_catch.init(); - let pattern = v8_string(&scope, pattern)?; - if v8::RegExp::new(&scope, pattern, RegExpCreationFlags::UNICODE_SETS).is_none() { - scope.reset(); - return None; - } - Some(()) + let pattern = v8_string(scope, pattern)?; + NativeRegExp::new(scope, pattern, RegExpCreationFlags::UNICODE_SETS).map(|_| ()) } -fn v8_pattern_matches_entire_value( - scope: &mut v8::PinScope<'_, '_>, +fn compile_html_pattern<'s>( + scope: &mut v8::PinScope<'s, '_>, pattern: &str, - value: &str, -) -> Option { - let try_catch = std::pin::pin!(v8::TryCatch::new(scope)); - let mut scope = try_catch.init(); - - // HTML pattern validation is implicitly anchored; run it through V8 so - // backreferences, lookaheads, and other ECMAScript regexp syntax match the - // JavaScript engine instead of a Rust-side approximation. +) -> Option> { + // HTML validates the standalone source before anchoring it; invalid source + // must not become usable merely because the wrapper balances its groups. + v8_pattern_is_usable(scope, pattern)?; let anchored_pattern = format!("^(?:{pattern})$"); - let pattern = v8_string(&scope, &anchored_pattern)?; - let subject = v8_string(&scope, value)?; - let Some(regex) = v8::RegExp::new(&scope, pattern, RegExpCreationFlags::UNICODE_SETS) else { - // Invalid HTML pattern values are ignored by constraint validation, so - // swallow V8's SyntaxError instead of leaking it through input.validity. - scope.reset(); - return None; - }; + let pattern = v8_string(scope, &anchored_pattern)?; + NativeRegExp::new(scope, pattern, RegExpCreationFlags::UNICODE_SETS) +} - let Some(result) = regex.exec(&scope, subject) else { - // Exec should only be empty for exceptional cases; constraint - // validation treats those like an unusable pattern and continues. - scope.reset(); - return None; - }; - Some(!result.is_null()) +fn pattern_mismatches_value( + scope: &mut v8::PinScope<'_, '_>, + pattern: &NativeRegExp<'_>, + value: &str, +) -> bool { + v8_string(scope, value) + .and_then(|subject| pattern.is_match(scope, subject)) + .is_some_and(|matched| !matched) } fn control_suffers_too_long( diff --git a/moli-renderer-v8/src/native_bridge/element/query.rs b/moli-renderer-v8/src/native_bridge/element/query.rs index 2ebfd71afb1..fcc562c87a0 100644 --- a/moli-renderer-v8/src/native_bridge/element/query.rs +++ b/moli-renderer-v8/src/native_bridge/element/query.rs @@ -376,7 +376,7 @@ pub(in crate::native_bridge) fn node_closest_callback<'s>( } } -fn selector_validity_states( +pub(in crate::native_bridge) fn selector_validity_states( scope: &mut v8::PinScope<'_, '_>, runtime_ptr: *mut PageScriptHost, selector: &str, diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/input_patterns.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/input_patterns.rs new file mode 100644 index 00000000000..3b09ee5e6e3 --- /dev/null +++ b/moli-renderer-v8/src/script_vm/tests/browser_api/input_patterns.rs @@ -0,0 +1,22 @@ +use super::*; + +#[test] +fn input_patterns_use_bounded_native_regexps_without_changing_author_state() { + let mut vm = new_parsed_test_vm( + "https://input-pattern-matching.test/", + "", + ); + let result = vm + .eval(include_str!( + "../../../../tests/fixtures/input-pattern-matching.js" + )) + .expect("input pattern matrix should complete"); + assert_eq!(vm.eval("__uiEventResults.total").unwrap(), "3824"); + assert_eq!( + result, + "true", + "{}", + vm.eval("JSON.stringify(__uiEventResults.rows.filter(row => !row.passed))") + .unwrap(), + ); +} diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/mod.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/mod.rs index 9adeaa302ca..027ce995fa3 100644 --- a/moli-renderer-v8/src/script_vm/tests/browser_api/mod.rs +++ b/moli-renderer-v8/src/script_vm/tests/browser_api/mod.rs @@ -80,6 +80,7 @@ mod idle_detection; mod images; mod input_event_init; mod joint_history_child_pushes; +mod input_patterns; mod interaction_event_init; mod keyboard_event_init; mod legacy_event_init; diff --git a/moli-renderer-v8/tests/fixtures/input-pattern-matching.js b/moli-renderer-v8/tests/fixtures/input-pattern-matching.js new file mode 100644 index 00000000000..28afa91265b --- /dev/null +++ b/moli-renderer-v8/tests/fixtures/input-pattern-matching.js @@ -0,0 +1,143 @@ +(() => { + const rows = [], H = 'http://www.w3.org/1999/xhtml'; + const realms = [['main', globalThis], ['child', document.querySelector('#child').contentWindow]]; + const originals = realms.map(([name, win]) => ({name, ctor: win.RegExp, exec: win.RegExp.prototype.exec})); + const statics = ['input', 'lastMatch', 'lastParen', 'leftContext', 'rightContext', '$1', '$2', '$3', '$4', '$5', '$6', '$7', '$8', '$9']; + const seed = () => { + for (const {name, ctor, exec} of originals) exec.call(new ctor('(sentinel)-('+name+')'), 'before-sentinel-'+name+'-after'); + return originals.map(({ctor}) => statics.map(key => ctor[key])); + }; + const unchanged = before => originals.every(({ctor}, index) => statics.every((key, field) => ctor[key] === before[index][field])); + const same = (a, b) => a.length === b.length && a.every((value, index) => value === b[index]); + const check = (name, body) => { + try {rows.push({name, passed: body() === true});} + catch (error) {rows.push({name, passed: false, error: String(error)});} + }; + const cases = [ + ['digits match', '\\d+', '123', false], + ['full value', '\\d+', 'x123', true], + ['nested rejection', '(\\d+)*$', '12345678901234567890123456789123456789z', true], + ['nested match', '(\\d+)*$', '12345678901234567890123456789123456789', false], + ['backreference match', '([a-z])\\1', 'aa', false], + ['backreference rejection', '([a-z])\\1', 'ab', true], + ['lookahead match', '(?=.*[0-9]).+', 'abc1', false], + ['lookahead rejection', '(?=.*[0-9]).+', 'abc', true], + ['unicode intersection', '[\\p{ASCII}&&\\p{Letter}]+', 'abc', false], + ['unicode intersection rejection', '[\\p{ASCII}&&\\p{Letter}]+', '\u00e9', true], + ['unicode string set', '[\\q{ab|cd}]', 'ab', false], + ['unicode string set rejection', '[\\q{ab|cd}]', 'a', true], + ['invalid class', '[', 'x', false], + ['invalid standalone source balanced by wrapper', ')abc(', 'x', false], + ['empty pattern', '', 'x', true], + ['empty value', '\\d+', '', false], + ['supplementary character', '\\p{Emoji}', '\ud83d\ude00', false], + ['escaped punctuation', 'a\\.b', 'a.b', false], + ['invalid unicode-set punctuation', '[()]', 'x', false], + ['absent pattern', null, 'anything', false], + ]; + const methods = ['validity', 'checkValidity', 'reportValidity', 'validationMessage', 'matches', 'closest', 'elementQuery', 'documentQuery', 'formValidity']; + for (const [ownerName, owner] of realms) for (const flavor of ['live', 'html', 'parsed', 'xml']) { + const doc = flavor === 'live' ? owner.document : flavor === 'html' ? owner.document.implementation.createHTMLDocument('patterns') : + flavor === 'parsed' ? new owner.DOMParser().parseFromString('', 'text/html') : + owner.document.implementation.createDocument(H, 'html'); + const holder = (doc.body || doc.documentElement).appendChild(doc.createElementNS(H, 'div')); + const form = holder.appendChild(doc.createElementNS(H, 'form')); + const input = form.appendChild(doc.createElementNS(H, 'input')); + let invalidEvents = 0; + input.addEventListener('invalid', event => {invalidEvents++;event.preventDefault();}); + try { + for (const [calleeName, callee] of realms) { + for (const [caseName, pattern, value, expected] of cases) { + input.type = 'text';input.multiple = false; + if (pattern === null) input.removeAttribute('pattern'); else input.pattern = pattern; + input.value = value; + for (const method of methods) { + check(`${ownerName}/${flavor}/${calleeName}/${caseName}/${method}`, () => { + invalidEvents = 0; + const before = seed(); + let result; + if (method === 'validity') { + const state = Object.getOwnPropertyDescriptor(callee.HTMLInputElement.prototype, 'validity').get.call(input); + result = state.patternMismatch === expected && state.valid !== expected; + } else if (method === 'checkValidity' || method === 'reportValidity') result = callee.HTMLInputElement.prototype[method].call(input) !== expected; + else if (method === 'validationMessage') result = (Object.getOwnPropertyDescriptor(callee.HTMLInputElement.prototype, 'validationMessage').get.call(input) !== '') === expected; + else if (method === 'matches') result = callee.Element.prototype.matches.call(input, ':invalid') === expected; + else if (method === 'closest') result = callee.Element.prototype.closest.call(input, ':invalid') === (expected ? input : null); + else if (method === 'elementQuery') result = same([...callee.Element.prototype.querySelectorAll.call(holder, 'input:invalid')], expected ? [input] : []); + else if (method === 'documentQuery') result = same([...callee.Document.prototype.querySelectorAll.call(doc, 'input:invalid')], expected ? [input] : []); + else result = callee.HTMLFormElement.prototype.checkValidity.call(form) !== expected; + const fires = expected && ['checkValidity', 'reportValidity', 'formValidity'].includes(method); + return result && invalidEvents === Number(fires) && unchanged(before); + }); + } + } + input.type = 'text';input.multiple = false;input.pattern = '(a)\\1';input.value = 'ab'; + const selectorCases = [ + ['input:defined:invalid', true], + ['input:is(:defined):invalid', true], + ['input:where(:invalid):defined', true], + ['input:not(:valid):defined', true], + ['input:defined:not(:invalid)', false], + ['input:is(:defined,:invalid)', true], + ]; + for (const [selector, expected] of selectorCases) { + for (const method of ['matches', 'closest', 'elementQuery', 'documentQuery', 'elementQueryAll', 'documentQueryAll']) { + check(`${ownerName}/${flavor}/${calleeName}/selectors/${selector}/${method}`, () => { + invalidEvents = 0; + const before = seed(); + let result; + if (method === 'matches') result = callee.Element.prototype.matches.call(input, selector) === expected; + else if (method === 'closest') result = callee.Element.prototype.closest.call(input, selector) === (expected ? input : null); + else if (method === 'elementQuery') result = callee.Element.prototype.querySelector.call(holder, selector) === (expected ? input : null); + else if (method === 'documentQuery') result = callee.Document.prototype.querySelector.call(doc, selector) === (expected ? input : null); + else if (method === 'elementQueryAll') result = same([...callee.Element.prototype.querySelectorAll.call(holder, selector)], expected ? [input] : []); + else result = same([...callee.Document.prototype.querySelectorAll.call(doc, selector)], expected ? [input] : []); + return result && invalidEvents === 0 && unchanged(before); + }); + } + } + const unknown = holder.appendChild(doc.createElementNS(H, 'pattern-unknown')); + for (const selector of ['pattern-unknown:defined', 'pattern-unknown:is(:defined,:invalid)']) { + check(`${ownerName}/${flavor}/${calleeName}/undefined/${selector}`, () => { + const before = seed(); + return callee.Element.prototype.matches.call(unknown, selector) === false && unchanged(before); + }); + } + unknown.remove(); + const typed = [ + ...['text', 'search', 'tel', 'password'].flatMap(type => [[type, '(a)\\1', 'aa', false], [type, '(a)\\1', 'ab', true]]), + ['url', 'https://example\\.test/', 'https://example.test/', false], + ['url', 'https://example\\.test/', 'https://other.test/', true], + ['email', '[a-z]+@example\\.test', 'a@example.test', false], + ['email', '[a-z]+@example\\.test', 'a@other.test', true], + ...[['number', '123'], ['date', '2026-10-22'], ['color', '#ff0000'], ['range', '50'], ['checkbox', 'x'], ['hidden', 'x']].map(([type, value]) => [type, 'never-matches', value, false]), + ]; + for (const [type, pattern, value, expected] of typed) { + input.type = type;input.multiple = false;input.pattern = pattern;input.value = value; + check(`${ownerName}/${flavor}/${calleeName}/type/${type}/${value}`, () => { + const before = seed(); + const state = Object.getOwnPropertyDescriptor(callee.HTMLInputElement.prototype, 'validity').get.call(input); + return state.patternMismatch === expected && state.valid !== expected && + callee.HTMLInputElement.prototype.checkValidity.call(input) !== expected && unchanged(before); + }); + } + input.type = 'email';input.multiple = true;input.pattern = '[a-z]+@example\\.test'; + for (const [value, expected] of [['a@example.test,b@example.test', false], ['a@example.test, b@other.test', true], ['', false]]) { + input.value = value; + check(`${ownerName}/${flavor}/${calleeName}/multiple/${value}`, () => { + const before = seed(); + const state = Object.getOwnPropertyDescriptor(callee.HTMLInputElement.prototype, 'validity').get.call(input); + return state.patternMismatch === expected && state.valid !== expected && + callee.HTMLInputElement.prototype.checkValidity.call(input) !== expected && unchanged(before); + }); + } + } + } finally { + // Orphan nodes can remain in a native arena; leave a cheap pattern for + // later selector scans, instead of carrying an adversarial expression. + input.type = 'text';input.multiple = false;input.pattern = '.*';input.value = 'cleanup';holder.remove(); + } + } + globalThis.__uiEventResults = {complete: true, total: rows.length, passed: rows.filter(row => row.passed).length, rows}; + return rows.every(row => row.passed); +})() diff --git a/moli-v8-util/src/lib.rs b/moli-v8-util/src/lib.rs index b3e05a89db9..aba14c1493d 100644 --- a/moli-v8-util/src/lib.rs +++ b/moli-v8-util/src/lib.rs @@ -9,6 +9,7 @@ mod microtasks; mod object_readers; mod promises; mod properties; +mod regexp; mod strings; mod symbols; @@ -23,6 +24,7 @@ pub use microtasks::*; pub use object_readers::*; pub use promises::*; pub use properties::*; +pub use regexp::*; pub use strings::*; pub use symbols::*; diff --git a/moli-v8-util/src/regexp.rs b/moli-v8-util/src/regexp.rs new file mode 100644 index 00000000000..fad348d842c --- /dev/null +++ b/moli-v8-util/src/regexp.rs @@ -0,0 +1,130 @@ +use v8::{Context, Global, Local, PinScope, RegExp, RegExpCreationFlags}; + +// Blink's ScriptRegexp uses the same budget for user-agent regular expressions. +const NATIVE_REGEXP_BACKTRACK_LIMIT: u32 = 1_000_000; + +struct NativeRegExpContext(Global); + +fn native_regexp_context<'s>(scope: &mut PinScope<'s, '_>) -> Local<'s, Context> { + if let Some(context) = scope.get_slot::() { + return Local::new(scope, &context.0); + } + // This context contains no author objects. Keeping it in an isolate slot + // shares it across host matches without retaining a page's realm graph. + let context = Context::new(scope, Default::default()); + let retained = Global::new(scope, context); + scope.set_slot(NativeRegExpContext(retained)); + context +} + +/// A bounded user-agent regular expression, isolated from author intrinsics +/// and the observable legacy RegExp statics of every author realm. +pub struct NativeRegExp<'s> { + context: Local<'s, Context>, + regexp: Local<'s, RegExp>, +} + +impl<'s> NativeRegExp<'s> { + /// Compile without exposing syntax errors to the surrounding script. + pub fn new( + scope: &mut PinScope<'s, '_>, + pattern: Local, + flags: RegExpCreationFlags, + ) -> Option { + let context = native_regexp_context(scope); + let scope = &mut v8::ContextScope::new(scope, context); + let try_catch = std::pin::pin!(v8::TryCatch::new(scope)); + let mut scope = try_catch.init(); + let regexp = + RegExp::new_with_backtrack_limit(&scope, pattern, flags, NATIVE_REGEXP_BACKTRACK_LIMIT); + if regexp.is_none() { + scope.reset(); + } + regexp.map(|regexp| Self { context, regexp }) + } + + /// `Some(false)` includes exhausted backtracking budgets. `None` indicates + /// an exceptional execution failure, distinct from a failed match. + pub fn is_match( + &self, + scope: &mut PinScope<'_, '_>, + subject: Local, + ) -> Option { + let scope = &mut v8::ContextScope::new(scope, self.context); + let try_catch = std::pin::pin!(v8::TryCatch::new(scope)); + let mut scope = try_catch.init(); + let result = self.regexp.exec(&scope, subject); + if result.is_none() { + scope.reset(); + } + result.map(|value| !value.is_null()) + } +} + +#[cfg(test)] +mod tests { + use std::pin::pin; + + use super::*; + + fn eval<'s>(scope: &mut PinScope<'s, '_>, source: &str) -> Local<'s, v8::Value> { + let source = v8::String::new(scope, source).unwrap(); + v8::Script::compile(scope, source, None) + .unwrap() + .run(scope) + .unwrap() + } + + #[test] + fn native_regexp_bounds_backtracking_and_keeps_invalid_patterns_distinct() { + moli_v8_test_util::ensure_v8(); + let mut isolate = v8::Isolate::new(v8::CreateParams::default()); + let scope = pin!(v8::HandleScope::new(&mut isolate)); + let scope = &mut scope.init(); + let context = Context::new(scope, Default::default()); + let scope = &mut v8::ContextScope::new(scope, context); + let source = v8::String::new(scope, "^(?:(\\d+)*)$").unwrap(); + let regexp = NativeRegExp::new(scope, source, RegExpCreationFlags::UNICODE_SETS).unwrap(); + let matching = v8::String::new(scope, "12345678901234567890123456789123456789").unwrap(); + let rejecting = v8::String::new(scope, "12345678901234567890123456789123456789z").unwrap(); + assert_eq!(regexp.is_match(scope, matching), Some(true)); + assert_eq!(regexp.is_match(scope, rejecting), Some(false)); + let invalid = v8::String::new(scope, "[").unwrap(); + assert!(NativeRegExp::new(scope, invalid, RegExpCreationFlags::UNICODE_SETS).is_none()); + assert!(eval(scope, "true").is_true()); + assert_eq!(scope.get_current_context(), context); + } + + #[test] + fn native_regexp_does_not_read_author_intrinsics_or_change_realm_statics() { + moli_v8_test_util::ensure_v8(); + let mut isolate = v8::Isolate::new(v8::CreateParams::default()); + let scope = pin!(v8::HandleScope::new(&mut isolate)); + let scope = &mut scope.init(); + let contexts = [ + Context::new(scope, Default::default()), + Context::new(scope, Default::default()), + ]; + for context in contexts { + let scope = &mut v8::ContextScope::new(scope, context); + eval( + scope, + r#" + globalThis.originalRegExp = RegExp; + /(sentinel)/.exec('sentinel'); + RegExp.prototype.exec = () => { throw new Error('author exec'); }; + Object.defineProperty(globalThis, 'RegExp', { + get() { throw new Error('author RegExp'); } + }); + "#, + ); + let source = v8::String::new(scope, "(different)").unwrap(); + let subject = v8::String::new(scope, "different").unwrap(); + let regexp = + NativeRegExp::new(scope, source, RegExpCreationFlags::UNICODE_SETS).unwrap(); + assert_eq!(regexp.is_match(scope, subject), Some(true)); + assert_eq!(scope.get_current_context(), context); + assert!(eval(scope, "originalRegExp.$1 === 'sentinel'").is_true()); + } + } +}