Truly independent web browser
LibWeb: Implement Permissions and PermissionStatus in Rust
Shannon Booth49e3bc1d5a9d
diff --git a/Libraries/LibWeb/Bindings/MainThreadVM.cpp b/Libraries/LibWeb/Bindings/MainThreadVM.cppindex 0d98dd248c9..ea21741ce16 100644--- a/Libraries/LibWeb/Bindings/MainThreadVM.cpp+++ b/Libraries/LibWeb/Bindings/MainThreadVM.cpp@@ -75,7 +75,6 @@#include <LibWeb/HighResolutionTime/TimeOrigin.h>#include <LibWeb/Loader/ResourceLoader.h>#include <LibWeb/Page/Page.h>-#include <LibWeb/PermissionsAPI/PermissionStore.h>#include <LibWeb/Platform/EventLoopPlugin.h>#include <LibWeb/Platform/ImageCodecPlugin.h>#include <LibWeb/Platform/ThreadPoolWork.h>@@ -868,7 +867,6 @@ void shut_down_agent()Fetch::Fetching::disarm_all_body_stream_wakes();HTML::clear_message_event_ports_caches();ServiceWorker::clear_service_worker_container_ready_promise_caches();- PermissionsAPI::PermissionStore::forget_statuses_of_this_agent();FileAPI::forget_blob_url_store_of_this_agent();Fetch::Fetching::clear_http_memory_cache();ServiceWorker::forget_job_queues_of_this_agent();diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs b/Libraries/LibWeb/Bindings/Rust/src/html/exports.rsindex 134cb915a57..31e485d936c 100644--- a/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs@@ -469,6 +469,7 @@ pub unsafe extern "C" fn web_rust_shut_down_agent(vm: *mut c_void) {crate::html::broadcast_channel::forget_broadcast_channels_of_agent();crate::web_assembly::Agent::shut_down();crate::indexed_db::internal::storage::shut_down_storage();+ crate::permissions_api::permission_store::forget_statuses_of_this_agent();}/// Steps 6 to 9 of BroadcastChannel's postMessage(), for a message that another process posted, whose channel namediff --git a/Libraries/LibWeb/Bindings/Rust/src/lib.rs b/Libraries/LibWeb/Bindings/Rust/src/lib.rsindex 09b4f78aa74..a26b04aea05 100644--- a/Libraries/LibWeb/Bindings/Rust/src/lib.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/lib.rs@@ -215,6 +215,18 @@ pub(crate) mod paint_timing;)]pub(crate) mod performance_timeline;#[cfg(not(test))]+pub(crate) mod permissions;+#[cfg(not(test))]+#[cfg_attr(+ not(web_idl_bindings),+ allow(dead_code, reason = "only the generated bindings use the interfaces")+)]+#[allow(+ clippy::unnecessary_wraps,+ reason = "the bindings call every attribute and operation as one that can throw"+)]+pub(crate) mod permissions_api;+#[cfg(not(test))]pub(crate) mod platform;#[cfg(not(test))]#[cfg_attr(diff --git a/Libraries/LibWeb/Bindings/Rust/src/permissions/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/permissions/mod.rsnew file mode 100644index 00000000000..438c6578c32--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/permissions/mod.rs@@ -0,0 +1,11 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#[allow(+ clippy::module_inception,+ reason = "the module mirrors LibWebCommon/Permissions/Permissions.h"+)]+pub(crate) mod permissions;diff --git a/Libraries/LibWeb/Bindings/Rust/src/permissions/permissions.rs b/Libraries/LibWeb/Bindings/Rust/src/permissions/permissions.rsnew file mode 100644index 00000000000..23aa3b84358--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/permissions/permissions.rs@@ -0,0 +1,14 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++/// Web::Permissions::PermissionName.+#[derive(Clone, Copy, PartialEq, Eq)]+#[repr(u8)]+pub(crate) enum PermissionName {+ Geolocation = 0,+ Microphone = 1,+ Notifications = 2,+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/permissions_api/exports.rs b/Libraries/LibWeb/Bindings/Rust/src/permissions_api/exports.rsnew file mode 100644index 00000000000..5f3ae2d5b92--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/permissions_api/exports.rs@@ -0,0 +1,40 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The entry points through which LibWeb's C++ code reaches the Permissions API, declared in+//! Libraries/LibWeb/PermissionsAPI/Permissions.cpp and PermissionStore.cpp.++use core::ffi::c_void;++use libjs_rust::api::Vm;++use crate::bindings::interface::{allocate, cell_into_abi};+use crate::permissions_api::permission_store::update_statuses_of_this_agent;+use crate::permissions_api::permissions::Permissions;++/// # Safety+///+/// The VM must be live.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_permissions_api_create_permissions(vm: *const c_void) -> *mut c_void {+ // SAFETY: The caller passes a live VM.+ let vm = unsafe { &*vm.cast::<Vm>() };+ cell_into_abi(allocate(vm, |_| Permissions))+}++/// # Safety+///+/// The VM must be the live VM of the thread.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_permissions_api_update_statuses_of_this_agent(+ vm: *const c_void,+ revision: u64,+ store_changed: bool,+) -> bool {+ // SAFETY: The caller passes the live VM.+ let vm = unsafe { &*vm.cast::<Vm>() };+ update_statuses_of_this_agent(vm, revision, store_changed)+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/permissions_api/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/permissions_api/mod.rsnew file mode 100644index 00000000000..78fc35e1e01--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/permissions_api/mod.rs@@ -0,0 +1,10 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++pub(crate) mod exports;+pub(crate) mod permission_status;+pub(crate) mod permission_store;+pub(crate) mod permissions;diff --git a/Libraries/LibWeb/Bindings/Rust/src/permissions_api/permission_status.rs b/Libraries/LibWeb/Bindings/Rust/src/permissions_api/permission_status.rsnew file mode 100644index 00000000000..a5ac2a161fd--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/permissions_api/permission_status.rs@@ -0,0 +1,162 @@+/*+ * Copyright (c) 2026, Niccolo Antonelli-Dziri <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! PermissionStatus, https://w3c.github.io/permissions/#permissionstatus-interface++use core::cell::Cell;+use core::ffi::c_void;+use core::ptr::NonNull;++use ak::Utf16String;+use libjs_rust::api::{Gc, Realm, Trace, Vm};++use crate::bindings::environment_settings_object::relevant_settings_object;+use crate::bindings::event_target::{CppEvent, CppEventTarget, GetTheParent};+use crate::bindings::global_object::window_from_global_object;+use crate::bindings::interface::{Ref, Wrappable, allocate};+use crate::bindings::promise::{TaskSource, queue_a_global_task};+use crate::bindings::{CallContext, WebIdlResult};+use crate::permissions::permissions::PermissionName;+use crate::permissions_api::permission_store::register_status;+use crate::permissions_api::permissions::{PermissionDescriptor, permission_state};++unsafe extern "C" {+ fn web_html_window_or_worker_global_scope_register_permission_status(+ global_object: *mut c_void,+ status: *mut c_void,+ );+}++// https://w3c.github.io/permissions/#dom-permissionstate+#[derive(Clone, Copy, PartialEq, Eq)]+pub(crate) enum PermissionState {+ Granted,+ Denied,+ Prompt,+}++// https://w3c.github.io/permissions/#permissionstatus-interface+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct PermissionStatus {+ event_target: CppEventTarget,+ realm: Gc<Realm>,++ #[gc(untraced)]+ name: Utf16String,+ #[gc(untraced)]+ permission_name: PermissionName,+ #[gc(untraced)]+ state: Cell<PermissionState>,++ // https://w3c.github.io/permissions/#dfn-query+ #[gc(untraced)]+ query: PermissionDescriptor,+}++impl Wrappable for PermissionStatus {+ fn relevant_realm(&self) -> Option<Gc<Realm>> {+ Some(self.realm)+ }++ fn cpp_parent(&self) -> Option<NonNull<c_void>> {+ self.event_target.as_cpp_parent()+ }+}++impl GetTheParent for PermissionStatus {+ fn get_the_parent(&self) -> Option<CppEventTarget> {+ None+ }+}++impl PermissionStatus {+ // https://w3c.github.io/permissions/#dfn-create-a-permissionstatus+ pub(crate) fn create(vm: &Vm, realm: Gc<Realm>, permission_desc: PermissionDescriptor) -> Ref<Self> {+ // 1. Let name be permissionDesc's name.+ let name = permission_desc.name.clone();++ // 2. Assert: The feature identified by name is supported by the user agent.+ let permission_name = PermissionName::from_name(&name).expect("the name is supported");++ // 3. Let status be a new instance of the permission result type identified by name:+ // FIXME: A permission result type is a PermissionStatus or one of its subtypes.+ // If unspecified, this defaults to PermissionStatus. No subtypes exist yet in Ladybird.+ // 1. Initialize status's [[query]] internal slot to permissionDesc.+ // 2. Initialize status's name to name.+ let status = allocate(vm, |_| Self {+ event_target: CppEventTarget::new(),+ realm,+ name,+ permission_name,+ state: Cell::new(PermissionState::Prompt),+ query: permission_desc,+ });+ status.event_target.set_owner(status);++ // NB: The store tells every status when a permission changes, and the global keeps a status alive while it has a+ // change listener.+ register_status(vm, status);+ // SAFETY: The global object and the EventTarget are live.+ unsafe {+ web_html_window_or_worker_global_scope_register_permission_status(+ realm.global_object().as_ptr().cast(),+ status.event_target.as_ptr(),+ );+ }++ // 4. Return status.+ status+ }++ // https://w3c.github.io/permissions/#dom-permissionstatus-state+ pub(crate) fn state(&self, _: &mut CallContext) -> WebIdlResult<PermissionState> {+ Ok(self.state.get())+ }++ pub(crate) fn set_state(&self, state: PermissionState) {+ self.state.set(state);+ }++ // https://w3c.github.io/permissions/#dom-permissionstatus-name+ pub(crate) fn name(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {+ Ok(self.name.clone())+ }++ pub(crate) fn query(&self) -> &PermissionDescriptor {+ &self.query+ }++ // Reads the state again from the permission store, and fires change at this status if it moved.+ pub(crate) fn update_from_store(this: Ref<Self>, vm: &Vm) {+ let global = this.realm.global_object();++ // A document that isn't fully active sees no change until it is again.+ if let Some(window) = window_from_global_object(global)+ && !window.associated_document().is_fully_active()+ {+ return;+ }++ let state = permission_state(this.permission_name, &relevant_settings_object(global));+ if state == this.state.get() {+ return;+ }++ // NB: The state is read again when the task runs, so a status that heard of several changes ends with the last.+ queue_a_global_task(vm, global, TaskSource::Permissions, this, |_, this| {+ let global = this.realm.global_object();+ let state = permission_state(this.permission_name, &relevant_settings_object(global));+ if state == this.state.get() {+ return;+ }+ this.state.set(state);+ let event = CppEvent::create(this.realm, "change", false, false, false);+ this.event_target.dispatch_event(&event);+ });+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/permissions_api/permission_store.rs b/Libraries/LibWeb/Bindings/Rust/src/permissions_api/permission_store.rsnew file mode 100644index 00000000000..4cef05cda74--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/permissions_api/permission_store.rs@@ -0,0 +1,61 @@+/*+ * Copyright (c) 2026, Niccolo Antonelli-Dziri <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The statuses of the permission store, https://w3c.github.io/permissions/#dfn-permission-store++use core::cell::{Cell, RefCell};++use libjs_rust::api::{EmbedderCell, GcWeak, MarkedVec, Vm};++use crate::bindings::interface::{Ref, Wrapped};+use crate::permissions_api::permission_status::PermissionStatus;++thread_local! {+ static PERMISSION_STATUSES: RefCell<Vec<GcWeak<EmbedderCell<Wrapped<PermissionStatus>>>>> =+ const { RefCell::new(Vec::new()) };++ // The newest snapshot that the statuses of this agent have seen.+ static REVISION: Cell<Option<u64>> = const { Cell::new(None) };+}++pub(crate) fn register_status(vm: &Vm, status: Ref<PermissionStatus>) {+ PERMISSION_STATUSES.with_borrow_mut(|statuses| statuses.push(GcWeak::new(vm.heap(), status)));+}++/// Reads the state of every status of the thread's agent again from the permission store, once the store has applied+/// the snapshot of the revision. Returns whether the statuses heard of a change.+pub(crate) fn update_statuses_of_this_agent(vm: &Vm, revision: u64, store_changed: bool) -> bool {+ // NB: The agent that got here first made the change, and the others still have to hear of it. An agent has heard of a+ // revision only once its statuses have, which is not the case for one that it fetched without telling them.+ let is_unseen = REVISION.get().is_none_or(|seen| revision > seen);+ if is_unseen {+ REVISION.set(Some(revision));+ }+ if !store_changed && !is_unseen {+ return false;+ }++ // NB: Updating a status allocates, and a collection then could clear another status's weak reference, so every+ // live status is rooted first.+ let statuses = MarkedVec::new(vm);+ PERMISSION_STATUSES.with_borrow_mut(|weak_statuses| {+ weak_statuses.retain(|status| status.get().is_some());+ for status in weak_statuses.iter().filter_map(GcWeak::get) {+ statuses.push(status);+ }+ });+ for status in statuses.values().iter() {+ PermissionStatus::update_from_store(*status, vm);+ }+ true+}++/// For an agent that goes away, whose statuses have to go with its heap.+pub(crate) fn forget_statuses_of_this_agent() {+ PERMISSION_STATUSES.with_borrow_mut(Vec::clear);+ REVISION.set(None);+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/permissions_api/permissions.rs b/Libraries/LibWeb/Bindings/Rust/src/permissions_api/permissions.rsnew file mode 100644index 00000000000..79df211af2c--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/permissions_api/permissions.rs@@ -0,0 +1,179 @@+/*+ * Copyright (c) 2026, Niccolo Antonelli-Dziri <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Permissions, https://w3c.github.io/permissions/#permissions-interface++use core::ffi::c_void;++use ak::Utf16String;+use libjs_rust::api::{ErrorKind, ErrorType, Gc, Object, Throw, Trace, Value, Vm};++#[cfg(web_idl_bindings)]+use crate::bindings::conversions::FromJs;+use crate::bindings::environment_settings_object::{CppEnvironmentSettingsObject, relevant_settings_object};+use crate::bindings::global_object::window_from_global_object;+use crate::bindings::interface::{Wrappable, with_temporary_execution_context, wrap};+use crate::bindings::promise::{+ TaskSource, WebIdlPromise, exception_value, queue_a_global_task, reject_promise, resolve_promise,+};+use crate::bindings::{CallContext, Exception, WebIdlResult};+use crate::permissions::permissions::PermissionName;+use crate::permissions_api::permission_status::{PermissionState, PermissionStatus};++unsafe extern "C" {+ fn web_permissions_api_permission_state(settings_object: *mut c_void, name: u8) -> u8;+}++// https://w3c.github.io/permissions/#dom-permissiondescriptor+#[derive(Clone)]+pub(crate) struct PermissionDescriptor {+ pub(crate) name: Utf16String,+}++impl PermissionName {+ pub(crate) fn from_name(name: &Utf16String) -> Option<Self> {+ if *name == "geolocation" {+ return Some(Self::Geolocation);+ }+ if *name == "microphone" {+ return Some(Self::Microphone);+ }+ if *name == "notifications" {+ return Some(Self::Notifications);+ }+ None+ }+}++// https://w3c.github.io/permissions/#dfn-permission-state+pub(crate) fn permission_state(name: PermissionName, settings: &CppEnvironmentSettingsObject) -> PermissionState {+ // SAFETY: The settings object is live.+ match unsafe { web_permissions_api_permission_state(settings.as_ptr(), name as u8) } {+ 0 => PermissionState::Granted,+ 1 => PermissionState::Denied,+ 2 => PermissionState::Prompt,+ _ => unreachable!("LibWeb returns a PermissionState"),+ }+}++// https://w3c.github.io/permissions/#permissions-interface+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct Permissions;++impl Wrappable for Permissions {}++fn convert_to_permission_descriptor(vm: &Vm, value: Value) -> Result<PermissionDescriptor, Throw> {+ #[cfg(web_idl_bindings)]+ return PermissionDescriptor::from_js(vm, value);+ #[cfg(not(web_idl_bindings))]+ {+ let _ = (vm, value);+ unreachable!("converting to PermissionDescriptor requires the generated bindings")+ }+}++impl Permissions {+ // https://w3c.github.io/permissions/#query-method+ pub(crate) fn query(+ &self,+ cx: &mut CallContext,+ promise: WebIdlPromise,+ permission_desc: Gc<Object>,+ ) -> WebIdlResult<()> {+ let vm = cx.vm();+ let realm = vm.current_realm().expect("query() runs in a realm");+ let relevant_global_object = realm.global_object();++ // 1. If this's relevant global object is a Window object, then:+ if let Some(window) = window_from_global_object(relevant_global_object) {+ // 1. If the current settings object's associated Document is not fully active, return a promise rejected with an "InvalidStateError" DOMException.+ if !window.associated_document().is_fully_active() {+ let error = exception_value(+ vm,+ realm,+ Exception::Dom(+ "InvalidStateError",+ Utf16String::from_ascii(b"The document is not fully active."),+ ),+ );+ reject_promise(vm, promise, error);+ return Ok(());+ }+ }++ // 2. Let rootDesc be the object permissionDesc refers to, converted to an IDL value of type PermissionDescriptor.+ // 3. If the conversion throws an exception, return a promise rejected with that exception.+ let root_desc = match convert_to_permission_descriptor(vm, Value::from_object(permission_desc)) {+ Ok(root_desc) => root_desc,+ Err(throw) => {+ reject_promise(vm, promise, throw.value());+ return Ok(());+ }+ };++ // 4. If rootDesc["name"] is not supported, return a promise rejected with a TypeError.+ if PermissionName::from_name(&root_desc.name).is_none() {+ let Err(error) = vm.throw_completion::<()>(+ ErrorKind::TypeError,+ ErrorType::InvalidEnumerationValue,+ &[&root_desc.name, &"PermissionName"],+ ) else {+ unreachable!("throw_completion() throws")+ };+ reject_promise(vm, promise, error.value());+ return Ok(());+ }++ // 5. Let typedDescriptor be the object permissionDesc refers to, converted to an IDL value of rootDesc's name's permission descriptor type.+ // 6. If the conversion throws an exception, return a promise rejected with that exception.+ // FIXME: Support specific permission descriptor types. For now, we only support the base PermissionDescriptor.+ let typed_descriptor = root_desc;++ // 8. Return promise and continue in parallel:+ // FIXME: Continue in parallel.+ {+ // 1. Let status be create a PermissionStatus with typedDescriptor.+ let status = PermissionStatus::create(vm, realm, typed_descriptor);++ // 2. Let query be status's [[query]] internal slot.+ let query = status.query();++ // 3. Run query's name's permission query algorithm, passing query and status.+ // FIXME: For now, only the base PermissionDescriptor is supported so there is only one permission query algorithm.+ // NB: The status was registered for changes when it was created, so a change from here on reaches it.+ permission_query_algorithm(query, &status, &relevant_settings_object(relevant_global_object));++ // 4. Queue a global task on the permissions task source with this's relevant global object to resolve promise with status.+ queue_a_global_task(+ vm,+ relevant_global_object,+ TaskSource::Permissions,+ (realm, promise, status),+ |vm, (realm, promise, status)| {+ with_temporary_execution_context(realm, || {+ let wrapper = wrap(&CallContext::new(vm, realm), status);+ resolve_promise(vm, promise, Value::from_object(wrapper));+ });+ },+ );+ }++ Ok(())+ }+}++// https://w3c.github.io/permissions/#dfn-permission-query-algorithm+fn permission_query_algorithm(+ permission_desc: &PermissionDescriptor,+ status: &PermissionStatus,+ settings: &CppEnvironmentSettingsObject,+) {+ // 1. Set status's state to permissionDesc's permission state.+ let name = PermissionName::from_name(&permission_desc.name).expect("the name is supported");+ status.set_state(permission_state(name, settings));+}diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txtindex b127b4f36d7..52cacf4250f 100644--- a/Libraries/LibWeb/CMakeLists.txt+++ b/Libraries/LibWeb/CMakeLists.txt@@ -723,7 +723,6 @@ set(SOURCESPainting/SvgPaintResources.cppPermissionsAPI/Permissions.cppPermissionsAPI/PermissionStore.cpp- PermissionsAPI/PermissionStatus.cppPictureInPicture/PictureInPictureController.cppPictureInPicture/PictureInPictureEvent.cppPictureInPicture/PictureInPictureWindow.cppdiff --git a/Libraries/LibWeb/Forward.h b/Libraries/LibWeb/Forward.hindex 94b6fc19625..3b87a19d69b 100644--- a/Libraries/LibWeb/Forward.h+++ b/Libraries/LibWeb/Forward.h@@ -1013,7 +1013,6 @@ class PerformanceEntry;namespace Web::PermissionsAPI {class Permissions;-class PermissionStatus;}diff --git a/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp b/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cppindex d9000441e80..2ee67804e0e 100644--- a/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp+++ b/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp@@ -68,7 +68,6 @@#include <LibWeb/Page/RenderingStats.h>#include <LibWeb/PaintTiming/PerformancePaintTiming.h>#include <LibWeb/Painting/PaintingRustBridge.h>-#include <LibWeb/PermissionsAPI/PermissionStatus.h>#include <LibWeb/Platform/EventLoopPlugin.h>#include <LibWeb/Platform/ImageCodecPlugin.h>#include <LibWeb/SVG/SVGDecodedImageData.h>@@ -101,7 +100,7 @@ namespace Web::HTML {WindowOrWorkerGlobalScopeMixin::~WindowOrWorkerGlobalScopeMixin() = default;-void WindowOrWorkerGlobalScopeMixin::register_permission_status(PermissionsAPI::PermissionStatus& status)+void WindowOrWorkerGlobalScopeMixin::register_permission_status(DOM::EventTarget& status){m_permission_statuses.append(status);}@@ -1580,6 +1579,14 @@ WebIDL::ExceptionOr<GC::Ref<WebIDL::Promise>> fetch(JS::Realm& realm, HTML::Windnamespace Web::HTML {+extern "C" void web_html_window_or_worker_global_scope_register_permission_status(JSObject* global_object, DOM::EventTarget* status);++void web_html_window_or_worker_global_scope_register_permission_status(JSObject* global_object, DOM::EventTarget* status)+{+ if (auto* global_scope = window_or_worker_global_scope_from_global_object(*JS::HostABI::object_from_abi(global_object)))+ global_scope->register_permission_status(*status);+}+extern "C" void web_html_window_or_worker_global_scope_run_steps_after_a_timeout(JSObject* global_object, u64 milliseconds, void* cell, void (*steps)(JSVM*, void*));void web_html_window_or_worker_global_scope_run_steps_after_a_timeout(JSObject* global_object, u64 milliseconds, void* cell, void (*steps)(JSVM*, void*))diff --git a/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.h b/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.hindex a65bdbbdac5..60a762cd538 100644--- a/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.h+++ b/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.h@@ -70,7 +70,7 @@ public:void add_performance_entry(GC::Ref<PerformanceTimeline::PerformanceEntry> new_entry, CheckIfPerformanceBufferIsFull check_if_performance_buffer_is_full = CheckIfPerformanceBufferIsFull::No);void register_event_source(Badge<EventSource>, GC::Ref<EventSource>);- void register_permission_status(PermissionsAPI::PermissionStatus&);+ void register_permission_status(DOM::EventTarget&);void unregister_event_source(Badge<EventSource>, GC::Ref<EventSource>);void forcibly_close_all_event_sources();@@ -183,7 +183,7 @@ private:// The open BroadcastChannel objects with a message or messageerror listener, which this global keeps alive. They're// held here rather than rooted — so a channel that's never closed can't keep its global alive.HashTable<GC::Ref<DOM::EventTarget>> m_strongly_referenced_broadcast_channels;- Vector<GC::Weak<PermissionsAPI::PermissionStatus>> m_permission_statuses;+ Vector<GC::Weak<DOM::EventTarget>> m_permission_statuses;GC::Ptr<IndexedDB::IDBFactory> m_indexed_db;diff --git a/Libraries/LibWeb/PermissionsAPI/PermissionStatus.cpp b/Libraries/LibWeb/PermissionsAPI/PermissionStatus.cppdeleted file mode 100644index 0974bf08bd2..00000000000--- a/Libraries/LibWeb/PermissionsAPI/PermissionStatus.cpp+++ /dev/null@@ -1,113 +0,0 @@-/*- * Copyright (c) 2026, Niccolo Antonelli-Dziri <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <AK/Types.h>-#include <LibGC/Heap.h>-#include <LibWeb/DOM/Document.h>-#include <LibWeb/DOM/Event.h>-#include <LibWeb/HTML/EventLoop/EventLoop.h>-#include <LibWeb/HTML/EventLoop/Task.h>-#include <LibWeb/HTML/EventNames.h>-#include <LibWeb/HTML/Scripting/Environments.h>-#include <LibWeb/HTML/Window.h>-#include <LibWeb/HTML/WindowOrWorkerGlobalScope.h>-#include <LibWeb/HighResolutionTime/TimeOrigin.h>-#include <LibWeb/PermissionsAPI/PermissionStatus.h>-#include <LibWeb/PermissionsAPI/PermissionStore.h>-#include <LibWeb/PermissionsAPI/Permissions.h>--namespace Web::PermissionsAPI {--GC_DEFINE_ALLOCATOR(PermissionStatus);--PermissionStatus::PermissionStatus(GC::Ref<DOM::EventTarget> relevant_global_object, Utf16String const& name,- Web::Permissions::PermissionName permission_name, PermissionDescriptor query)- : DOM::EventTarget()- , m_name(name)- , m_permission_name(permission_name)- , m_query(move(query))- , m_global_object(relevant_global_object)-{-}--void PermissionStatus::visit_edges(Cell::Visitor& visitor)-{- Base::visit_edges(visitor);- visitor.visit(m_global_object);-}--GC::Ref<PermissionStatus> PermissionStatus::create(GC::Ref<DOM::EventTarget> relevant_global_object, PermissionDescriptor permission_desc)-{- // 1. Let name be permissionDesc's name.- auto name = permission_desc.name;-- // 2. Assert: The feature identified by name is supported by the user agent.- auto permission_name = permission_name_from(name);- VERIFY(permission_name.has_value());-- // 3. Let status be a new instance of the permission result type identified by name:- // FIXME: A permission result type is a PermissionStatus or one of its subtypes.- // If unspecified, this defaults to PermissionStatus. No subtypes exist yet in Ladybird.- // 1. Initialize status's [[query]] internal slot to permissionDesc.- // 2. Initialize status's name to name.- auto status = GC::Heap::the().allocate<PermissionStatus>(relevant_global_object, name, *permission_name, move(permission_desc));-- // NB: The store tells every status when a permission changes, and the global keeps a status alive while it has a- // change listener.- PermissionStore::the().register_status(status);- if (auto* global_scope = HTML::window_or_worker_global_scope_from_global_object(status->relevant_global_object()))- global_scope->register_permission_status(status);-- // 4. Return status.- return status;-}--PermissionState PermissionStatus::state() const-{- return m_state;-}--void PermissionStatus::update_from_store()-{- auto& global = relevant_global_object();-- // A document that isn't fully active sees no change until it is again.- if (auto* window = HTML::window_from_global_object(global); window && !window->associated_document().is_fully_active())- return;-- auto state = permission_state(m_permission_name, HTML::relevant_settings_object(global));- if (state == m_state)- return;-- // NB: The state is read again when the task runs, so a status that heard of several changes ends with the last.- HTML::queue_global_task(HTML::Task::Source::Permissions, global, GC::create_function(heap(), GC::captures(*this), [](auto& self) {- auto& global = self.relevant_global_object();- auto state = permission_state(self.m_permission_name, HTML::relevant_settings_object(global));- if (state == self.m_state)- return;- self.m_state = state;- self.dispatch_event(DOM::Event::create(global, HTML::EventNames::change));- }));-}--JS::Object& PermissionStatus::relevant_global_object() const-{- return HTML::relevant_global_object(HTML::relevant_window_or_worker_global_scope(*m_global_object));-}--// https://w3c.github.io/permissions/#dom-permissionstatus-onchange-void PermissionStatus::set_onchange(GC::Ptr<WebIDL::CallbackType> event_handler)-{- set_event_handler_attribute(HTML::EventNames::change, event_handler);-}--// https://w3c.github.io/permissions/#dom-permissionstatus-onchange-GC::Ptr<WebIDL::CallbackType> PermissionStatus::onchange()-{- return event_handler_attribute(HTML::EventNames::change);-}--}diff --git a/Libraries/LibWeb/PermissionsAPI/PermissionStatus.h b/Libraries/LibWeb/PermissionsAPI/PermissionStatus.hdeleted file mode 100644index 0e5b7854c75..00000000000--- a/Libraries/LibWeb/PermissionsAPI/PermissionStatus.h+++ /dev/null@@ -1,54 +0,0 @@-/*- * Copyright (c) 2026, Niccolo Antonelli-Dziri <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <LibWeb/DOM/EventTarget.h>-#include <LibWeb/Forward.h>-#include <LibWeb/PermissionsAPI/Permissions.h>--namespace Web::PermissionsAPI {--class WEB_API PermissionStatus : public DOM::EventTarget {- WEB_WRAPPABLE(PermissionStatus, DOM::EventTarget);- GC_DECLARE_ALLOCATOR(PermissionStatus);--public:- static GC::Ref<PermissionStatus> create(GC::Ref<DOM::EventTarget> relevant_global_object, PermissionDescriptor);-- // https://w3c.github.io/permissions/#dom-permissionstatus-state- PermissionState state() const;- void set_state(PermissionState state) { m_state = state; }-- // https://w3c.github.io/permissions/#dom-permissionstatus-name- Utf16String const& name() const { return m_name; }-- PermissionDescriptor const& query() const { return m_query; }-- // Reads the state again from the permission store, and fires change at this status if it moved.- void update_from_store();-- // https://w3c.github.io/permissions/#dom-permissionstatus-onchange- void set_onchange(GC::Ptr<WebIDL::CallbackType> event_handler);- GC::Ptr<WebIDL::CallbackType> onchange();--private:- PermissionStatus(GC::Ref<DOM::EventTarget> relevant_global_object, Utf16String const&,- Web::Permissions::PermissionName, PermissionDescriptor);- JS::Object& relevant_global_object() const;- virtual void visit_edges(Cell::Visitor&) override;-- Utf16String m_name;- Web::Permissions::PermissionName m_permission_name;- PermissionState m_state { PermissionState::Prompt };-- // https://w3c.github.io/permissions/#dfn-query- PermissionDescriptor m_query;-- GC::Ref<DOM::EventTarget> m_global_object;-};--}diff --git a/Libraries/LibWeb/PermissionsAPI/PermissionStatus.idl b/Libraries/LibWeb/PermissionsAPI/PermissionStatus.idlindex 9f783ba0a30..312b1c28af9 100644--- a/Libraries/LibWeb/PermissionsAPI/PermissionStatus.idl+++ b/Libraries/LibWeb/PermissionsAPI/PermissionStatus.idl@@ -1,5 +1,5 @@// https://w3c.github.io/permissions/#permissionstatus-interface-[Exposed=(Window,Worker)]+[Exposed=(Window,Worker), ImplementedIn=Rust]interface PermissionStatus : EventTarget {readonly attribute PermissionState state;readonly attribute DOMString name;diff --git a/Libraries/LibWeb/PermissionsAPI/PermissionStore.cpp b/Libraries/LibWeb/PermissionsAPI/PermissionStore.cppindex f14b1a9a8ed..380f03e9c99 100644--- a/Libraries/LibWeb/PermissionsAPI/PermissionStore.cpp+++ b/Libraries/LibWeb/PermissionsAPI/PermissionStore.cpp@@ -4,8 +4,8 @@* SPDX-License-Identifier: BSD-2-Clause*/-#include <AK/NeverDestroyed.h>-#include <LibGC/Root.h>+#include <LibJS/HostClassBuilder.h>+#include <LibJS/Runtime/VM.h>#include <LibWeb/DOM/Document.h>#include <LibWeb/HTML/LocalNavigable.h>#include <LibWeb/HTML/Navigator.h>@@ -13,7 +13,6 @@#include <LibWeb/HTML/Window.h>#include <LibWeb/MediaCapture/MediaDevices.h>#include <LibWeb/Page/Page.h>-#include <LibWeb/PermissionsAPI/PermissionStatus.h>#include <LibWeb/PermissionsAPI/PermissionStore.h>namespace Web::PermissionsAPI {@@ -55,22 +54,9 @@ PermissionStore& PermissionStore::the()return s_the;}-struct AgentPermissionStatuses {- Vector<GC::Weak<PermissionStatus>> statuses;-- // The newest snapshot that these statuses have seen.- Optional<u64> revision;-};--static AgentPermissionStatuses& agent_permission_statuses()-{- static thread_local NeverDestroyed<AgentPermissionStatuses> statuses;- return *statuses;-}--void PermissionStore::forget_statuses_of_this_agent()-{- agent_permission_statuses() = {};+extern "C" {+// Defined in Bindings/Rust/src/permissions_api/exports.rs.+bool web_rust_permissions_api_update_statuses_of_this_agent(JSVM*, u64 revision, bool store_changed);}Optional<PermissionStoreEntry> PermissionStore::get_permission_store_entry(Web::Permissions::PermissionName name, URL::Origin const& key)@@ -142,28 +128,9 @@ void PermissionStore::apply_snapshot(Web::Permissions::PermissionSnapshot snapshif (notify == Notify::No)return;- // NB: The agent that got here first made the change, and the others still have to hear of it. An agent has heard of a- // revision only once its statuses have, which is not the case for one that it fetched without telling them.- auto& agent = agent_permission_statuses();- if (!agent.revision.has_value() || snapshot.revision > *agent.revision) {- agent.revision = snapshot.revision;- changed = true;- }-- if (!changed)+ if (!web_rust_permissions_api_update_statuses_of_this_agent(JS::HostABI::vm_to_abi(JS::VM::the()), snapshot.revision, changed))return;- // NB: Updating a status allocates, and a collection then could clear another status's weak reference, so every- // live status is rooted first.- agent.statuses.remove_all_matching([](auto const& status) { return !status; });- Vector<GC::Root<PermissionStatus>> statuses;- for (auto const& status : agent.statuses) {- if (status)- statuses.append(GC::make_root(status.ptr()));- }- for (auto const& status : statuses)- status->update_from_store();-// Only a window agent has documents.if (!HTML::surrounding_agent().is_similar_origin_window_agent())return;@@ -232,9 +199,4 @@ Vector<String> PermissionStore::cached_origins_for_testing() constreturn origins;}-void PermissionStore::register_status(PermissionStatus& status)-{- agent_permission_statuses().statuses.append(status);-}-}diff --git a/Libraries/LibWeb/PermissionsAPI/PermissionStore.h b/Libraries/LibWeb/PermissionsAPI/PermissionStore.hindex 8212b118580..b24553fe3cd 100644--- a/Libraries/LibWeb/PermissionsAPI/PermissionStore.h+++ b/Libraries/LibWeb/PermissionsAPI/PermissionStore.h@@ -12,7 +12,6 @@#include <AK/String.h>#include <AK/Vector.h>#include <AK/kmalloc.h>-#include <LibGC/Weak.h>#include <LibURL/Origin.h>#include <LibWeb/Export.h>#include <LibWeb/PermissionsAPI/Permissions.h>@@ -20,8 +19,6 @@namespace Web::PermissionsAPI {-class PermissionStatus;-// https://w3c.github.io/permissions/#dfn-permission-store-entrystruct PermissionStoreEntry {Web::Permissions::PermissionName name;@@ -56,14 +53,9 @@ public:void apply_snapshot(Web::Permissions::PermissionSnapshot, Notify = Notify::Yes);Web::Permissions::EffectiveState state_for(Web::Permissions::PermissionName, URL::Origin const& key, Page&);- void register_status(PermissionStatus&);-// The sites this process holds decisions for.Vector<String> cached_origins_for_testing() const;- // For an agent that goes away, whose statuses have to go with its heap.- static void forget_statuses_of_this_agent();-private:PermissionStore() = default;diff --git a/Libraries/LibWeb/PermissionsAPI/Permissions.cpp b/Libraries/LibWeb/PermissionsAPI/Permissions.cppindex f698e91e12d..5a037a7d167 100644--- a/Libraries/LibWeb/PermissionsAPI/Permissions.cpp+++ b/Libraries/LibWeb/PermissionsAPI/Permissions.cpp@@ -5,22 +5,15 @@*/#include <LibGC/Heap.h>-#include <LibJS/Runtime/Error.h>-#include <LibWeb/Bindings/Permissions.h>+#include <LibJS/HostClassBuilder.h>+#include <LibJS/Runtime/VM.h>#include <LibWeb/Bindings/PrincipalHostDefined.h>-#include <LibWeb/Bindings/Wrappable.h>-#include <LibWeb/Bindings/WrapperWorld.h>#include <LibWeb/DOM/Document.h>#include <LibWeb/HTML/Scripting/Environments.h>-#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>#include <LibWeb/HTML/Window.h>-#include <LibWeb/HTML/WindowOrWorkerGlobalScope.h>#include <LibWeb/Page/Page.h>-#include <LibWeb/PermissionsAPI/PermissionStatus.h>#include <LibWeb/PermissionsAPI/PermissionStore.h>#include <LibWeb/PermissionsAPI/Permissions.h>-#include <LibWeb/WebIDL/DOMException.h>-#include <LibWeb/WebIDL/Promise.h>namespace Web::PermissionsAPI {@@ -163,83 +156,26 @@ PermissionState permission_state(Web::Permissions::PermissionName name, Optionalreturn permission_state_from(PermissionStore::the().state_for(feature, key, page));}-GC_DEFINE_ALLOCATOR(Permissions);--GC::Ref<Permissions> Permissions::create()-{- return GC::Heap::the().allocate<Permissions>();+extern "C" {+Permissions* web_rust_permissions_api_create_permissions(JSVM*);+u8 web_permissions_api_permission_state(HTML::EnvironmentSettingsObject*, u8 name);}-Permissions::Permissions() = default;+static_assert(to_underlying(Web::Permissions::PermissionName::Geolocation) == 0);+static_assert(to_underlying(Web::Permissions::PermissionName::Microphone) == 1);+static_assert(to_underlying(Web::Permissions::PermissionName::Notifications) == 2);+static_assert(to_underlying(PermissionState::Granted) == 0);+static_assert(to_underlying(PermissionState::Denied) == 1);+static_assert(to_underlying(PermissionState::Prompt) == 2);-// https://w3c.github.io/permissions/#query-method-void Permissions::query(GC::Ref<JS::Object> permission_desc, GC::Ref<WebIDL::Promise> promise)+GC::Ref<Permissions> Permissions::create(){- auto& relevant_global_object = HTML::current_global_object();- auto& realm = HTML::relevant_realm(relevant_global_object);- auto& vm = realm.vm();-- // 1. If this's relevant global object is a Window object, then:- if (auto* window = HTML::window_from_global_object(relevant_global_object)) {- // 1. If the current settings object's associated Document is not fully active, return a promise rejected with an "InvalidStateError" DOMException.- if (!window->associated_document().is_fully_active()) {- auto error = WebIDL::InvalidStateError::create(realm, "The document is not fully active."_utf16);- WebIDL::reject_promise(promise, error);- return;- }- }-- // 2. Let rootDesc be the object permissionDesc refers to, converted to an IDL value of type PermissionDescriptor.- // 3. If the conversion throws an exception, return a promise rejected with that exception.- auto root_desc_or_error = Bindings::convert_to_idl_value_for_permission_descriptor(vm, permission_desc);- if (root_desc_or_error.is_error()) {- WebIDL::reject_promise(promise, root_desc_or_error.release_error().value());- return;- }- auto root_desc = root_desc_or_error.release_value();-- // 4. If rootDesc["name"] is not supported, return a promise rejected with a TypeError.- if (!permission_name_from(root_desc.name).has_value()) {- auto error = vm.throw_completion<JS::TypeError>(JS::ErrorType::InvalidEnumerationValue, root_desc.name, "PermissionName"sv);- WebIDL::reject_promise(promise, error.release_error().value());- return;- }-- // 5. Let typedDescriptor be the object permissionDesc refers to, converted to an IDL value of rootDesc's name's permission descriptor type.- // 6. If the conversion throws an exception, return a promise rejected with that exception.- // FIXME: Support specific permission descriptor types. For now, we only support the base PermissionDescriptor.- auto typed_descriptor = root_desc;-- // 8. Return promise and continue in parallel:- // FIXME: Continue in parallel.- {- // 1. Let status be create a PermissionStatus with typedDescriptor.- auto* global_scope = HTML::window_or_worker_global_scope_from_global_object(relevant_global_object);- VERIFY(global_scope);- auto status = PermissionStatus::create(global_scope->this_impl(), typed_descriptor);-- // 2. Let query be status's [[query]] internal slot.- auto const& query = status->query();-- // 3. Run query's name's permission query algorithm, passing query and status.- // FIXME: For now, only the base PermissionDescriptor is supported so there is only one permission query algorithm.- // NB: The status was registered for changes when it was created, so a change from here on reaches it.- permission_query_algorithm(query, status, HTML::relevant_settings_object(relevant_global_object));-- // 4. Queue a global task on the permissions task source with this's relevant global object to resolve promise with status.- HTML::queue_global_task(HTML::Task::Source::Permissions, relevant_global_object, GC::create_function(GC::Heap::the(), GC::captures(GC::Ref(relevant_global_object), promise, status), [](auto& relevant_global_object, auto& promise, auto& status) {- auto& realm = HTML::relevant_realm(relevant_global_object);- HTML::TemporaryExecutionContext execution_context { realm };- WebIDL::resolve_promise(promise, Bindings::wrap(Bindings::host_defined_wrapper_world(realm), realm, status));- }));- }+ return *web_rust_permissions_api_create_permissions(JS::HostABI::vm_to_abi(JS::VM::the()));}-// https://w3c.github.io/permissions/#dfn-permission-query-algorithm-void permission_query_algorithm(PermissionDescriptor const& permission_desc, PermissionStatus& status, HTML::EnvironmentSettingsObject& settings)+u8 web_permissions_api_permission_state(HTML::EnvironmentSettingsObject* settings, u8 name){- // 1. Set status's state to permissionDesc's permission state.- status.set_state(permission_state(*permission_name_from(permission_desc.name), settings));+ return to_underlying(permission_state(static_cast<Web::Permissions::PermissionName>(name), *settings));}}diff --git a/Libraries/LibWeb/PermissionsAPI/Permissions.h b/Libraries/LibWeb/PermissionsAPI/Permissions.hindex 65755fec53b..1b09d8f21ff 100644--- a/Libraries/LibWeb/PermissionsAPI/Permissions.h+++ b/Libraries/LibWeb/PermissionsAPI/Permissions.h@@ -13,14 +13,13 @@#include <LibGC/Ptr.h>#include <LibWeb/Bindings/PermissionStatus.h>#include <LibWeb/Bindings/Permissions.h>-#include <LibWeb/Bindings/Wrappable.h>+#include <LibWeb/Bindings/RustInterface.h>#include <LibWeb/Export.h>#include <LibWeb/Forward.h>#include <LibWebCommon/Permissions/Permissions.h>namespace Web::PermissionsAPI {-using PermissionDescriptor = Bindings::PermissionDescriptor;using PermissionState = Bindings::PermissionState;Optional<Web::Permissions::PermissionName> permission_name_from(Utf16View);@@ -31,19 +30,11 @@ PermissionState permission_state(Web::Permissions::PermissionName, Optional<HTMLusing PermissionDecisionCallback = GC::Ref<GC::Function<void(PermissionState)>>;void request_permission_with_user_prompt(Web::Permissions::PermissionName, HTML::EnvironmentSettingsObject&, PermissionDecisionCallback);-class WEB_API Permissions : public Bindings::GCAllocatedWrappable {- WEB_WRAPPABLE(Permissions, Bindings::GCAllocatedWrappable);- GC_DECLARE_ALLOCATOR(Permissions);+class Permissions : public Bindings::RustInterfaceCell {+ WEB_RUST_INTERFACE(Permissions, permissions)public:- static GC::Ref<Permissions> create();-- void query(GC::Ref<JS::Object> permission_desc, GC::Ref<WebIDL::Promise>);--private:- Permissions();+ [[nodiscard]] static GC::Ref<Permissions> create();};-void permission_query_algorithm(PermissionDescriptor const&, PermissionStatus&, HTML::EnvironmentSettingsObject&);-}diff --git a/Libraries/LibWeb/PermissionsAPI/Permissions.idl b/Libraries/LibWeb/PermissionsAPI/Permissions.idlindex c58ec7a3d63..d41c7e80e43 100644--- a/Libraries/LibWeb/PermissionsAPI/Permissions.idl+++ b/Libraries/LibWeb/PermissionsAPI/Permissions.idl@@ -1,9 +1,10 @@// https://w3c.github.io/permissions/#permissions-interface-[Exposed=(Window,Worker)]+[Exposed=(Window,Worker), ImplementedIn=Rust]interface Permissions {[CreatesPromise] Promise<PermissionStatus> query(object permissionDesc);};+[ImplementedIn=Rust]dictionary PermissionDescriptor {required DOMString name;};