From bd92a1c093dfe90e5fef5138a5e631095f3c6340 Mon Sep 17 00:00:00 2001 From: ldm0 Date: Sun, 8 Nov 2026 11:29:37 +0800 Subject: [PATCH] fix(focus): check the native document ancestor chain MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Compute Document.hasFocus from the branded receiver, current document owners, page activity, and every ancestor’s focused area. Retained child focus must not report true when an outer ancestor selected another target. Avoid observable property reads from defaultView, frameElement, and activeElement while computing native focus. Cover nested focus, document retirement, page deactivation, receiver branding, and author property overrides. --- .../src/context_bootstrap/event_document.rs | 43 ++++++--------- .../src/native_bridge/context_host/focus.rs | 25 +++++++++ .../tests/browser_api/window_focus.rs | 54 +++++++++++++++++++ 3 files changed, 95 insertions(+), 27 deletions(-) diff --git a/moli-renderer-v8/src/context_bootstrap/event_document.rs b/moli-renderer-v8/src/context_bootstrap/event_document.rs index b3bc18e5aad..2c248f95d66 100644 --- a/moli-renderer-v8/src/context_bootstrap/event_document.rs +++ b/moli-renderer-v8/src/context_bootstrap/event_document.rs @@ -127,33 +127,22 @@ pub(super) fn document_has_focus_callback( args: v8::FunctionCallbackArguments<'_>, mut rv: v8::ReturnValue<'_, v8::Value>, ) { - let document = args.this(); - let focused = document - .get(scope, v8str(scope, "defaultView").into()) - .and_then(|value| v8::Local::::try_from(value).ok()) - .map(|default_view| { - default_view - .get(scope, v8str(scope, "frameElement").into()) - .filter(|value| !value.is_null_or_undefined()) - .and_then(|value| v8::Local::::try_from(value).ok()) - .map(|frame_element| { - frame_element - .get(scope, v8str(scope, "ownerDocument").into()) - .and_then(|value| v8::Local::::try_from(value).ok()) - .and_then(|owner_document| { - owner_document.get(scope, v8str(scope, "activeElement").into()) - }) - .is_some_and(|active_element| { - active_element.strict_equals(frame_element.into()) - }) - }) - .unwrap_or(true) - }) - .unwrap_or(false); - let focused = focused - && context_host_ptr_from_global_bridge(scope) - .is_some_and(|host_ptr| unsafe { &*host_ptr }.document_activity().focused); - rv.set_bool(focused); + let Ok((host_ptr, document)) = + crate::native_bridge::node_runtime_and_handle_from_object_or_detached(scope, args.this()) + else { + webidl::throw_type_error(scope, "Document.hasFocus called on incompatible receiver."); + return; + }; + let host = unsafe { &*host_ptr }; + if !host + .dom_host() + .node(document) + .is_some_and(crate::dom::native::Node::is_document) + { + webidl::throw_type_error(scope, "Document.hasFocus called on incompatible receiver."); + return; + } + rv.set_bool(host.document_has_focus(document)); } #[cfg(test)] diff --git a/moli-renderer-v8/src/native_bridge/context_host/focus.rs b/moli-renderer-v8/src/native_bridge/context_host/focus.rs index 430773b0589..6437bc6c604 100644 --- a/moli-renderer-v8/src/native_bridge/context_host/focus.rs +++ b/moli-renderer-v8/src/native_bridge/context_host/focus.rs @@ -13,6 +13,31 @@ pub(super) struct DocumentFocusChangeState { } impl JsContextHost { + pub(crate) fn document_has_focus(&self, document: DomHandle) -> bool { + if !self.document_activity().focused || !self.document_is_fully_active(document) { + return false; + } + let mut document = document; + loop { + match self.window_endpoint_for_document(document) { + Some(PendingWindowMessageEndpoint::TopWindow) + | Some(PendingWindowMessageEndpoint::LightweightPopup(_)) => return true, + Some(PendingWindowMessageEndpoint::ChildWindow(container)) => { + let Some(parent) = self.dom_host().owner_document_handle(container) else { + return false; + }; + // Inactive Documents retain their local focused area. Every + // ancestor must still select this child's navigable. + if self.document_focused_area(parent) != Some(container) { + return false; + } + document = parent; + } + None => return false, + } + } + } + pub(crate) fn focused_viewport_document(&self) -> Option { self.focused_viewport_document.filter(|document| { self.active_element_handle().is_none() diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/window_focus.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/window_focus.rs index bb4cc14cbef..e45a3b4234d 100644 --- a/moli-renderer-v8/src/script_vm/tests/browser_api/window_focus.rs +++ b/moli-renderer-v8/src/script_vm/tests/browser_api/window_focus.rs @@ -1,5 +1,59 @@ use super::*; +#[test] +fn document_has_focus_checks_every_live_ancestor_in_the_native_focus_chain() { + let mut vm = new_storage_test_vm("https://document-focus-chain.test/"); + let result = vm.eval(r#"(() => { + const root = document.documentElement || document.appendChild(document.createElement('html')); + const body = document.body || root.appendChild(document.createElement('body')); + body.innerHTML = ''; + const outer = document.getElementById('outer'); + const middle = outer.contentDocument; + middle.body.innerHTML = ''; + const inner = middle.getElementById('inner'); + const deep = inner.contentDocument; + deep.body.innerHTML = ''; + const state = () => [document.hasFocus(), middle.hasFocus(), deep.hasFocus()].join(','); + const states = [state()]; + deep.getElementById('deep').focus(); + states.push(state()); + document.getElementById('top').focus(); + states.push(state()); + if (middle.activeElement !== inner) throw Error('inactive child lost its local focused area'); + middle.getElementById('middle').focus(); + states.push(state()); + deep.getElementById('deep').focus(); + states.push(state()); + outer.remove(); + states.push(state()); + if (document.implementation.createHTMLDocument('').hasFocus()) throw Error('detached Document focused'); + window.checkFocusState = state; + return states.join('|'); + })()"#).unwrap(); + assert_eq!( + result, + "true,false,false|true,true,true|true,false,false|true,true,false|true,true,true|true,false,false" + ); + vm.set_document_activity(moli_page_types::DocumentActivity::new(false, true)) + .unwrap(); + assert_eq!(vm.eval("checkFocusState()").unwrap(), "false,false,false"); +} + +#[test] +fn document_has_focus_uses_the_branded_receiver_without_reading_author_properties() { + let mut vm = new_storage_test_vm("https://document-focus-receiver.test/"); + assert_eq!(vm.eval(r#"(() => { + const hasFocus = Document.prototype.hasFocus; + for (const receiver of [{defaultView: window}, Object.create(document), new Proxy(document, {}), document.createElement('div')]) { + let error; + try { hasFocus.call(receiver); } catch (caught) { error = caught; } + if (!(error instanceof TypeError)) throw Error('invalid Document receiver accepted'); + } + Object.defineProperty(document, 'defaultView', {get() { throw Error('author defaultView getter invoked'); }}); + return hasFocus.call(document); + })()"#).unwrap(), "true"); +} + #[test] fn window_focus_and_blur_validate_the_receiver_in_the_callee_realm() { let mut vm = new_storage_test_vm("https://window-focus-native.test/");