Truly independent web browser
LibWeb+Meta: Implement the Cookie Store API in Rust
Shannon Booth7e47eb4b9347
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/environment_settings_object.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/environment_settings_object.rsindex 39b8817df1c..c11f5be23d2 100644--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/environment_settings_object.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/environment_settings_object.rs@@ -45,6 +45,11 @@ unsafe extern "C" {origin: *mut c_void,on_origin: unsafe extern "C" fn(*mut c_void, *const FfiOrigin),);+ fn web_bindings_environment_settings_object_creation_url(+ settings_object: *mut c_void,+ url: *mut c_void,+ on_url: unsafe extern "C" fn(*mut c_void, *const RustUrl),+ );fn web_bindings_environment_settings_object_encoding_parse_url(settings_object: *mut c_void,url: usize,@@ -142,6 +147,14 @@ impl CppEnvironmentSettingsObject {origin.expect("LibWeb lends the origin")}+ /// https://html.spec.whatwg.org/multipage/webappapis.html#concept-environment-creation-url+ pub(crate) fn creation_url(&self) -> Url {+ let mut url = None;+ // SAFETY: The settings object is live, and the URL outlives the call.+ unsafe { web_bindings_environment_settings_object_creation_url(self.as_ptr(), (&raw mut url).cast(), on_url) };+ url.expect("LibWeb lends the creation URL")+ }+/// https://html.spec.whatwg.org/multipage/webappapis.html#concept-environment-top-level-originpub(crate) fn top_level_origin(&self) -> Option<Origin> {let mut origin = None;diff --git a/Libraries/LibWeb/Bindings/Rust/src/cookie_store/cookie_change_event.rs b/Libraries/LibWeb/Bindings/Rust/src/cookie_store/cookie_change_event.rsnew file mode 100644index 00000000000..c1d8c9fe057--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/cookie_store/cookie_change_event.rs@@ -0,0 +1,88 @@+/*+ * Copyright (c) 2025, Idan Horowitz <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! CookieChangeEvent, https://cookiestore.spec.whatwg.org/#cookiechangeevent++use core::ffi::c_void;+use core::ptr::NonNull;++use ak::Utf16String;+use libjs_rust::api::{Gc, Realm, Trace, Vm};++use crate::bindings::event_target::CppEvent;+use crate::bindings::interface::{Ref, Wrappable, allocate};+use crate::bindings::{CallContext, WebIdlResult};+use crate::cookie_store::cookie_store::CookieListItem;+use crate::dom::event::EventInit;++/// The dictionary CookieChangeEventInit of CookieStore/CookieChangeEvent.idl.+pub(crate) struct CookieChangeEventInit {+ pub(crate) parent: EventInit,+ pub(crate) changed: Option<Vec<CookieListItem>>,+ pub(crate) deleted: Option<Vec<CookieListItem>>,+}++// https://cookiestore.spec.whatwg.org/#cookiechangeevent+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct CookieChangeEvent {+ event: CppEvent,+ #[gc(untraced)]+ changed: Vec<CookieListItem>,+ #[gc(untraced)]+ deleted: Vec<CookieListItem>,+}++impl Wrappable for CookieChangeEvent {+ fn cpp_parent(&self) -> Option<NonNull<c_void>> {+ self.event.as_cpp_parent()+ }+}++impl CookieChangeEvent {+ pub(crate) fn create(+ vm: &Vm,+ realm: Gc<Realm>,+ event_name: &Utf16String,+ event_init: CookieChangeEventInit,+ ) -> Ref<CookieChangeEvent> {+ let event = CppEvent::create_for_owner(+ realm,+ event_name,+ event_init.parent.bubbles,+ event_init.parent.cancelable,+ event_init.parent.composed,+ );+ let object = allocate(vm, |_| CookieChangeEvent {+ event,+ changed: event_init.changed.unwrap_or_default(),+ deleted: event_init.deleted.unwrap_or_default(),+ });+ object.event.set_owner(object);+ object+ }++ pub(crate) fn construct(+ cx: &mut CallContext,+ r#type: Utf16String,+ event_init_dict: CookieChangeEventInit,+ ) -> WebIdlResult<Ref<CookieChangeEvent>> {+ Ok(Self::create(cx.vm(), cx.realm(), &r#type, event_init_dict))+ }++ pub(crate) fn event(&self) -> &CppEvent {+ &self.event+ }++ pub(crate) fn changed(&self, _: &mut CallContext) -> WebIdlResult<Vec<CookieListItem>> {+ Ok(self.changed.clone())+ }++ pub(crate) fn deleted(&self, _: &mut CallContext) -> WebIdlResult<Vec<CookieListItem>> {+ Ok(self.deleted.clone())+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/cookie_store/cookie_store.rs b/Libraries/LibWeb/Bindings/Rust/src/cookie_store/cookie_store.rsnew file mode 100644index 00000000000..402e1717785--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/cookie_store/cookie_store.rs@@ -0,0 +1,1095 @@+/*+ * Copyright (c) 2025, Idan Horowitz <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! CookieStore, https://cookiestore.spec.whatwg.org/#cookiestore++use core::ffi::c_void;+use core::ptr::NonNull;+use std::time::{SystemTime, UNIX_EPOCH};++use ak::Utf16String;+use libjs_rust::api::{Gc, Object, Realm, Trace, Value, Vm};+use liburl_rust::origin::Host;+use liburl_rust::url::{ExcludeFragment, UrlInput, parse_host};+use liburl_rust::{BasicParseOptions, RustUrl, Url, basic_parse};++use crate::bindings::conversions::UsvString;+#[cfg(web_idl_bindings)]+use crate::bindings::conversions::{ToJs, sequence_to_js};+use crate::bindings::environment_settings_object::{CppEnvironmentSettingsObject, relevant_settings_object};+use crate::bindings::event_target::{CppEventTarget, GetTheParent};+use crate::bindings::global_object::window_from_global_object;+use crate::bindings::interface::{Ref, Wrappable, allocate, with_temporary_execution_context};+use crate::bindings::promise::{+ TaskSource, WebIdlPromise, create_promise, create_rejected_promise_from_exception, deferred_invoke, promise_realm,+ queue_a_global_task, reject_promise_with_exception, resolve_promise,+};+use crate::bindings::{CallContext, Exception, WebIdlResult};+use crate::cookie_store::cookie_change_event::{CookieChangeEvent, CookieChangeEventInit};+use crate::dom::document::is_a_registrable_domain_suffix_of_or_is_equal_to;+use crate::dom::event::EventInit;++#[repr(C)]+struct ParsedCookieAbi<'a> {+ name: ak::Span<'a, u8>,+ value: ak::Span<'a, u8>,+ has_expiry_time: bool,+ expiry_time: i64,+ has_domain: bool,+ domain: ak::Span<'a, u8>,+ path: ak::Span<'a, u8>,+ secure_attribute_present: bool,+ same_site_attribute: u8,+}++/// The values of HTTP::Cookie::SameSite.+const SAME_SITE_NONE: u8 = 1;+const SAME_SITE_STRICT: u8 = 2;+const SAME_SITE_LAX: u8 = 3;++unsafe extern "C" {+ fn web_cookie_store_request_all_cookies(+ settings_object: *mut c_void,+ url: *const RustUrl,+ ctx: *mut c_void,+ on_cookie: unsafe extern "C" fn(*mut c_void, ak::Span<'_, u8>, ak::Span<'_, u8>, bool),+ );+ fn web_cookie_store_set_cookie(settings_object: *mut c_void, url: *const RustUrl, cookie: *const ParsedCookieAbi);+}++/// The dictionary CookieListItem of CookieStore/CookieStore.idl.+#[derive(Clone)]+pub(crate) struct CookieListItem {+ pub(crate) name: Option<UsvString>,+ pub(crate) value: Option<UsvString>,+}++/// The dictionary CookieStoreGetOptions of CookieStore/CookieStore.idl.+#[derive(Default)]+pub(crate) struct CookieStoreGetOptions {+ pub(crate) name: Option<UsvString>,+ pub(crate) url: Option<UsvString>,+}++/// The enumeration CookieSameSite of CookieStore/CookieStore.idl.+#[derive(Clone, Copy, Default)]+pub(crate) enum CookieSameSite {+ #[default]+ Strict,+ Lax,+ None,+}++/// The dictionary CookieInit of CookieStore/CookieStore.idl.+pub(crate) struct CookieInit {+ pub(crate) name: UsvString,+ pub(crate) value: UsvString,+ pub(crate) expires: Option<f64>,+ pub(crate) domain: Option<UsvString>,+ pub(crate) path: UsvString,+ pub(crate) same_site: CookieSameSite,+ pub(crate) partitioned: bool,+}++/// The dictionary CookieStoreDeleteOptions of CookieStore/CookieStore.idl.+pub(crate) struct CookieStoreDeleteOptions {+ pub(crate) name: UsvString,+ pub(crate) domain: Option<UsvString>,+ pub(crate) path: UsvString,+ pub(crate) partitioned: bool,+}++/// A cookie of the cookie store, as the UI process reports its changes.+#[derive(Clone, Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct Cookie {+ pub(crate) name: String,+ pub(crate) value: String,+ pub(crate) expiry_time_in_milliseconds: i64,+}++#[derive(Clone, Copy, PartialEq, Eq)]+enum EmptyOptionsAllowed {+ No,+ Yes,+}++#[derive(Clone, Copy, PartialEq, Eq)]+enum FirstItemOnly {+ No,+ Yes,+}++#[derive(Clone, Trace)]+#[gc(crate = libjs_rust)]+struct CookieListRequest {+ environment: CppEnvironmentSettingsObject,+ #[gc(untraced)]+ url: Url,+ name: Option<String>,+ global: Gc<Object>,+ promise: WebIdlPromise,+ #[gc(untraced)]+ first_item_only: FirstItemOnly,+}++#[derive(Clone, Trace)]+#[gc(crate = libjs_rust)]+struct CookieMutation {+ environment: CppEnvironmentSettingsObject,+ #[gc(untraced)]+ url: Url,+ name: String,+ value: String,+ #[gc(untraced)]+ expires: Option<f64>,+ domain: Option<String>,+ path: String,+ #[gc(untraced)]+ same_site: CookieSameSite,+ partitioned: bool,+ global: Gc<Object>,+ promise: WebIdlPromise,+ failure_message: &'static str,+}++#[derive(Clone, Trace)]+#[gc(crate = libjs_rust)]+struct CookieDeletion {+ environment: CppEnvironmentSettingsObject,+ #[gc(untraced)]+ url: Url,+ name: String,+ domain: Option<String>,+ path: String,+ partitioned: bool,+ global: Gc<Object>,+ promise: WebIdlPromise,+ failure_message: &'static str,+}++fn cookie_list_item_to_js(cx: &CallContext, item: CookieListItem) -> Value {+ // NB: The generated bindings convert the dictionary, which a build of the crate on its own leaves out.+ #[cfg(web_idl_bindings)]+ return ToJs::to_js(item, cx).expect("a cookie list item converts to a JS value");+ #[cfg(not(web_idl_bindings))]+ {+ let _ = (item, cx);+ unreachable!("only the generated bindings resolve a promise with the dictionary")+ }+}++fn cookie_list_to_js(cx: &CallContext, cookie_list: Vec<CookieListItem>) -> Value {+ #[cfg(web_idl_bindings)]+ return sequence_to_js(cx, cookie_list, |item| ToJs::to_js(item, cx))+ .expect("a cookie list converts to a JS value");+ #[cfg(not(web_idl_bindings))]+ {+ let _ = (cookie_list, cx);+ unreachable!("only the generated bindings resolve a promise with the dictionary")+ }+}++fn resolve_cookie_list_item_or_null_promise(vm: &Vm, promise: WebIdlPromise, cookie_list: Vec<CookieListItem>) {+ let Some(first_item) = cookie_list.into_iter().next() else {+ resolve_promise(vm, promise, Value::NULL);+ return;+ };++ let value = cookie_list_item_to_js(&CallContext::new(vm, promise_realm(promise)), first_item);+ resolve_promise(vm, promise, value);+}++fn resolve_cookie_list_promise(vm: &Vm, promise: WebIdlPromise, cookie_list: Vec<CookieListItem>) {+ let result = cookie_list_to_js(&CallContext::new(vm, promise_realm(promise)), cookie_list);+ resolve_promise(vm, promise, result);+}++fn validate_cookie_store_get_options(+ realm: Gc<Realm>,+ options: &CookieStoreGetOptions,+ empty_options_allowed: EmptyOptionsAllowed,+) -> Result<Url, Exception> {+ // 1. Let settings be this's relevant settings object.+ let settings = relevant_settings_object(realm.global_object());++ // 2. Let origin be settings's origin.+ let origin = settings.origin();++ // 3. If origin is an opaque origin, then return a promise rejected with a "SecurityError" DOMException.+ if origin.is_opaque() {+ return Err(Exception::Dom(+ "SecurityError",+ Utf16String::from_utf8("Document origin is opaque"),+ ));+ }++ // 4. Let url be settings's creation URL.+ let mut url = settings.creation_url();++ // 5. If options is empty, then return a promise rejected with a TypeError.+ if empty_options_allowed == EmptyOptionsAllowed::No && options.name.is_none() && options.url.is_none() {+ return Err(Exception::type_error("CookieStoreGetOptions is empty"));+ }++ // 6. If options["url"] is present, then run these steps:+ if let Some(options_url) = &options.url {+ // 1. Let parsed be the result of parsing options["url"] with settings's API base URL.+ let api_base_url = settings.api_base_url();+ let options_url = options_url.to_utf16();+ let parsed = basic_parse(+ UrlInput::from(&*options_url),+ BasicParseOptions::new().base_url(&api_base_url),+ );++ // AD-HOC: This isn't explicitly mentioned in the specification, but we have to reject invalid URLs as well+ let Some(parsed) = parsed else {+ return Err(Exception::type_error("url is invalid"));+ };++ // 2. If this's relevant global object is a Window object and parsed does not equal url with exclude fragments+ // set to true, then return a promise rejected with a TypeError.+ if window_from_global_object(settings.global_object()).is_some()+ && parsed.serialize(ExcludeFragment::Yes) != url.serialize(ExcludeFragment::Yes)+ {+ return Err(Exception::type_error("url does not match creation URL"));+ }++ // 3. If parsed's origin and url's origin are not the same origin, then return a promise rejected with a TypeError.+ if !parsed.origin().is_same_origin(&url.origin()) {+ return Err(Exception::type_error(+ "url's origin does not match creation URL's origin",+ ));+ }++ // 4. Set url to parsed.+ url = parsed;+ }++ Ok(url)+}++fn validate_cookie_store_mutation(realm: Gc<Realm>) -> Result<Url, Exception> {+ // 1. Let settings be this's relevant settings object.+ let settings = relevant_settings_object(realm.global_object());++ // 2. Let origin be settings's origin.+ let origin = settings.origin();++ // 3. If origin is an opaque origin, then return a promise rejected with a "SecurityError" DOMException.+ if origin.is_opaque() {+ return Err(Exception::Dom(+ "SecurityError",+ Utf16String::from_utf8("Document origin is opaque"),+ ));+ }++ // 4. Let url be settings's creation URL.+ Ok(settings.creation_url())+}++fn complete_cookie_list_request(vm: &Vm, request: CookieListRequest, cookie_list: Vec<CookieListItem>) {+ // AD-HOC: Queue a global task to perform the next steps+ // Spec issue: https://github.com/whatwg/cookiestore/issues/239+ queue_a_global_task(+ vm,+ request.global,+ TaskSource::Unspecified,+ (+ request.promise,+ CookieListResult { list: cookie_list },+ request.first_item_only == FirstItemOnly::Yes,+ ),+ |vm, (promise, cookie_list, first_item_only)| {+ with_temporary_execution_context(promise_realm(promise), || {+ if first_item_only {+ resolve_cookie_list_item_or_null_promise(vm, promise, cookie_list.list);+ } else {+ resolve_cookie_list_promise(vm, promise, cookie_list.list);+ }+ });+ },+ );+}++#[derive(Clone, Trace)]+#[gc(crate = libjs_rust)]+struct CookieListResult {+ #[gc(untraced)]+ list: Vec<CookieListItem>,+}++fn complete_cookie_mutation(+ vm: &Vm,+ global: Gc<Object>,+ promise: WebIdlPromise,+ failure_message: &'static str,+ result: bool,+) {+ // NB: The UI's notification of this mutation's cookie changes is handled from a deferred invocation scheduled while+ // waiting for its reply. Queue the task below after that, so the change event is fired first.+ deferred_invoke(+ vm,+ (global, promise, result, failure_message),+ |vm, (global, promise, result, failure_message)| {+ // AD-HOC: Queue a global task to perform the next steps+ // Spec issue: https://github.com/whatwg/cookiestore/issues/239+ queue_a_global_task(+ vm,+ global,+ TaskSource::Unspecified,+ (promise, result, failure_message),+ |vm, (promise, result, failure_message)| {+ with_temporary_execution_context(promise_realm(promise), || {+ if !result {+ reject_promise_with_exception(vm, promise, Exception::type_error(failure_message));+ return;+ }++ resolve_promise(vm, promise, Value::UNDEFINED);+ });+ },+ );+ },+ );+}++// https://cookiestore.spec.whatwg.org/#create-a-cookielistitem+fn create_a_cookie_list_item(name: &str, value: &str) -> CookieListItem {+ // 1. Let name be the result of running UTF-8 decode without BOM on cookie’s name.+ // 2. Let value be the result of running UTF-8 decode without BOM on cookie’s value.+ // 3. Return «[ "name" → name, "value" → value ]»+ CookieListItem {+ name: Some(UsvString::from_utf8(name)),+ value: Some(UsvString::from_utf8(value)),+ }+}++// https://cookiestore.spec.whatwg.org/#normalize-a-cookie-name-or-value+fn normalize(input: &str) -> &str {+ // Remove all U+0009 TAB and U+0020 SPACE that are at the start or end of input.+ input.trim_matches(['\t', ' '])+}++// https://cookiestore.spec.whatwg.org/#query-cookies+fn query_cookies(environment: &CppEnvironmentSettingsObject, url: &Url, name: Option<&str>) -> Vec<CookieListItem> {+ struct QueriedCookie {+ name: String,+ value: String,+ http_only: bool,+ }++ unsafe extern "C" fn on_cookie(ctx: *mut c_void, name: ak::Span<'_, u8>, value: ak::Span<'_, u8>, http_only: bool) {+ // SAFETY: ctx is the list below, and LibWeb lends the name and the value, which are UTF-8, for the call.+ unsafe { &mut *ctx.cast::<Vec<QueriedCookie>>() }.push(QueriedCookie {+ name: String::from_utf8_lossy(name.as_slice()).into_owned(),+ value: String::from_utf8_lossy(value.as_slice()).into_owned(),+ http_only,+ });+ }++ // 1. Perform the steps defined in Cookies § Retrieval Model to compute the "cookie-string from a given cookie store"+ // with url as request-uri. The cookie-string itself is ignored, but the intermediate cookie-list is used in subsequent steps.+ // For the purposes of the steps, the cookie-string is being generated for a "non-HTTP" API.+ let mut cookie_list: Vec<QueriedCookie> = Vec::new();+ let rust_url = RustUrl::from_url(url);+ // SAFETY: The settings object is live, and the URL and the list outlive the call.+ unsafe {+ web_cookie_store_request_all_cookies(+ environment.as_ptr(),+ &raw const rust_url,+ (&raw mut cookie_list).cast(),+ on_cookie,+ );+ }++ // 2. Let list be a new list.+ let mut list = Vec::new();++ // 3. For each cookie in cookie-list, run these steps:+ for cookie in &cookie_list {+ // 1. Assert: cookie’s http-only-flag is false.+ assert!(!cookie.http_only);++ // 2. If name is non-null:+ if let Some(name) = name {+ // 1. Normalize name.+ let normalized_name = normalize(name);++ // 2. Let cookieName be the result of running UTF-8 decode without BOM on cookie’s name.+ // 3. If cookieName does not equal name, then continue.+ if cookie.name != normalized_name {+ continue;+ }+ }++ // 3. Let item be the result of running create a CookieListItem from cookie.+ let item = create_a_cookie_list_item(&cookie.name, &cookie.value);++ // 4. Append item to list.+ list.push(item);+ }++ // 4. Return list.+ list+}++// https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-layered-cookies#name-cookie-default-path+fn cookie_default_path(mut path: Vec<&str>) -> Vec<&str> {+ // 1. Assert: path is a non-empty list.+ assert!(!path.is_empty());++ // 2. If path's size is greater than 1, then remove path's last item.+ if path.len() > 1 {+ path.pop();+ }+ // 3. Otherwise, set path[0] to the empty string.+ else {+ path[0] = "";+ }++ // 4. Return path.+ path+}++// https://fetch.spec.whatwg.org/#serialized-cookie-default-path+fn serialized_cookie_default_path(url: &Url) -> String {+ // 1. Let cloneURL be a clone of url.+ let mut clone_url = url.clone();++ // 2. Set cloneURL’s path to the cookie default path of cloneURL’s path.+ clone_url.set_path(cookie_default_path(url.path_segments().collect()));++ // 3. Return the URL path serialization of cloneURL.+ clone_url.serialize_path().to_owned()+}++const MAXIMUM_NAME_VALUE_PAIR_SIZE: usize = 4096;+const MAXIMUM_ATTRIBUTE_VALUE_SIZE: usize = 1024;++/// LibHTTP's MAXIMUM_COOKIE_AGE: 400 days.+const MAXIMUM_COOKIE_AGE_IN_MILLISECONDS: i64 = 400 * 24 * 60 * 60 * 1000;++fn unix_now_in_milliseconds() -> i64 {+ let since_epoch = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default();+ i64::try_from(since_epoch.as_millis()).unwrap_or(i64::MAX)+}++// https://cookiestore.spec.whatwg.org/#set-a-cookie+#[allow(clippy::too_many_arguments, reason = "the algorithm has these arguments")]+fn set_a_cookie(+ environment: &CppEnvironmentSettingsObject,+ url: &Url,+ name: &str,+ value: &str,+ expires: Option<f64>,+ domain: Option<&str>,+ path: &str,+ same_site: CookieSameSite,+ partitioned: bool,+) -> bool {+ // 1. Normalize name.+ let name = normalize(name);++ // 2. Normalize value.+ let value = normalize(value);++ // 3. If name or value contain U+003B (;), any C0 control character except U+0009 TAB, or U+007F DELETE, then return failure.+ let is_forbidden = |code_point: char| {+ code_point == ';' || (code_point <= '\u{1F}' && code_point != '\t') || code_point == '\u{7F}'+ };+ if name.contains(is_forbidden) || value.contains(is_forbidden) {+ return false;+ }++ // 4. If name contains U+003D (=), then return failure.+ if name.contains('=') {+ return false;+ }++ // 5. If name’s length is 0:+ if name.is_empty() {+ // 1. If value contains U+003D (=), then return failure.+ if value.contains('=') {+ return false;+ }++ // 2. If value’s length is 0, then return failure.+ if value.is_empty() {+ return false;+ }++ // 3. If value, byte-lowercased, starts with `__host-`, `__host-http-`, `__http-`, or `__secure-`, then return failure.+ let value_byte_lowercased = value.to_ascii_lowercase();+ if value_byte_lowercased.starts_with("__host-")+ || value_byte_lowercased.starts_with("__host-http-")+ || value_byte_lowercased.starts_with("__http-")+ || value_byte_lowercased.starts_with("__secure-")+ {+ return false;+ }+ }++ // 6. If name, byte-lowercased, starts with `__host-http-` or `__http-`, then return failure.+ let name_ascii_lowercased = name.to_ascii_lowercase();+ if name_ascii_lowercased.starts_with("__host-http-") || name_ascii_lowercased.starts_with("__http-") {+ return false;+ }++ // 7. Let encodedName be the result of UTF-8 encoding name.+ // 8. Let encodedValue be the result of UTF-8 encoding value.+ let encoded_name = name.as_bytes();+ let encoded_value = value.as_bytes();++ // 9. If the byte sequence length of encodedName plus the byte sequence length of encodedValue is greater than the+ // maximum name/value pair size, then return failure.+ if encoded_name.len() + encoded_value.len() > MAXIMUM_NAME_VALUE_PAIR_SIZE {+ return false;+ }++ // 10. Let host be url’s host+ let host = url.serialized_host().map(|serialization| Host {+ kind: url.host_kind(),+ serialization: serialization.to_owned(),+ });++ // 11. Let attributes be a new list.+ let mut encoded_domain = None;++ // 12. If domain is not null, then run these steps:+ if let Some(domain) = domain {+ // 1. If domain starts with U+002E (.), then return failure.+ if domain.starts_with('.') {+ return false;+ }++ // 2. If name, byte-lowercased, starts with `__host-`, then return failure.+ if name_ascii_lowercased.starts_with("__host-") {+ return false;+ }++ // 3. If domain is not a registrable domain suffix of and is not equal to host, then return failure.+ let Some(host) = &host else {+ return false;+ };+ if !is_a_registrable_domain_suffix_of_or_is_equal_to(&Utf16String::from_utf8(domain), host) {+ return false;+ }++ // 4. Let parsedDomain be the result of host parsing domain.+ let parsed_domain = parse_host(domain);++ // 5. Assert: parsedDomain is not failure.+ let parsed_domain = parsed_domain.expect("a registrable domain suffix of a host parses");++ // 6. Let encodedDomain be the result of UTF-8 encoding parsedDomain.+ let domain = parsed_domain.serialization;++ // 7. If the byte sequence length of encodedDomain is greater than the maximum attribute value size, then return failure.+ if domain.len() > MAXIMUM_ATTRIBUTE_VALUE_SIZE {+ return false;+ }++ // 8. Append `Domain`/encodedDomain to attributes.+ encoded_domain = Some(domain);+ }++ // 13. If expires is given, then append `Expires`/expires (date serialized) to attributes.+ let expiry_time = expires.map(|expires| {+ #[allow(+ clippy::cast_possible_truncation,+ reason = "a timestamp is milliseconds since the epoch"+ )]+ let mut expiry_time = expires as i64;++ // https://www.ietf.org/archive/id/draft-ietf-httpbis-rfc6265bis-15.html#section-5.6.1+ // 3. Let cookie-age-limit be the maximum age of the cookie (which SHOULD be 400 days in the future or sooner, see+ // Section 5.5).+ let cookie_age_limit = unix_now_in_milliseconds().saturating_add(MAXIMUM_COOKIE_AGE_IN_MILLISECONDS);++ // 4. If the expiry-time is more than cookie-age-limit, the user agent MUST set the expiry time to cookie-age-limit+ // in seconds.+ if expiry_time.div_euclid(1000) > cookie_age_limit.div_euclid(1000) {+ expiry_time = cookie_age_limit;+ }++ expiry_time+ });++ // 14. If path is the empty string, then set path to the serialized cookie default path of url.+ let path = if path.is_empty() {+ serialized_cookie_default_path(url)+ } else {+ path.to_owned()+ };++ // 15. If path does not start with U+002F (/), then return failure.+ if !path.starts_with('/') {+ return false;+ }++ // 16. If path is not U+002F (/), and name, byte-lowercased, starts with `__host-`, then return failure.+ if path != "/" && name_ascii_lowercased.starts_with("__host-") {+ return false;+ }++ // 17. Let encodedPath be the result of UTF-8 encoding path.+ let encoded_path = path.as_bytes();++ // 18. If the byte sequence length of encodedPath is greater than the maximum attribute value size, then return failure.+ if encoded_path.len() > MAXIMUM_ATTRIBUTE_VALUE_SIZE {+ return false;+ }++ // 19. Append `Path`/encodedPath to attributes.+ // 20. Append `Secure`/`` to attributes.+ let secure_attribute_present = true;++ // 21. Switch on sameSite:+ let same_site_attribute = match same_site {+ // -> "none"+ // Append `SameSite`/`None` to attributes.+ CookieSameSite::None => SAME_SITE_NONE,+ // -> "strict"+ // Append `SameSite`/`Strict` to attributes.+ CookieSameSite::Strict => SAME_SITE_STRICT,+ // -> "lax"+ // Append `SameSite`/`Lax` to attributes.+ CookieSameSite::Lax => SAME_SITE_LAX,+ };++ // FIXME: 22. If partitioned is true, Append `Partitioned`/`` to attributes.+ let _ = partitioned;++ // 23. Perform the steps defined in Cookies § Storage Model for when the user agent "receives a cookie" with url as+ // request-uri, encodedName as cookie-name, encodedValue as cookie-value, and attributes as cookie-attribute-list.+ // For the purposes of the steps, the newly-created cookie was received from a "non-HTTP" API.+ let attributes = ParsedCookieAbi {+ name: ak::Span::new(encoded_name),+ value: ak::Span::new(encoded_value),+ has_expiry_time: expiry_time.is_some(),+ expiry_time: expiry_time.unwrap_or_default(),+ has_domain: encoded_domain.is_some(),+ domain: ak::Span::new(encoded_domain.as_deref().unwrap_or_default().as_bytes()),+ path: ak::Span::new(encoded_path),+ secure_attribute_present,+ same_site_attribute,+ };+ let rust_url = RustUrl::from_url(url);+ // SAFETY: The settings object is live, and the URL and the attributes outlive the call.+ unsafe { web_cookie_store_set_cookie(environment.as_ptr(), &raw const rust_url, &raw const attributes) };++ // 24. Return success.+ true+}++// https://cookiestore.spec.whatwg.org/#delete-a-cookie+fn delete_a_cookie(+ environment: &CppEnvironmentSettingsObject,+ url: &Url,+ name: &str,+ domain: Option<&str>,+ path: &str,+ partitioned: bool,+) -> bool {+ // 1. Let expires be the earliest representable date represented as a timestamp.+ // NOTE: The exact value of expires is not important for the purposes of this algorithm, as long as it is in the past.+ #[allow(clippy::cast_precision_loss, reason = "-2^63 is exact as a double")]+ let expires = i64::MIN as f64;++ // 2. Normalize name.+ let name = normalize(name);++ // 3. Let value be the empty string.+ let mut value = "";++ // 4. If name’s length is 0, then set value to any non-empty implementation-defined string.+ if name.is_empty() {+ value = "ladybird";+ }++ // 5. Return the results of running set a cookie with url, name, value, expires, domain, path, "strict", and partitioned.+ set_a_cookie(+ environment,+ url,+ name,+ value,+ Some(expires),+ domain,+ path,+ CookieSameSite::Strict,+ partitioned,+ )+}++// https://cookiestore.spec.whatwg.org/#cookie-change+#[derive(Clone, Trace)]+#[gc(crate = libjs_rust)]+struct CookieChange {+ cookie: Cookie,+ #[gc(untraced)]+ r#type: CookieChangeType,+}++#[derive(Clone, Copy, PartialEq, Eq)]+enum CookieChangeType {+ Changed,+ Deleted,+}++// https://cookiestore.spec.whatwg.org/#observable-changes+fn observable_changes(changes: Vec<Cookie>) -> Vec<CookieChange> {+ // The observable changes for url are the set of cookie changes to cookies in a cookie store which meet the+ // requirements in step 1 of Cookies § Retrieval Algorithm’s steps to compute the "cookie-string from a given+ // cookie store" with url as request-uri, for a "non-HTTP" API.+ let now = unix_now_in_milliseconds();++ changes+ .into_iter()+ .map(|cookie| {+ // A cookie change is a cookie and a type (either changed or deleted):+ // - A cookie which is removed due to an insertion of another cookie with the same name, domain, and path is ignored.+ // - A newly-created cookie which is not immediately evicted is considered changed.+ // - A newly-created cookie which is immediately evicted is considered deleted.+ // - A cookie which is otherwise evicted or removed is considered deleted+ let r#type = if cookie.expiry_time_in_milliseconds < now {+ CookieChangeType::Deleted+ } else {+ CookieChangeType::Changed+ };+ CookieChange { cookie, r#type }+ })+ .collect()+}++// https://cookiestore.spec.whatwg.org/#prepare-lists+fn prepare_lists(changes: &[CookieChange]) -> (Vec<CookieListItem>, Vec<CookieListItem>) {+ // 1. Let changedList be a new list.+ let mut changed_list = Vec::new();++ // 2. Let deletedList be a new list.+ let mut deleted_list = Vec::new();++ // 3. For each change in changes, run these steps:+ for change in changes {+ // 1. Let item be the result of running create a CookieListItem from change’s cookie.+ let mut item = create_a_cookie_list_item(&change.cookie.name, &change.cookie.value);++ // 2. If change’s type is changed, then append item to changedList.+ if change.r#type == CookieChangeType::Changed {+ changed_list.push(item);+ }+ // 3. Otherwise, run these steps:+ else {+ // 1. Set item["value"] to undefined.+ item.value = None;++ // 2. Append item to deletedList.+ deleted_list.push(item);+ }+ }++ // 4. Return changedList and deletedList.+ (changed_list, deleted_list)+}++// https://cookiestore.spec.whatwg.org/#cookiestore+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct CookieStore {+ event_target: CppEventTarget,+ realm: Gc<Realm>,+}++impl Wrappable for CookieStore {+ 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 CookieStore {+ fn get_the_parent(&self) -> Option<CppEventTarget> {+ None+ }+}++impl CookieStore {+ pub(crate) fn create(vm: &Vm, realm: Gc<Realm>) -> Ref<Self> {+ let cookie_store = allocate(vm, |_| Self {+ event_target: CppEventTarget::new(),+ realm,+ });+ cookie_store.event_target.set_owner(cookie_store);+ cookie_store+ }++ fn request_cookie_list(+ &self,+ vm: &Vm,+ options: &CookieStoreGetOptions,+ empty_options_allowed: EmptyOptionsAllowed,+ first_item_only: FirstItemOnly,+ in_parallel: fn(&Vm, CookieListRequest),+ ) -> WebIdlPromise {+ let url = match validate_cookie_store_get_options(self.realm, options, empty_options_allowed) {+ Ok(url) => url,+ Err(exception) => return create_rejected_promise_from_exception(vm, self.realm, exception),+ };++ let promise = create_promise(vm, self.realm);+ in_parallel(+ vm,+ CookieListRequest {+ environment: relevant_settings_object(self.realm.global_object()),+ url,+ name: options.name.as_ref().map(UsvString::to_utf8),+ global: self.realm.global_object(),+ promise,+ first_item_only,+ },+ );+ promise+ }++ pub(crate) fn get_with_name(&self, cx: &mut CallContext, name: UsvString) -> WebIdlResult<WebIdlPromise> {+ let options = CookieStoreGetOptions {+ name: Some(name),+ url: None,+ };+ Ok(self.request_cookie_list(+ cx.vm(),+ &options,+ EmptyOptionsAllowed::No,+ FirstItemOnly::Yes,+ Self::get_in_parallel,+ ))+ }++ // https://cookiestore.spec.whatwg.org/#dom-cookiestore-get-options+ pub(crate) fn get(&self, cx: &mut CallContext, options: CookieStoreGetOptions) -> WebIdlResult<WebIdlPromise> {+ Ok(self.request_cookie_list(+ cx.vm(),+ &options,+ EmptyOptionsAllowed::No,+ FirstItemOnly::Yes,+ Self::get_in_parallel,+ ))+ }++ fn get_in_parallel(vm: &Vm, request: CookieListRequest) {+ // 8. Run the following steps in parallel:+ deferred_invoke(vm, request, |vm, request| {+ // 1. Let list be the results of running query cookies with url and options["name"] with default null.+ let list = query_cookies(&request.environment, &request.url, request.name.as_deref());+ complete_cookie_list_request(vm, request, list);+ });+ }++ pub(crate) fn get_all_with_name(&self, cx: &mut CallContext, name: UsvString) -> WebIdlResult<WebIdlPromise> {+ let options = CookieStoreGetOptions {+ name: Some(name),+ url: None,+ };+ Ok(self.request_cookie_list(+ cx.vm(),+ &options,+ EmptyOptionsAllowed::Yes,+ FirstItemOnly::No,+ Self::get_all_in_parallel,+ ))+ }++ // https://cookiestore.spec.whatwg.org/#dom-cookiestore-getall-options+ pub(crate) fn get_all(&self, cx: &mut CallContext, options: CookieStoreGetOptions) -> WebIdlResult<WebIdlPromise> {+ Ok(self.request_cookie_list(+ cx.vm(),+ &options,+ EmptyOptionsAllowed::Yes,+ FirstItemOnly::No,+ Self::get_all_in_parallel,+ ))+ }++ fn get_all_in_parallel(vm: &Vm, request: CookieListRequest) {+ // 7. Run the following steps in parallel:+ deferred_invoke(vm, request, |vm, request| {+ // 1. Let list be the results of running query cookies with url and options["name"] with default null.+ let list = query_cookies(&request.environment, &request.url, request.name.as_deref());+ complete_cookie_list_request(vm, request, list);+ });+ }++ fn request_cookie_mutation(&self, vm: &Vm, options: &CookieInit, failure_message: &'static str) -> WebIdlPromise {+ let url = match validate_cookie_store_mutation(self.realm) {+ Ok(url) => url,+ Err(exception) => return create_rejected_promise_from_exception(vm, self.realm, exception),+ };++ let promise = create_promise(vm, self.realm);+ let mutation = CookieMutation {+ environment: relevant_settings_object(self.realm.global_object()),+ url,+ name: options.name.to_utf8(),+ value: options.value.to_utf8(),+ expires: options.expires,+ domain: options.domain.as_ref().map(UsvString::to_utf8),+ path: options.path.to_utf8(),+ same_site: options.same_site,+ partitioned: options.partitioned,+ global: self.realm.global_object(),+ promise,+ failure_message,+ };++ // 6. Run the following steps in parallel:+ deferred_invoke(vm, mutation, |vm, mutation| {+ // 1. Let r be the result of running set a cookie with url, options["name"], options["value"], options["expires"],+ // options["domain"], options["path"], options["sameSite"], and options["partitioned"].+ let result = set_a_cookie(+ &mutation.environment,+ &mutation.url,+ &mutation.name,+ &mutation.value,+ mutation.expires,+ mutation.domain.as_deref(),+ &mutation.path,+ mutation.same_site,+ mutation.partitioned,+ );+ complete_cookie_mutation(vm, mutation.global, mutation.promise, mutation.failure_message, result);+ });+ promise+ }++ pub(crate) fn set_with_name_and_value(+ &self,+ cx: &mut CallContext,+ name: UsvString,+ value: UsvString,+ ) -> WebIdlResult<WebIdlPromise> {+ let options = CookieInit {+ name,+ value,+ expires: None,+ domain: None,+ path: UsvString::from_ascii(b"/"),+ same_site: CookieSameSite::Strict,+ partitioned: false,+ };+ Ok(self.request_cookie_mutation(cx.vm(), &options, "Name or value are malformed"))+ }++ // https://cookiestore.spec.whatwg.org/#dom-cookiestore-set-options+ pub(crate) fn set(&self, cx: &mut CallContext, options: CookieInit) -> WebIdlResult<WebIdlPromise> {+ Ok(self.request_cookie_mutation(cx.vm(), &options, "Name, value, domain or path are malformed"))+ }++ fn request_cookie_deletion(&self, vm: &Vm, options: &CookieStoreDeleteOptions) -> WebIdlPromise {+ let url = match validate_cookie_store_mutation(self.realm) {+ Ok(url) => url,+ Err(exception) => return create_rejected_promise_from_exception(vm, self.realm, exception),+ };++ let promise = create_promise(vm, self.realm);+ let deletion = CookieDeletion {+ environment: relevant_settings_object(self.realm.global_object()),+ url,+ name: options.name.to_utf8(),+ domain: options.domain.as_ref().map(UsvString::to_utf8),+ path: options.path.to_utf8(),+ partitioned: options.partitioned,+ global: self.realm.global_object(),+ promise,+ failure_message: "Name is malformed",+ };++ // 6. Run the following steps in parallel:+ deferred_invoke(vm, deletion, |vm, deletion| {+ // 1. Let r be the result of running delete a cookie with url, options["name"], options["domain"], options["path"],+ // and options["partitioned"].+ let result = delete_a_cookie(+ &deletion.environment,+ &deletion.url,+ &deletion.name,+ deletion.domain.as_deref(),+ &deletion.path,+ deletion.partitioned,+ );+ complete_cookie_mutation(vm, deletion.global, deletion.promise, deletion.failure_message, result);+ });+ promise+ }++ pub(crate) fn delete_with_name(&self, cx: &mut CallContext, name: UsvString) -> WebIdlResult<WebIdlPromise> {+ let options = CookieStoreDeleteOptions {+ name,+ domain: None,+ path: UsvString::from_ascii(b"/"),+ partitioned: true,+ };+ Ok(self.request_cookie_deletion(cx.vm(), &options))+ }++ // https://cookiestore.spec.whatwg.org/#dom-cookiestore-delete-options+ pub(crate) fn delete(+ &self,+ cx: &mut CallContext,+ options: CookieStoreDeleteOptions,+ ) -> WebIdlResult<WebIdlPromise> {+ Ok(self.request_cookie_deletion(cx.vm(), &options))+ }++ // https://cookiestore.spec.whatwg.org/#process-cookie-changes+ pub(crate) fn process_cookie_changes(this: Ref<Self>, vm: &Vm, all_changes: Vec<Cookie>) {+ // 1. Let url be window’s relevant settings object’s creation URL.+ // 2. Let changes be the observable changes for url.+ // 3. If changes is empty, then continue.+ // NB: We perform the URL-based filtering in the UI process so that we don't have to send all changed cookies over+ // IPC to every tab.+ let changes = observable_changes(all_changes);++ // 4. Queue a global task on the DOM manipulation task source given window to fire a change event named "change"+ // with changes at window’s CookieStore.+ queue_a_global_task(+ vm,+ this.realm.global_object(),+ TaskSource::DOMManipulation,+ (this, changes),+ |vm, (this, changes)| {+ with_temporary_execution_context(this.realm, || {+ // https://cookiestore.spec.whatwg.org/#fire-a-change-event+ // 4. Let changedList and deletedList be the result of running prepare lists from changes.+ let (changed_list, deleted_list) = prepare_lists(&changes);++ // 1. Let event be the result of creating an Event using CookieChangeEvent.+ // 2. Set event’s type attribute to type.+ // 3. Set event’s bubbles and cancelable attributes to false.+ // 5. Set event’s changed attribute to changedList.+ // 6. Set event’s deleted attribute to deletedList.+ let event_init = CookieChangeEventInit {+ parent: EventInit {+ bubbles: false,+ cancelable: false,+ composed: false,+ },+ changed: Some(changed_list),+ deleted: Some(deleted_list),+ };+ let event =+ CookieChangeEvent::create(vm, this.realm, &Utf16String::from_utf8("change"), event_init);++ // 7. Dispatch event at target.+ this.event_target.dispatch_event(event.event());+ });+ },+ );+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/cookie_store/exports.rs b/Libraries/LibWeb/Bindings/Rust/src/cookie_store/exports.rsnew file mode 100644index 00000000000..7fe5c8403a4--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/cookie_store/exports.rs@@ -0,0 +1,60 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The entry points through which LibWeb's C++ code creates a CookieStore and reports cookie changes to it, declared+//! in Libraries/LibWeb/CookieStore/CookieStore.cpp.++use core::ffi::c_void;++use libjs_rust::api::Vm;++use crate::bindings::interface::{cell_from_abi, cell_into_abi, realm_arguments};+use crate::cookie_store::cookie_store::{Cookie, CookieStore};++/// A changed cookie, with its name and value in UTF-8 and its expiry time in milliseconds since the epoch.+#[repr(C)]+pub struct CookieAbi<'a> {+ name: ak::Span<'a, u8>,+ value: ak::Span<'a, u8>,+ expiry_time: i64,+}++/// # Safety+///+/// The pointers must be the live VM and a live realm.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_cookie_store_create_cookie_store(vm: *mut c_void, realm: *mut c_void) -> *mut c_void {+ // SAFETY: The caller passes the live VM and a live realm.+ let (vm, realm) = unsafe { realm_arguments(vm, realm) };+ cell_into_abi(CookieStore::create(vm, realm))+}++/// https://cookiestore.spec.whatwg.org/#process-cookie-changes+///+/// # Safety+///+/// The pointers must be the live VM and the live cell of a CookieStore object.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_cookie_store_process_cookie_changes(+ vm: *mut c_void,+ cookie_store: *mut c_void,+ changes: ak::Span<'_, CookieAbi<'_>>,+) {+ // SAFETY: The caller passes the live VM.+ let vm = unsafe { &*vm.cast::<Vm>() };+ // SAFETY: The caller passes a live CookieStore object.+ let cookie_store = unsafe { cell_from_abi::<CookieStore>(cookie_store) };+ let changes = changes+ .as_slice()+ .iter()+ .map(|cookie| Cookie {+ name: String::from_utf8_lossy(cookie.name.as_slice()).into_owned(),+ value: String::from_utf8_lossy(cookie.value.as_slice()).into_owned(),+ expiry_time_in_milliseconds: cookie.expiry_time,+ })+ .collect();+ CookieStore::process_cookie_changes(cookie_store, vm, changes);+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/cookie_store/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/cookie_store/mod.rsnew file mode 100644index 00000000000..52eefec3fce--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/cookie_store/mod.rs@@ -0,0 +1,15 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The Cookie Store API, https://cookiestore.spec.whatwg.org/++pub(crate) mod cookie_change_event;+#[allow(+ clippy::module_inception,+ reason = "the module mirrors the CookieStore interface file"+)]+pub(crate) mod cookie_store;+pub(crate) mod exports;diff --git a/Libraries/LibWeb/Bindings/Rust/src/dom/document.rs b/Libraries/LibWeb/Bindings/Rust/src/dom/document.rsindex 87a36e9bd57..8c0f47c983c 100644--- a/Libraries/LibWeb/Bindings/Rust/src/dom/document.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/dom/document.rs@@ -6,9 +6,10 @@use core::ffi::c_void;+use ak::Utf16String;use libjs_rust::api::{Trace, Vm};-use liburl_rust::origin::Origin;-use liburl_rust::{FfiOrigin, Url};+use liburl_rust::origin::{Host, Origin};+use liburl_rust::{FfiOrigin, FfiUrlHost, Url};use crate::bindings::cpp_cell::{CppCell, WeakCppCell};use crate::bindings::interface::{Ref, cell_from_abi, cell_into_abi};@@ -18,6 +19,10 @@ use crate::navigation_timing::performance_navigation_timing::PerformanceNavigatiuse crate::permissions_policy::permissions_policy::PolicyControlledFeature;unsafe extern "C" {+ fn web_bindings_is_a_registrable_domain_suffix_of_or_is_equal_to(+ host_suffix_string: usize,+ original_host: *const FfiUrlHost,+ ) -> bool;fn web_bindings_document_navigable(document: *mut c_void) -> *mut c_void;fn web_bindings_document_is_fully_active(document: *mut c_void) -> bool;fn web_bindings_document_is_allowed_to_use_feature(document: *mut c_void, feature: u8) -> bool;@@ -183,3 +188,18 @@ impl CppDocument {unsafe { web_bindings_document_set_navigation_timing_entry(self.0.as_ptr(), cell_into_abi(entry)) };}}++/// https://html.spec.whatwg.org/multipage/browsers.html#is-a-registrable-domain-suffix-of-or-is-equal-to+pub(crate) fn is_a_registrable_domain_suffix_of_or_is_equal_to(+ host_suffix_string: &Utf16String,+ original_host: &Host,+) -> bool {+ let original_host = FfiUrlHost::new(original_host.kind, &original_host.serialization);+ // SAFETY: The host suffix string and the host are lent for the call.+ unsafe {+ web_bindings_is_a_registrable_domain_suffix_of_or_is_equal_to(+ host_suffix_string.raw_identity(),+ &raw const original_host,+ )+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/lib.rs b/Libraries/LibWeb/Bindings/Rust/src/lib.rsindex ac5ec004cc4..d01162466b2 100644--- a/Libraries/LibWeb/Bindings/Rust/src/lib.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/lib.rs@@ -74,6 +74,16 @@ pub(crate) mod compression;clippy::unnecessary_wraps,reason = "the bindings call every attribute and operation as one that can throw")]+pub(crate) mod cookie_store;+#[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 credential_management;#[cfg(not(test))]pub(crate) mod crypto;diff --git a/Libraries/LibWeb/Bindings/RustBindingsServices.cpp b/Libraries/LibWeb/Bindings/RustBindingsServices.cppindex 06918d1043c..6c23fdb20bb 100644--- a/Libraries/LibWeb/Bindings/RustBindingsServices.cpp+++ b/Libraries/LibWeb/Bindings/RustBindingsServices.cpp@@ -127,6 +127,7 @@ void web_bindings_document_load_timing_info(DOM::Document const*, DOM::DocumentLvoid web_bindings_document_previous_document_unload_timing(DOM::Document const*, DOM::DocumentUnloadTimingInfo*);NavigationTiming::PerformanceNavigationTiming* web_bindings_document_navigation_timing_entry(DOM::Document const*);void web_bindings_document_set_navigation_timing_entry(DOM::Document*, NavigationTiming::PerformanceNavigationTiming*);+bool web_bindings_is_a_registrable_domain_suffix_of_or_is_equal_to(FlatPtr host_suffix_string, URL::FFI::FfiUrlHost const* original_host);HTML::WorkerGlobalScope* web_bindings_worker_global_scope_from_global_object(JSObject* global_object);HTML::EnvironmentSettingsObject* web_bindings_relevant_settings_object(JSObject* global_object);HTML::EnvironmentSettingsObject* web_bindings_principal_realm_settings_object(void* realm);@@ -138,6 +139,7 @@ void web_bindings_environment_settings_object_id(HTML::EnvironmentSettingsObjectbool web_bindings_worker_global_scope_is_closing(HTML::WorkerGlobalScope*);void web_bindings_set_has_pending_activity(void* realm, DOM::EventTarget*, bool has_pending_activity);void web_bindings_environment_settings_object_origin(HTML::EnvironmentSettingsObject*, void* origin, void (*on_origin)(void*, URL::FFI::FfiOrigin const*));+void web_bindings_environment_settings_object_creation_url(HTML::EnvironmentSettingsObject*, void* url, void (*on_url)(void*, URL::FFI::RustUrl const*));bool web_bindings_environment_settings_object_top_level_origin(HTML::EnvironmentSettingsObject*, void* origin, void (*on_origin)(void*, URL::FFI::FfiOrigin const*));void web_bindings_environment_settings_object_api_base_url(HTML::EnvironmentSettingsObject*, void* url, void (*on_url)(void*, URL::FFI::RustUrl const*));double web_bindings_environment_settings_object_current_wall_time(HTML::EnvironmentSettingsObject*);@@ -331,6 +333,11 @@ void web_bindings_document_set_navigation_timing_entry(DOM::Document* document,document->set_navigation_timing_entry(*entry);}+bool web_bindings_is_a_registrable_domain_suffix_of_or_is_equal_to(FlatPtr host_suffix_string, URL::FFI::FfiUrlHost const* original_host)+{+ return DOM::is_a_registrable_domain_suffix_of_or_is_equal_to(Utf16String::from_raw(host_suffix_string), URL::RustIntegration::host_from_ffi(*original_host).value());+}+HTML::EnvironmentSettingsObject* web_bindings_relevant_settings_object(JSObject* global_object){return &HTML::relevant_settings_object(*JS::HostABI::object_from_abi(global_object));@@ -383,6 +390,12 @@ void web_bindings_environment_settings_object_origin(HTML::EnvironmentSettingsOb});}+void web_bindings_environment_settings_object_creation_url(HTML::EnvironmentSettingsObject* settings_object, void* url, void (*on_url)(void*, URL::FFI::RustUrl const*))+{+ auto rust_url = settings_object->creation_url.to_rust();+ on_url(url, &rust_url);+}+bool web_bindings_environment_settings_object_top_level_origin(HTML::EnvironmentSettingsObject* settings_object, void* origin, void (*on_origin)(void*, URL::FFI::FfiOrigin const*)){if (!settings_object->top_level_origin.has_value())diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txtindex 513de48dec2..ad58aad81d9 100644--- a/Libraries/LibWeb/CMakeLists.txt+++ b/Libraries/LibWeb/CMakeLists.txt@@ -54,7 +54,6 @@ set(SOURCESContentSecurityPolicy/PolicyList.cppContentSecurityPolicy/SecurityPolicyViolationEvent.cppContentSecurityPolicy/Violation.cpp- CookieStore/CookieChangeEvent.cppCookieStore/CookieStore.cppCredentialManagement/CredentialsContainer.cppCrypto/Crypto.cppdiff --git a/Libraries/LibWeb/CookieStore/BindingsGlue.h b/Libraries/LibWeb/CookieStore/BindingsGlue.hdeleted file mode 100644index 96fa7ac59c7..00000000000--- a/Libraries/LibWeb/CookieStore/BindingsGlue.h+++ /dev/null@@ -1,28 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <LibGC/Forward.h>-#include <LibJS/Forward.h>-#include <LibWeb/Export.h>--namespace Web::CookieStore {--class CookieChangeEvent;--}--namespace Web::Bindings {--class WrapperWorld;--WEB_API GC::Ptr<JS::Object> cached_changed(CookieStore::CookieChangeEvent const&, WrapperWorld const&);-WEB_API void set_cached_changed(CookieStore::CookieChangeEvent const&, WrapperWorld const&, GC::Ptr<JS::Object>);-WEB_API GC::Ptr<JS::Object> cached_deleted(CookieStore::CookieChangeEvent const&, WrapperWorld const&);-WEB_API void set_cached_deleted(CookieStore::CookieChangeEvent const&, WrapperWorld const&, GC::Ptr<JS::Object>);--}diff --git a/Libraries/LibWeb/CookieStore/CookieChangeEvent.cpp b/Libraries/LibWeb/CookieStore/CookieChangeEvent.cppdeleted file mode 100644index a40d2433e36..00000000000--- a/Libraries/LibWeb/CookieStore/CookieChangeEvent.cpp+++ /dev/null@@ -1,88 +0,0 @@-/*- * Copyright (c) 2025, Idan Horowitz <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <AK/NeverDestroyed.h>-#include <LibGC/Heap.h>-#include <LibWeb/Bindings/WrapperWorld.h>-#include <LibWeb/CookieStore/BindingsGlue.h>-#include <LibWeb/CookieStore/CookieChangeEvent.h>--namespace Web::CookieStore {--GC_DEFINE_ALLOCATOR(CookieChangeEvent);--GC::Ref<CookieChangeEvent> CookieChangeEvent::create(Utf16FlyString const& event_name, CookieChangeEventInit const& event_init, HighResolutionTime::DOMHighResTimeStamp time_stamp)-{- return GC::Heap::the().allocate<CookieChangeEvent>(event_name, event_init, time_stamp);-}--CookieChangeEvent::CookieChangeEvent(Utf16FlyString const& event_name, CookieChangeEventInit const& event_init, HighResolutionTime::DOMHighResTimeStamp time_stamp)- : DOM::Event(FlyString { event_name.view().to_utf8_but_should_be_ported_to_utf16() }, event_init, time_stamp)- , m_changed(event_init.changed.value_or({}))- , m_deleted(event_init.deleted.value_or({}))-{-}--CookieChangeEvent::~CookieChangeEvent() = default;--}--namespace Web::Bindings {--struct CookieChangeEventCacheEntry {- GC::Weak<CookieStore::CookieChangeEvent const> event;- WrapperWorldWeakValueCache<JS::Object> changed_arrays;- WrapperWorldWeakValueCache<JS::Object> deleted_arrays;-};--static Vector<CookieChangeEventCacheEntry>& cookie_change_event_caches()-{- static NeverDestroyed<Vector<CookieChangeEventCacheEntry>> caches;- return *caches;-}--static void prune_cookie_change_event_caches()-{- cookie_change_event_caches().remove_all_matching([](auto const& entry) {- return !entry.event;- });-}--static CookieChangeEventCacheEntry& cookie_change_event_cache_for(CookieStore::CookieChangeEvent const& event)-{- auto& caches = cookie_change_event_caches();- prune_cookie_change_event_caches();-- for (auto& entry : caches) {- if (entry.event.ptr().ptr() == &event)- return entry;- }-- caches.append(CookieChangeEventCacheEntry { event, {}, {} });- return caches.last();-}--GC::Ptr<JS::Object> cached_changed(CookieStore::CookieChangeEvent const& event, WrapperWorld const& wrapper_world)-{- return cookie_change_event_cache_for(event).changed_arrays.get(wrapper_world);-}--void set_cached_changed(CookieStore::CookieChangeEvent const& event, WrapperWorld const& wrapper_world, GC::Ptr<JS::Object> array)-{- cookie_change_event_cache_for(event).changed_arrays.set(wrapper_world, array);-}--GC::Ptr<JS::Object> cached_deleted(CookieStore::CookieChangeEvent const& event, WrapperWorld const& wrapper_world)-{- return cookie_change_event_cache_for(event).deleted_arrays.get(wrapper_world);-}--void set_cached_deleted(CookieStore::CookieChangeEvent const& event, WrapperWorld const& wrapper_world, GC::Ptr<JS::Object> array)-{- cookie_change_event_cache_for(event).deleted_arrays.set(wrapper_world, array);-}--}diff --git a/Libraries/LibWeb/CookieStore/CookieChangeEvent.h b/Libraries/LibWeb/CookieStore/CookieChangeEvent.hdeleted file mode 100644index ac85252b311..00000000000--- a/Libraries/LibWeb/CookieStore/CookieChangeEvent.h+++ /dev/null@@ -1,48 +0,0 @@-/*- * Copyright (c) 2025, Idan Horowitz <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/Utf16FlyString.h>-#include <AK/Vector.h>-#include <LibJS/Forward.h>-#include <LibWeb/Bindings/CookieChangeEvent.h>-#include <LibWeb/Bindings/CookieStore.h>-#include <LibWeb/DOM/Event.h>-#include <LibWebCommon/HighResolutionTime/DOMHighResTimeStamp.h>--namespace Web::HTML {--class Window;--}--namespace Web::CookieStore {--using CookieListItem = Bindings::CookieListItem;-using CookieChangeEventInit = Bindings::CookieChangeEventInit;--// https://cookiestore.spec.whatwg.org/#cookiechangeevent-class CookieChangeEvent final : public DOM::Event {- WEB_WRAPPABLE(CookieChangeEvent, DOM::Event);- GC_DECLARE_ALLOCATOR(CookieChangeEvent);--public:- [[nodiscard]] static GC::Ref<CookieChangeEvent> create(Utf16FlyString const& event_name, CookieChangeEventInit const& event_init, HighResolutionTime::DOMHighResTimeStamp);-- virtual ~CookieChangeEvent() override;-- Vector<CookieListItem> changed() const { return m_changed; }- Vector<CookieListItem> deleted() const { return m_deleted; }--private:- CookieChangeEvent(Utf16FlyString const& event_name, CookieChangeEventInit const& event_init, HighResolutionTime::DOMHighResTimeStamp);-- Vector<CookieListItem> m_changed;- Vector<CookieListItem> m_deleted;-};--}diff --git a/Libraries/LibWeb/CookieStore/CookieChangeEvent.idl b/Libraries/LibWeb/CookieStore/CookieChangeEvent.idlindex 9680fbbec4d..0de64fde353 100644--- a/Libraries/LibWeb/CookieStore/CookieChangeEvent.idl+++ b/Libraries/LibWeb/CookieStore/CookieChangeEvent.idl@@ -4,9 +4,9 @@ dictionary CookieChangeEventInit : EventInit {};// https://cookiestore.spec.whatwg.org/#cookiechangeevent-[Exposed=Window, SecureContext]+[Exposed=Window, SecureContext, ImplementedIn=Rust]interface CookieChangeEvent : Event {constructor(DOMString type, optional CookieChangeEventInit eventInitDict = {});- [SameObject, CachedAttribute] readonly attribute FrozenArray<CookieListItem> changed;- [SameObject, CachedAttribute] readonly attribute FrozenArray<CookieListItem> deleted;+ [SameObject, CachedAccessor] readonly attribute FrozenArray<CookieListItem> changed;+ [SameObject, CachedAccessor] readonly attribute FrozenArray<CookieListItem> deleted;};diff --git a/Libraries/LibWeb/CookieStore/CookieStore.cpp b/Libraries/LibWeb/CookieStore/CookieStore.cppindex 2c5c2cfb63a..4646f84ec78 100644--- a/Libraries/LibWeb/CookieStore/CookieStore.cpp+++ b/Libraries/LibWeb/CookieStore/CookieStore.cpp@@ -1,775 +1,101 @@/** Copyright (c) 2025, Idan Horowitz <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.** SPDX-License-Identifier: BSD-2-Clause*/-#include <LibGC/Heap.h>#include <LibHTTP/Cookie/Cookie.h>#include <LibHTTP/Cookie/ParsedCookie.h>-#include <LibJS/Runtime/Array.h>-#include <LibJS/Runtime/Error.h>-#include <LibURL/Parser.h>-#include <LibWeb/Bindings/CookieStore.h>-#include <LibWeb/CookieStore/CookieChangeEvent.h>+#include <LibJS/HostClassBuilder.h>+#include <LibJS/Runtime/Realm.h>+#include <LibURL/URL.h>#include <LibWeb/CookieStore/CookieStore.h>-#include <LibWeb/DOM/Document.h>-#include <LibWeb/HTML/EventLoop/EventLoop.h>-#include <LibWeb/HTML/EventLoop/Task.h>#include <LibWeb/HTML/Scripting/Environments.h>-#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>#include <LibWeb/HTML/Window.h>-#include <LibWeb/HighResolutionTime/TimeOrigin.h>+#include <LibWeb/HTML/WorkerGlobalScope.h>#include <LibWeb/Page/Page.h>-#include <LibWeb/Platform/EventLoopPlugin.h>-#include <LibWeb/WebIDL/DOMException.h>-#include <LibWeb/WebIDL/Promise.h>+#include <LibWeb/ServiceWorker/ServiceWorkerGlobalScope.h>namespace Web::CookieStore {-GC_DEFINE_ALLOCATOR(CookieStore);--static HTTP::Cookie::SameSite same_site_from_bindings(Bindings::CookieSameSite same_site)-{- switch (same_site) {- case Bindings::CookieSameSite::Strict:- return HTTP::Cookie::SameSite::Strict;- case Bindings::CookieSameSite::Lax:- return HTTP::Cookie::SameSite::Lax;- case Bindings::CookieSameSite::None:- return HTTP::Cookie::SameSite::None;- }- VERIFY_NOT_REACHED();-}--enum class EmptyOptionsAllowed {- No,- Yes,+struct CookieABI {+ ReadonlyBytes name;+ ReadonlyBytes value;+ i64 expiry_time;};-enum class FirstItemOnly {- No,- Yes,+struct ParsedCookieABI {+ ReadonlyBytes name;+ ReadonlyBytes value;+ bool has_expiry_time;+ i64 expiry_time;+ bool has_domain;+ ReadonlyBytes domain;+ ReadonlyBytes path;+ bool secure_attribute_present;+ HTTP::Cookie::SameSite same_site_attribute;};-static JS::Value cookie_store_cookie_list_item_to_value(JS::Realm& realm, CookieListItem const& item)-{- return Bindings::cookie_list_item_to_value(realm, item);-}--static void resolve_cookie_list_item_or_null_promise(JS::Realm& realm, WebIDL::Promise& promise, Vector<CookieListItem> const& cookie_list)-{- if (cookie_list.is_empty()) {- WebIDL::resolve_promise(promise, JS::js_null());- return;- }-- WebIDL::resolve_promise(promise, cookie_store_cookie_list_item_to_value(realm, cookie_list[0]));-}--static void resolve_cookie_list_promise(JS::Realm& realm, WebIDL::Promise& promise, Vector<CookieListItem> const& cookie_list)-{- auto result = JS::Array::create_from<CookieListItem>(realm, cookie_list, [&](auto const& cookie) {- return cookie_store_cookie_list_item_to_value(realm, cookie);- });- WebIDL::resolve_promise(promise, result);-}--static Optional<URL::URL> validate_cookie_store_get_options(WebIDL::Promise& promise, CookieStoreGetOptions const& options, EmptyOptionsAllowed empty_options_allowed)-{- auto& realm = WebIDL::promise_realm(promise);-- // 1. Let settings be this's relevant settings object.- auto const& settings = HTML::principal_realm_settings_object(realm);-- // 2. Let origin be settings's origin.- auto const& origin = settings.origin();-- // 3. If origin is an opaque origin, then return a promise rejected with a "SecurityError" DOMException.- if (origin.is_opaque()) {- WebIDL::reject_promise(promise, WebIDL::SecurityError::create(realm, "Document origin is opaque"_utf16));- return {};- }-- // 4. Let url be settings's creation URL.- auto url = settings.creation_url;-- // 5. If options is empty, then return a promise rejected with a TypeError.- if (empty_options_allowed == EmptyOptionsAllowed::No && !options.name.has_value() && !options.url.has_value()) {- WebIDL::reject_promise(promise, JS::TypeError::create(realm, "CookieStoreGetOptions is empty"sv));- return {};- }-- // 6. If options["url"] is present, then run these steps:- if (options.url.has_value()) {- // 1. Let parsed be the result of parsing options["url"] with settings's API base URL.- auto parsed = URL::Parser::basic_parse(options.url.value(), settings.api_base_url());-- // AD-HOC: This isn't explicitly mentioned in the specification, but we have to reject invalid URLs as well- if (!parsed.has_value()) {- WebIDL::reject_promise(promise, JS::TypeError::create(realm, "url is invalid"sv));- return {};- }-- // 2. If this's relevant global object is a Window object and parsed does not equal url with exclude fragments- // set to true, then return a promise rejected with a TypeError.- if (HTML::window_from_global_object(settings.global_object()) && !parsed->equals(url, URL::ExcludeFragment::Yes)) {- WebIDL::reject_promise(promise, JS::TypeError::create(realm, "url does not match creation URL"sv));- return {};- }+extern "C" {+// Defined in Bindings/Rust/src/cookie_store/exports.rs.+void* web_rust_cookie_store_create_cookie_store(JSVM*, void* realm);+void web_rust_cookie_store_process_cookie_changes(JSVM*, CookieStore*, ReadonlySpan<CookieABI>);- // 3. If parsed's origin and url's origin are not the same origin, then return a promise rejected with a TypeError.- if (parsed->origin() != url.origin()) {- WebIDL::reject_promise(promise, JS::TypeError::create(realm, "url's origin does not match creation URL's origin"sv));- return {};- }-- // 4. Set url to parsed.- url = parsed.value();- }-- return url;-}--static Optional<URL::URL> validate_cookie_store_mutation(WebIDL::Promise& promise)-{- auto& realm = WebIDL::promise_realm(promise);-- // 1. Let settings be this's relevant settings object.- auto const& settings = HTML::principal_realm_settings_object(realm);-- // 2. Let origin be settings's origin.- auto const& origin = settings.origin();-- // 3. If origin is an opaque origin, then return a promise rejected with a "SecurityError" DOMException.- if (origin.is_opaque()) {- WebIDL::reject_promise(promise, WebIDL::SecurityError::create(realm, "Document origin is opaque"_utf16));- return {};- }-- // 4. Let url be settings's creation URL.- return settings.creation_url;+// Called by Bindings/Rust/src/cookie_store/cookie_store.rs.+void web_cookie_store_request_all_cookies(HTML::EnvironmentSettingsObject*, URL::FFI::RustUrl const*, void* ctx, void (*on_cookie)(void*, ReadonlyBytes name, ReadonlyBytes value, bool http_only));+void web_cookie_store_set_cookie(HTML::EnvironmentSettingsObject*, URL::FFI::RustUrl const*, ParsedCookieABI const*);}-static GC::Ref<CookieListCompletionSteps> create_cookie_list_completion_steps(JS::Object& global, GC::Ref<WebIDL::Promise> promise, FirstItemOnly first_item_only)+GC::Ref<CookieStore> CookieStore::create(JS::Realm& realm){- return GC::create_function(GC::Heap::the(), GC::captures(global, promise, first_item_only), [](auto& global, auto& promise, auto& first_item_only, Vector<CookieListItem> cookie_list) {- // AD-HOC: Queue a global task to perform the next steps- // Spec issue: https://github.com/whatwg/cookiestore/issues/239- HTML::queue_global_task(HTML::Task::Source::Unspecified, global, GC::create_function(GC::Heap::the(), GC::captures(promise, move(cookie_list), first_item_only), [](auto& promise, auto& cookie_list, auto& first_item_only) {- auto& realm = WebIDL::promise_realm(promise);- HTML::TemporaryExecutionContext execution_context { realm };- if (first_item_only == FirstItemOnly::Yes)- resolve_cookie_list_item_or_null_promise(realm, promise, cookie_list);- else- resolve_cookie_list_promise(realm, promise, cookie_list);- }));- });+ return *static_cast<CookieStore*>(web_rust_cookie_store_create_cookie_store(JS::HostABI::vm_to_abi(realm.vm()), &realm));}-static GC::Ref<CookieMutationCompletionSteps> create_cookie_mutation_completion_steps(JS::Object& global, GC::Ref<WebIDL::Promise> promise, Utf16String failure_message)+void CookieStore::process_cookie_changes(Vector<HTTP::Cookie::Cookie> const& cookies){- return GC::create_function(GC::Heap::the(), GC::captures(global, promise, move(failure_message)), [](auto& global, auto& promise, auto& failure_message, bool result) {- // NB: The UI's notification of this mutation's cookie changes is handled from a deferred invocation scheduled while- // waiting for its reply. Queue the task below after that, so the change event is fired first.- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(global, promise, result, failure_message), [](auto& global, auto& promise, auto& result, auto& failure_message) {- // AD-HOC: Queue a global task to perform the next steps- // Spec issue: https://github.com/whatwg/cookiestore/issues/239- HTML::queue_global_task(HTML::Task::Source::Unspecified, global, GC::create_function(GC::Heap::the(), GC::captures(promise, result, failure_message), [](auto& promise, auto& result, auto& failure_message) {- auto& realm = WebIDL::promise_realm(promise);- HTML::TemporaryExecutionContext execution_context { realm };- if (!result)- return WebIDL::reject_promise(promise, JS::TypeError::create(realm, failure_message));+ Vector<CookieABI> changes;+ changes.ensure_capacity(cookies.size());+ for (auto const& cookie : cookies)+ changes.unchecked_append({ cookie.name.bytes(), cookie.value.bytes(), cookie.expiry_time.milliseconds_since_epoch() });- WebIDL::resolve_promise(promise);- }));- }));- });+ web_rust_cookie_store_process_cookie_changes(JS::HostABI::vm_to_abi(JS::VM::the()), this, changes);}-CookieStore::CookieStore(PageClient& client)- : DOM::EventTarget()- , m_client(client)+static PageClient& page_client(HTML::EnvironmentSettingsObject& settings_object){+ auto& global_object = settings_object.global_object();+ if (auto* window = HTML::window_from_global_object(global_object))+ return window->page().client();+ return Bindings::service_worker_global_scope_from_global_object(global_object)->page()->client();}-void CookieStore::visit_edges(Cell::Visitor& visitor)+void web_cookie_store_request_all_cookies(HTML::EnvironmentSettingsObject* settings_object, URL::FFI::RustUrl const* rust_url, void* ctx, void (*on_cookie)(void*, ReadonlyBytes name, ReadonlyBytes value, bool http_only)){- Base::visit_edges(visitor);+ URL::URL url;+ url.set_from_rust(*rust_url);- visitor.visit(m_client);-}--// https://cookiestore.spec.whatwg.org/#create-a-cookielistitem-static CookieListItem create_a_cookie_list_item(HTTP::Cookie::Cookie const& cookie)-{- // 1. Let name be the result of running UTF-8 decode without BOM on cookie’s name.- // 2. Let value be the result of running UTF-8 decode without BOM on cookie’s value.- // 3. Return «[ "name" → name, "value" → value ]»- return CookieListItem {- .name = Utf16String::from_utf8(cookie.name),- .value = Utf16String::from_utf8(cookie.value),- };+ for (auto const& cookie : page_client(*settings_object).page_did_request_all_cookies_cookiestore(settings_object->id, url))+ on_cookie(ctx, cookie.name.bytes(), cookie.value.bytes(), cookie.http_only);}-// https://cookiestore.spec.whatwg.org/#normalize-a-cookie-name-or-value-static Utf16String normalize(Utf16String const& input)+void web_cookie_store_set_cookie(HTML::EnvironmentSettingsObject* settings_object, URL::FFI::RustUrl const* rust_url, ParsedCookieABI const* cookie){- // Remove all U+0009 TAB and U+0020 SPACE that are at the start or end of input.- return input.trim("\t "sv);-}--// https://cookiestore.spec.whatwg.org/#query-cookies-Vector<CookieListItem> CookieStore::query_cookies(HTML::EnvironmentId const& environment_id, URL::URL const& url, Optional<Utf16String> const& name)-{- // 1. Perform the steps defined in Cookies § Retrieval Model to compute the "cookie-string from a given cookie store"- // with url as request-uri. The cookie-string itself is ignored, but the intermediate cookie-list is used in subsequent steps.- // For the purposes of the steps, the cookie-string is being generated for a "non-HTTP" API.- auto cookie_list = m_client->page_did_request_all_cookies_cookiestore(environment_id, url);-- // 2. Let list be a new list.- Vector<CookieListItem> list;-- // 3. For each cookie in cookie-list, run these steps:- for (auto const& cookie : cookie_list) {- // 1. Assert: cookie’s http-only-flag is false.- VERIFY(!cookie.http_only);-- // 2. If name is non-null:- if (name.has_value()) {- // 1. Normalize name.- auto normalized_name = normalize(name.value());- auto encoded_name = normalized_name.to_utf8();-- // 2. Let cookieName be the result of running UTF-8 decode without BOM on cookie’s name.- // 3. If cookieName does not equal name, then continue.- if (cookie.name != encoded_name)- continue;- }- // 3. Let item be the result of running create a CookieListItem from cookie.- auto item = create_a_cookie_list_item(cookie);-- // 4. Append item to list.- list.append(move(item));- }-- // 4. Return list.- return list;-}--GC::Ref<WebIDL::Promise> CookieStore::get(JS::Realm& realm, CookieStoreGetOptions const& options)-{- auto promise = WebIDL::create_promise(realm);- auto cookie_store_options = options;- auto url = validate_cookie_store_get_options(promise, cookie_store_options, EmptyOptionsAllowed::No);- if (!url.has_value())- return promise;-- get(HTML::principal_realm_settings_object(realm).id, url.release_value(), move(cookie_store_options.name), create_cookie_list_completion_steps(realm.global_object(), promise, FirstItemOnly::Yes));- return promise;-}--GC::Ref<WebIDL::Promise> CookieStore::get(JS::Realm& realm, Utf16String name)-{- CookieStoreGetOptions options {- .name = move(name),- .url = {},- };- auto promise = WebIDL::create_promise(realm);- auto url = validate_cookie_store_get_options(promise, options, EmptyOptionsAllowed::No);- if (!url.has_value())- return promise;-- get(HTML::principal_realm_settings_object(realm).id, url.release_value(), move(options.name), create_cookie_list_completion_steps(realm.global_object(), promise, FirstItemOnly::Yes));- return promise;-}--// https://cookiestore.spec.whatwg.org/#dom-cookiestore-get-options-void CookieStore::get(HTML::EnvironmentId environment_id, URL::URL url, Optional<Utf16String> name, GC::Ref<CookieListCompletionSteps> completion_steps)-{- // 8. Run the following steps in parallel:- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(*this, completion_steps, environment_id, move(url), move(name)), [](auto& self, auto& completion_steps, auto& environment_id, auto& url, auto& name) {- // 1. Let list be the results of running query cookies with url and options["name"] with default null.- auto list = self.query_cookies(environment_id, url, name);- completion_steps->function()(move(list));- }));-}--GC::Ref<WebIDL::Promise> CookieStore::get_all(JS::Realm& realm, CookieStoreGetOptions const& options)-{- auto promise = WebIDL::create_promise(realm);- auto cookie_store_options = options;- auto url = validate_cookie_store_get_options(promise, cookie_store_options, EmptyOptionsAllowed::Yes);- if (!url.has_value())- return promise;-- get_all(HTML::principal_realm_settings_object(realm).id, url.release_value(), move(cookie_store_options.name), create_cookie_list_completion_steps(realm.global_object(), promise, FirstItemOnly::No));- return promise;-}--GC::Ref<WebIDL::Promise> CookieStore::get_all(JS::Realm& realm, Utf16String name)-{- CookieStoreGetOptions options {- .name = move(name),- .url = {},- };- auto promise = WebIDL::create_promise(realm);- auto url = validate_cookie_store_get_options(promise, options, EmptyOptionsAllowed::Yes);- if (!url.has_value())- return promise;-- get_all(HTML::principal_realm_settings_object(realm).id, url.release_value(), move(options.name), create_cookie_list_completion_steps(realm.global_object(), promise, FirstItemOnly::No));- return promise;-}--// https://cookiestore.spec.whatwg.org/#dom-cookiestore-getall-options-void CookieStore::get_all(HTML::EnvironmentId environment_id, URL::URL url, Optional<Utf16String> name, GC::Ref<CookieListCompletionSteps> completion_steps)-{- // 7. Run the following steps in parallel:- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(*this, completion_steps, environment_id, move(url), move(name)), [](auto& self, auto& completion_steps, auto& environment_id, auto& url, auto& name) {- // 1. Let list be the results of running query cookies with url and options["name"] with default null.- auto list = self.query_cookies(environment_id, url, name);- completion_steps->function()(move(list));- }));-}--// https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-layered-cookies#name-cookie-default-path-static Vector<StringView> cookie_default_path(Vector<StringView> path)-{- // 1. Assert: path is a non-empty list.- VERIFY(!path.is_empty());-- // 2. If path's size is greater than 1, then remove path's last item.- if (path.size() > 1)- path.take_last();-- // 3. Otherwise, set path[0] to the empty string.- else- path[0] = ""sv;-- // 4. Return path.- return path;-}--// https://fetch.spec.whatwg.org/#serialized-cookie-default-path-static String serialized_cookie_default_path(URL::URL const& url)-{- // 1. Let cloneURL be a clone of url.- auto clone_url = url;-- // 2. Set cloneURL’s path to the cookie default path of cloneURL’s path.- Vector<StringView> path;- for (auto segment : url.path_segments())- path.append(segment);- clone_url.set_path(cookie_default_path(move(path)));-- // 3. Return the URL path serialization of cloneURL.- return MUST(String::from_utf8(clone_url.serialize_path()));-}--static constexpr size_t maximum_name_value_pair_size = 4096;-static constexpr size_t maximum_attribute_value_size = 1024;--// https://cookiestore.spec.whatwg.org/#set-a-cookie-bool CookieStore::set_a_cookie(HTML::EnvironmentId const& environment_id, URL::URL const& url, Utf16String name, Utf16String value, Optional<HighResolutionTime::DOMHighResTimeStamp> expires, Optional<Utf16String> const& domain, Utf16String path, HTTP::Cookie::SameSite same_site, bool partitioned)-{- // 1. Normalize name.- name = normalize(name);-- // 2. Normalize value.- value = normalize(value);-- // 3. If name or value contain U+003B (;), any C0 control character except U+0009 TAB, or U+007F DELETE, then return failure.- if (name.utf16_view().contains(';') || value.utf16_view().contains(';'))- return false;- for (auto c = '\x00'; c <= '\x1F'; ++c) {- if (c == '\t')- continue;- if (name.utf16_view().contains(c) || value.utf16_view().contains(c))- return false;- }- if (name.utf16_view().contains('\x7F') || value.utf16_view().contains('\x7F'))- return false;-- // 4. If name contains U+003D (=), then return failure.- if (name.utf16_view().contains('='))- return false;-- // 5. If name’s length is 0:- if (name.is_empty()) {- // 1. If value contains U+003D (=), then return failure.- if (value.utf16_view().contains('='))- return false;-- // 2. If value’s length is 0, then return failure.- if (value.is_empty())- return false;-- // 3. If value, byte-lowercased, starts with `__host-`, `__host-http-`, `__http-`, or `__secure-`, then return failure.- auto value_byte_lowercased = value.to_ascii_lowercase();- if (value_byte_lowercased.utf16_view().starts_with("__host-"sv) || value_byte_lowercased.utf16_view().starts_with("__host-http-"sv) || value_byte_lowercased.utf16_view().starts_with("__http-"sv) || value_byte_lowercased.utf16_view().starts_with("__secure-"sv))- return false;- }-- // 6. If name, byte-lowercased, starts with `__host-http-` or `__http-`, then return failure.- auto name_ascii_lowercased = name.to_ascii_lowercase();- if (name_ascii_lowercased.utf16_view().starts_with("__host-http-"sv) || name_ascii_lowercased.utf16_view().starts_with("__http-"sv))- return false;-- // 7. Let encodedName be the result of UTF-8 encoding name.- // 8. Let encodedValue be the result of UTF-8 encoding value.- auto encoded_name = name.to_utf8();- auto encoded_value = value.to_utf8();-- // 9. If the byte sequence length of encodedName plus the byte sequence length of encodedValue is greater than the- // maximum name/value pair size, then return failure.- if (encoded_name.byte_count() + encoded_value.byte_count() > maximum_name_value_pair_size)- return false;-- // 10. Let host be url’s host- auto const& host = url.host();+ URL::URL url;+ url.set_from_rust(*rust_url);- // 11. Let attributes be a new list.HTTP::Cookie::ParsedCookie parsed_cookie {};- parsed_cookie.name = move(encoded_name);- parsed_cookie.value = move(encoded_value);-- // 12. If domain is not null, then run these steps:- if (domain.has_value()) {- // 1. If domain starts with U+002E (.), then return failure.- if (domain->starts_with('.'))- return false;-- // 2. If name, byte-lowercased, starts with `__host-`, then return failure.- if (name_ascii_lowercased.utf16_view().starts_with("__host-"sv))- return false;-- // 3. If domain is not a registrable domain suffix of and is not equal to host, then return failure.- auto domain_utf8 = domain->to_utf8();- // NB: Parse domain once so the suffix check and parsedDomain can share it.- auto parsed_domain = URL::Parser::parse_host(domain_utf8);- if (!host.has_value() || !parsed_domain.has_value() || !DOM::is_a_registrable_domain_suffix_of_or_is_equal_to(parsed_domain.value(), host.value()))- return false;-- // 4. Let parsedDomain be the result of host parsing domain.- // 5. Assert: parsedDomain is not failure.- // NB: This is asserted by the suffix check above.-- // 6. Let encodedDomain be the result of UTF-8 encoding parsedDomain.- auto encoded_domain = parsed_domain->serialize();-- // 7. If the byte sequence length of encodedDomain is greater than the maximum attribute value size, then return failure.- if (encoded_domain.byte_count() > maximum_attribute_value_size)- return false;-- // 8. Append `Domain`/encodedDomain to attributes.- parsed_cookie.domain = move(encoded_domain);- }-- // 13. If expires is given, then append `Expires`/expires (date serialized) to attributes.- if (expires.has_value()) {- auto expiry_time = UnixDateTime::from_milliseconds_since_epoch(expires.value());-- // https://www.ietf.org/archive/id/draft-ietf-httpbis-rfc6265bis-15.html#section-5.6.1- // 3. Let cookie-age-limit be the maximum age of the cookie (which SHOULD be 400 days in the future or sooner, see- // Section 5.5).- auto cookie_age_limit = UnixDateTime::now() + HTTP::Cookie::MAXIMUM_COOKIE_AGE;-- // 4. If the expiry-time is more than cookie-age-limit, the user agent MUST set the expiry time to cookie-age-limit- // in seconds.- if (expiry_time.seconds_since_epoch() > cookie_age_limit.seconds_since_epoch())- expiry_time = cookie_age_limit;-- parsed_cookie.expiry_time_from_expires_attribute = expiry_time;- }-- // 14. If path is the empty string, then set path to the serialized cookie default path of url.- if (path.is_empty())- path = Utf16String::from_utf8(serialized_cookie_default_path(url));-- // 15. If path does not start with U+002F (/), then return failure.- if (!path.starts_with('/'))- return false;-- // 16. If path is not U+002F (/), and name, byte-lowercased, starts with `__host-`, then return failure.- if (path != "/"sv && name_ascii_lowercased.utf16_view().starts_with("__host-"sv))- return false;-- // 17. Let encodedPath be the result of UTF-8 encoding path.- auto encoded_path = path.to_utf8();-- // 18. If the byte sequence length of encodedPath is greater than the maximum attribute value size, then return failure.- if (encoded_path.byte_count() > maximum_attribute_value_size)- return false;-- // 19. Append `Path`/encodedPath to attributes.- parsed_cookie.path = move(encoded_path);-- // 20. Append `Secure`/`` to attributes.- parsed_cookie.secure_attribute_present = true;-- // 21. Switch on sameSite:- switch (same_site) {- // -> "none"- case HTTP::Cookie::SameSite::None:- // Append `SameSite`/`None` to attributes.- parsed_cookie.same_site_attribute = HTTP::Cookie::SameSite::None;- break;- // -> "strict"- case HTTP::Cookie::SameSite::Strict:- // Append `SameSite`/`Strict` to attributes.- parsed_cookie.same_site_attribute = HTTP::Cookie::SameSite::Strict;- break;- // -> "lax"- case HTTP::Cookie::SameSite::Lax:- // Append `SameSite`/`Lax` to attributes.- parsed_cookie.same_site_attribute = HTTP::Cookie::SameSite::Lax;- break;- case HTTP::Cookie::SameSite::Default:- VERIFY_NOT_REACHED();- }-- // FIXME: 22. If partitioned is true, Append `Partitioned`/`` to attributes.- (void)partitioned;-- // 23. Perform the steps defined in Cookies § Storage Model for when the user agent "receives a cookie" with url as- // request-uri, encodedName as cookie-name, encodedValue as cookie-value, and attributes as cookie-attribute-list.- // For the purposes of the steps, the newly-created cookie was received from a "non-HTTP" API.- m_client->page_did_set_cookie(environment_id, url, parsed_cookie, HTTP::Cookie::Source::NonHttp);-- // 24. Return success.- return true;-}--// https://cookiestore.spec.whatwg.org/#dom-cookiestore-set-options-GC::Ref<WebIDL::Promise> CookieStore::set(JS::Realm& realm, CookieInit const& options)-{- auto promise = WebIDL::create_promise(realm);- auto url = validate_cookie_store_mutation(promise);- if (!url.has_value())- return promise;-- set(HTML::principal_realm_settings_object(realm).id, url.release_value(), options, create_cookie_mutation_completion_steps(realm.global_object(), promise, "Name, value, domain or path are malformed"_utf16));- return promise;-}--GC::Ref<WebIDL::Promise> CookieStore::set(JS::Realm& realm, Utf16String name, Utf16String value)-{- CookieInit options {- .domain = {},- .expires = {},- .name = move(name),- .partitioned = false,- .path = "/"_utf16,- .same_site = Bindings::CookieSameSite::Strict,- .value = move(value),- };- auto promise = WebIDL::create_promise(realm);- auto url = validate_cookie_store_mutation(promise);- if (!url.has_value())- return promise;-- set(HTML::principal_realm_settings_object(realm).id, url.release_value(), options, create_cookie_mutation_completion_steps(realm.global_object(), promise, "Name or value are malformed"_utf16));- return promise;-}--void CookieStore::set(HTML::EnvironmentId environment_id, URL::URL url, CookieInit const& options, GC::Ref<CookieMutationCompletionSteps> completion_steps)-{- // 6. Run the following steps in parallel:- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(*this, completion_steps, environment_id, move(url), options), [](auto& self, auto& completion_steps, auto& environment_id, auto& url, auto& options) {- // 1. Let r be the result of running set a cookie with url, options["name"], options["value"], options["expires"],- // options["domain"], options["path"], options["sameSite"], and options["partitioned"].- auto result = self.set_a_cookie(environment_id, url, options.name, options.value, options.expires, options.domain, options.path, same_site_from_bindings(options.same_site), options.partitioned);- completion_steps->function()(result);- }));-}--// https://cookiestore.spec.whatwg.org/#delete-a-cookie-bool CookieStore::delete_a_cookie(HTML::EnvironmentId const& environment_id, URL::URL const& url, Utf16String name, Optional<Utf16String> domain, Utf16String path, bool partitioned)-{- // 1. Let expires be the earliest representable date represented as a timestamp.- // NOTE: The exact value of expires is not important for the purposes of this algorithm, as long as it is in the past.- HighResolutionTime::DOMHighResTimeStamp expires = UnixDateTime::earliest().milliseconds_since_epoch();-- // 2. Normalize name.- name = normalize(name);-- // 3. Let value be the empty string.- Utf16String value;-- // 4. If name’s length is 0, then set value to any non-empty implementation-defined string.- if (name.is_empty())- value = "ladybird"_utf16;-- // 5. Return the results of running set a cookie with url, name, value, expires, domain, path, "strict", and partitioned.- return set_a_cookie(environment_id, url, move(name), move(value), expires, move(domain), move(path), HTTP::Cookie::SameSite::Strict, partitioned);-}--// https://cookiestore.spec.whatwg.org/#dom-cookiestore-delete-options-GC::Ref<WebIDL::Promise> CookieStore::delete_(JS::Realm& realm, CookieStoreDeleteOptions const& options)-{- auto promise = WebIDL::create_promise(realm);- auto url = validate_cookie_store_mutation(promise);- if (!url.has_value())- return promise;-- delete_(HTML::principal_realm_settings_object(realm).id, url.release_value(), options, create_cookie_mutation_completion_steps(realm.global_object(), promise, "Name is malformed"_utf16));- return promise;-}--GC::Ref<WebIDL::Promise> CookieStore::delete_(JS::Realm& realm, Utf16String name)-{- CookieStoreDeleteOptions options {- .domain = {},- .name = move(name),- .partitioned = true,- .path = "/"_utf16,- };- auto promise = WebIDL::create_promise(realm);- auto url = validate_cookie_store_mutation(promise);- if (!url.has_value())- return promise;-- delete_(HTML::principal_realm_settings_object(realm).id, url.release_value(), options, create_cookie_mutation_completion_steps(realm.global_object(), promise, "Name is malformed"_utf16));- return promise;-}--void CookieStore::delete_(HTML::EnvironmentId environment_id, URL::URL url, CookieStoreDeleteOptions const& options, GC::Ref<CookieMutationCompletionSteps> completion_steps)-{- // 6. Run the following steps in parallel:- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(*this, completion_steps, environment_id, move(url), options), [](auto& self, auto& completion_steps, auto& environment_id, auto& url, auto& options) {- // 1. Let r be the result of running delete a cookie with url, options["name"], options["domain"], options["path"],- // and options["partitioned"].- auto result = self.delete_a_cookie(environment_id, url, options.name, options.domain, options.path, options.partitioned);- completion_steps->function()(result);- }));-}--void CookieStore::set_onchange(GC::Ptr<WebIDL::CallbackType> event_handler)-{- set_event_handler_attribute(HTML::EventNames::change, event_handler);-}--GC::Ptr<WebIDL::CallbackType> CookieStore::onchange()-{- return event_handler_attribute(HTML::EventNames::change);-}--// https://cookiestore.spec.whatwg.org/#cookie-change-struct CookieChange {- enum class Type {- Changed,- Deleted,- };-- HTTP::Cookie::Cookie cookie;- Type type;-};--}--GC_UNTRACED_CAPTURE(Web::CookieStore::CookieChange);--namespace Web::CookieStore {--// https://cookiestore.spec.whatwg.org/#observable-changes-static Vector<CookieChange> observable_changes(Vector<HTTP::Cookie::Cookie> changes)-{- // The observable changes for url are the set of cookie changes to cookies in a cookie store which meet the- // requirements in step 1 of Cookies § Retrieval Algorithm’s steps to compute the "cookie-string from a given- // cookie store" with url as request-uri, for a "non-HTTP" API.- Vector<CookieChange> observable_changes;- observable_changes.ensure_capacity(changes.size());-- auto now = UnixDateTime::now();-- for (auto& cookie : changes) {- // A cookie change is a cookie and a type (either changed or deleted):- // - A cookie which is removed due to an insertion of another cookie with the same name, domain, and path is ignored.- // - A newly-created cookie which is not immediately evicted is considered changed.- // - A newly-created cookie which is immediately evicted is considered deleted.- // - A cookie which is otherwise evicted or removed is considered deleted- auto type = cookie.expiry_time < now ? CookieChange::Type::Deleted : CookieChange::Type::Changed;- observable_changes.unchecked_empend(move(cookie), type);- }-- return observable_changes;-}--struct PreparedLists {- Vector<CookieListItem> changed_list;- Vector<CookieListItem> deleted_list;-};--// https://cookiestore.spec.whatwg.org/#prepare-lists-static PreparedLists prepare_lists(Vector<CookieChange> const& changes)-{- // 1. Let changedList be a new list.- Vector<CookieListItem> changed_list;-- // 2. Let deletedList be a new list.- Vector<CookieListItem> deleted_list;-- // 3. For each change in changes, run these steps:- for (auto const& change : changes) {- // 1. Let item be the result of running create a CookieListItem from change’s cookie.- auto item = create_a_cookie_list_item(change.cookie);-- // 2. If change’s type is changed, then append item to changedList.- if (change.type == CookieChange::Type::Changed)- changed_list.append(move(item));-- // 3. Otherwise, run these steps:- else {- // 1. Set item["value"] to undefined.- item.value.clear();-- // 2. Append item to deletedList.- deleted_list.append(move(item));- }- }-- // 4. Return changedList and deletedList.- return { move(changed_list), move(deleted_list) };-}--// https://cookiestore.spec.whatwg.org/#process-cookie-changes-void CookieStore::process_cookie_changes(JS::Object& relevant_global_object, Vector<HTTP::Cookie::Cookie> all_changes)-{- // 1. Let url be window’s relevant settings object’s creation URL.- // 2. Let changes be the observable changes for url.- // 3. If changes is empty, then continue.- // NB: We perform the URL-based filtering in the UI process so that we don't have to send all changed cookies over- // IPC to every tab.- auto changes = observable_changes(move(all_changes));-- // 4. Queue a global task on the DOM manipulation task source given window to fire a change event named "change"- // with changes at window’s CookieStore.- queue_global_task(HTML::Task::Source::DOMManipulation, relevant_global_object, GC::create_function(GC::Heap::the(), GC::captures(*this, relevant_global_object, move(changes)), [](auto& self, auto& relevant_global_object, auto& changes) {- auto& realm = HTML::relevant_realm(relevant_global_object);- HTML::TemporaryExecutionContext execution_context { realm };- // https://cookiestore.spec.whatwg.org/#fire-a-change-event- // 4. Let changedList and deletedList be the result of running prepare lists from changes.- auto [changed_list, deleted_list] = prepare_lists(changes);-- CookieChangeEventInit event_init = {};- // 5. Set event’s changed attribute to changedList.- event_init.changed = move(changed_list);-- // 6. Set event’s deleted attribute to deletedList.- event_init.deleted = move(deleted_list);-- // 1. Let event be the result of creating an Event using CookieChangeEvent.- // 2. Set event’s type attribute to type.- auto event = CookieChangeEvent::create(HTML::EventNames::change, event_init, HighResolutionTime::current_high_resolution_time(relevant_global_object));-- // 3. Set event’s bubbles and cancelable attributes to false.- event->set_bubbles(false);- event->set_cancelable(false);-- // 7. Dispatch event at target.- self.dispatch_event(event);- }));+ parsed_cookie.name = MUST(String::from_utf8(StringView { cookie->name }));+ parsed_cookie.value = MUST(String::from_utf8(StringView { cookie->value }));+ if (cookie->has_expiry_time)+ parsed_cookie.expiry_time_from_expires_attribute = UnixDateTime::from_milliseconds_since_epoch(cookie->expiry_time);+ if (cookie->has_domain)+ parsed_cookie.domain = MUST(String::from_utf8(StringView { cookie->domain }));+ parsed_cookie.path = MUST(String::from_utf8(StringView { cookie->path }));+ parsed_cookie.secure_attribute_present = cookie->secure_attribute_present;+ parsed_cookie.same_site_attribute = cookie->same_site_attribute;++ page_client(*settings_object).page_did_set_cookie(settings_object->id, url, parsed_cookie, HTTP::Cookie::Source::NonHttp);}}diff --git a/Libraries/LibWeb/CookieStore/CookieStore.h b/Libraries/LibWeb/CookieStore/CookieStore.hindex 23157b50223..0889dc5ed54 100644--- a/Libraries/LibWeb/CookieStore/CookieStore.h+++ b/Libraries/LibWeb/CookieStore/CookieStore.h@@ -1,74 +1,29 @@/** Copyright (c) 2025, Idan Horowitz <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.** SPDX-License-Identifier: BSD-2-Clause*/#pragma once-#include <AK/Optional.h>-#include <AK/String.h>-#include <AK/Types.h>-#include <AK/Utf16String.h>-#include <LibGC/Function.h>-#include <LibHTTP/Cookie/Cookie.h>+#include <AK/Vector.h>+#include <LibGC/Ptr.h>#include <LibHTTP/Forward.h>#include <LibJS/Forward.h>-#include <LibURL/URL.h>#include <LibWeb/Bindings/CookieStore.h>-#include <LibWeb/DOM/EventTarget.h>+#include <LibWeb/Bindings/RustInterface.h>#include <LibWeb/Export.h>-#include <LibWeb/WebIDL/CallbackType.h>-#include <LibWeb/WebIDL/Promise.h>-#include <LibWebCommon/HTML/Scripting/EnvironmentId.h>-#include <LibWebCommon/HighResolutionTime/DOMHighResTimeStamp.h>namespace Web::CookieStore {-using CookieInit = Bindings::CookieInit;-using CookieListItem = Bindings::CookieListItem;-using CookieStoreDeleteOptions = Bindings::CookieStoreDeleteOptions;-using CookieStoreGetOptions = Bindings::CookieStoreGetOptions;--using CookieListCompletionSteps = GC::Function<void(Vector<CookieListItem>)>;-using CookieMutationCompletionSteps = GC::Function<void(bool)>;--// https://cookiestore.spec.whatwg.org/#cookiestore-class WEB_API CookieStore final : public DOM::EventTarget {- WEB_WRAPPABLE(CookieStore, DOM::EventTarget);- GC_DECLARE_ALLOCATOR(CookieStore);+class WEB_API CookieStore : public Bindings::RustInterfaceCell {+ WEB_RUST_INTERFACE(CookieStore, cookie_store)public:- GC::Ref<WebIDL::Promise> get(JS::Realm&, CookieStoreGetOptions const&);- GC::Ref<WebIDL::Promise> get(JS::Realm&, Utf16String);- void get(HTML::EnvironmentId, URL::URL, Optional<Utf16String>, GC::Ref<CookieListCompletionSteps>);-- GC::Ref<WebIDL::Promise> get_all(JS::Realm&, CookieStoreGetOptions const&);- GC::Ref<WebIDL::Promise> get_all(JS::Realm&, Utf16String);- void get_all(HTML::EnvironmentId, URL::URL, Optional<Utf16String>, GC::Ref<CookieListCompletionSteps>);-- GC::Ref<WebIDL::Promise> set(JS::Realm&, CookieInit const&);- GC::Ref<WebIDL::Promise> set(JS::Realm&, Utf16String name, Utf16String value);- void set(HTML::EnvironmentId, URL::URL, CookieInit const&, GC::Ref<CookieMutationCompletionSteps>);-- GC::Ref<WebIDL::Promise> delete_(JS::Realm&, CookieStoreDeleteOptions const&);- GC::Ref<WebIDL::Promise> delete_(JS::Realm&, Utf16String);- void delete_(HTML::EnvironmentId, URL::URL, CookieStoreDeleteOptions const&, GC::Ref<CookieMutationCompletionSteps>);-- void set_onchange(GC::Ptr<WebIDL::CallbackType>);- GC::Ptr<WebIDL::CallbackType> onchange();-- void process_cookie_changes(JS::Object&, Vector<HTTP::Cookie::Cookie>);--private:- CookieStore(PageClient&);- virtual void visit_edges(Cell::Visitor&) override;-- Vector<CookieListItem> query_cookies(HTML::EnvironmentId const&, URL::URL const&, Optional<Utf16String> const& name);- bool set_a_cookie(HTML::EnvironmentId const&, URL::URL const&, Utf16String name, Utf16String value, Optional<HighResolutionTime::DOMHighResTimeStamp> expires, Optional<Utf16String> const& domain, Utf16String path, HTTP::Cookie::SameSite, bool partitioned);- bool delete_a_cookie(HTML::EnvironmentId const&, URL::URL const&, Utf16String name, Optional<Utf16String> domain, Utf16String path, bool partitioned);+ static GC::Ref<CookieStore> create(JS::Realm&);- GC::Ref<PageClient> m_client;+ void process_cookie_changes(Vector<HTTP::Cookie::Cookie> const&);};}diff --git a/Libraries/LibWeb/CookieStore/CookieStore.idl b/Libraries/LibWeb/CookieStore/CookieStore.idlindex 33ea854bc52..b7dbd02c2a3 100644--- a/Libraries/LibWeb/CookieStore/CookieStore.idl+++ b/Libraries/LibWeb/CookieStore/CookieStore.idl@@ -1,4 +1,3 @@-[GenerateToValue]dictionary CookieListItem {USVString name;USVString value;@@ -35,19 +34,19 @@ dictionary CookieStoreDeleteOptions {};// https://cookiestore.spec.whatwg.org/#cookiestore-[Exposed=(ServiceWorker,Window), SecureContext]+[Exposed=(ServiceWorker,Window), SecureContext, ImplementedIn=Rust]interface CookieStore : EventTarget {- Promise<CookieListItem?> get(USVString name);- Promise<CookieListItem?> get(optional CookieStoreGetOptions options = {});+ [ImplementedAs=get_with_name] Promise<CookieListItem?> get(USVString name);+ [ImplementedAs=get] Promise<CookieListItem?> get(optional CookieStoreGetOptions options = {});- Promise<CookieList> getAll(USVString name);- Promise<CookieList> getAll(optional CookieStoreGetOptions options = {});+ [ImplementedAs=get_all_with_name] Promise<CookieList> getAll(USVString name);+ [ImplementedAs=get_all] Promise<CookieList> getAll(optional CookieStoreGetOptions options = {});- Promise<undefined> set(USVString name, USVString value);- Promise<undefined> set(CookieInit options);+ [ImplementedAs=set_with_name_and_value] Promise<undefined> set(USVString name, USVString value);+ [ImplementedAs=set] Promise<undefined> set(CookieInit options);- Promise<undefined> delete(USVString name);- Promise<undefined> delete(CookieStoreDeleteOptions options);+ [ImplementedAs=delete_with_name] Promise<undefined> delete(USVString name);+ [ImplementedAs=delete] Promise<undefined> delete(CookieStoreDeleteOptions options);[Exposed=Window] attribute EventHandler onchange;};diff --git a/Libraries/LibWeb/Forward.h b/Libraries/LibWeb/Forward.hindex 20b7036d744..ecfbc32ea6a 100644--- a/Libraries/LibWeb/Forward.h+++ b/Libraries/LibWeb/Forward.h@@ -236,7 +236,6 @@ class Directive;namespace Web::CookieStore {-class CookieChangeEvent;class CookieStore;}diff --git a/Libraries/LibWeb/HTML/Window.cpp b/Libraries/LibWeb/HTML/Window.cppindex 696e44c430b..0050211f938 100644--- a/Libraries/LibWeb/HTML/Window.cpp+++ b/Libraries/LibWeb/HTML/Window.cpp@@ -1573,7 +1573,7 @@ GC::Ref<CookieStore::CookieStore> Window::cookie_store(){// The cookieStore getter steps are to return this’s associated CookieStore.if (!m_cookie_store)- m_cookie_store = GC::Heap::the().allocate<CookieStore::CookieStore>(page().client());+ m_cookie_store = CookieStore::CookieStore::create(relevant_realm(*this));return *m_cookie_store;}diff --git a/Libraries/LibWeb/ServiceWorker/ServiceWorkerGlobalScope.cpp b/Libraries/LibWeb/ServiceWorker/ServiceWorkerGlobalScope.cppindex bf792b298b0..3f97d315262 100644--- a/Libraries/LibWeb/ServiceWorker/ServiceWorkerGlobalScope.cpp+++ b/Libraries/LibWeb/ServiceWorker/ServiceWorkerGlobalScope.cpp@@ -93,7 +93,7 @@ GC::Ref<CookieStore::CookieStore> ServiceWorkerGlobalScope::cookie_store(){// The cookieStore getter steps are to return this’s associated CookieStore.if (!m_cookie_store)- m_cookie_store = GC::Heap::the().allocate<CookieStore::CookieStore>(page()->client());+ m_cookie_store = CookieStore::CookieStore::create(realm());return *m_cookie_store;}diff --git a/Meta/Generators/libweb_bindings/glue_headers.py b/Meta/Generators/libweb_bindings/glue_headers.pyindex 96dcb61ad70..f3abe24c809 100644--- a/Meta/Generators/libweb_bindings/glue_headers.py+++ b/Meta/Generators/libweb_bindings/glue_headers.py@@ -14,7 +14,6 @@ def bindings_glue_header_for_interface(interface: Interface, wrapper_interface_nmodule_headers = {"Animations": "LibWeb/Animations/BindingsGlue.h","CSS": "LibWeb/CSS/BindingsGlue.h",- "CookieStore": "LibWeb/CookieStore/BindingsGlue.h","IndexedDB": "LibWeb/IndexedDB/BindingsGlue.h","WebRTC": "LibWeb/WebRTC/BindingsGlue.h",}diff --git a/Meta/Generators/libweb_bindings/intrinsics.py b/Meta/Generators/libweb_bindings/intrinsics.pyindex af870cf3e69..db47c5dd39a 100644--- a/Meta/Generators/libweb_bindings/intrinsics.py+++ b/Meta/Generators/libweb_bindings/intrinsics.py@@ -748,7 +748,6 @@ def write_wrapper_factory_implementation(out: TextIO, interface_sets: InterfaceSout.write("""#include <AK/Assertions.h>#include <LibJS/Runtime/Realm.h>-#include <LibWeb/CookieStore/BindingsGlue.h>#include <LibWeb/DOM/BindingsGlue.h>#include <LibWeb/Fetch/BindingsGlue.h>#include <LibWeb/HTML/BindingsGlue.h>diff --git a/Meta/Linters/check_libweb_realm_mentions.py b/Meta/Linters/check_libweb_realm_mentions.pyindex 914a04387c8..0e2ce50063c 100755--- a/Meta/Linters/check_libweb_realm_mentions.py+++ b/Meta/Linters/check_libweb_realm_mentions.py@@ -43,7 +43,7 @@ ALLOWED_REALM_MENTIONS = {),"Clipboard": (4, 8, "the C++ facades create the Rust objects and wrap DataTransfers in a given realm"),"ContentSecurityPolicy": (4, 10, "CSP violation/report objects and callbacks still materialize JS-facing values"),- "CookieStore": (2, 19, "cookie-store async callbacks and promise/value materialization still thread realms"),+ "CookieStore": (2, 3, "the C++ facade creates the Rust CookieStore in a given realm"),"Crypto": (2, 3, "CryptoKey wrappers use the caller's realm and wrapper world"),"DOM": (9,diff --git a/Services/WebContent/ConnectionFromClient.cpp b/Services/WebContent/ConnectionFromClient.cppindex 30015a40fbe..5ed892073a0 100644--- a/Services/WebContent/ConnectionFromClient.cpp+++ b/Services/WebContent/ConnectionFromClient.cpp@@ -3946,7 +3946,7 @@ void ConnectionFromClient::cookies_changed(Web::PageId page_id, Vector<HTTP::Cooif (!window)return;- window->cookie_store()->process_cookie_changes(Web::HTML::relevant_global_object(*window), move(cookies));+ window->cookie_store()->process_cookie_changes(cookies);}}