feat(push): expose native interfaces with shared state

This commit is contained in:
ldm0
2026-11-20 22:47:46 +08:00
parent e2a0d0a292
commit 37ebf0bc4e
16 changed files with 738 additions and 121 deletions
@@ -4,6 +4,7 @@ mod animation_runtime;
mod assets;
mod bar_prop;
pub(crate) mod bridge_descriptor;
pub(crate) mod push_interfaces;
pub(crate) mod service_worker_interfaces;
pub(crate) use bar_prop::install_window_bar_props;
use moli_webapi::external;
@@ -543,6 +543,11 @@ pub(super) fn install_constructor_template_bindings<'s>(
template,
spec.interface.name(),
);
crate::context_bootstrap::push_interfaces::install_template_bindings(
scope,
template,
spec.interface.name(),
);
crate::context_bootstrap::service_worker_interfaces::install_attributes(
scope,
template,
@@ -60,6 +60,9 @@ pub(in crate::context_bootstrap) const WORKER_SHARED_INTERFACE_NAMES: &[&str] =
"ServiceWorkerContainer",
"ServiceWorkerRegistration",
"NavigationPreloadManager",
"PushManager",
"PushSubscription",
"PushSubscriptionOptions",
"Cache",
"CacheStorage",
"ProgressEvent",
@@ -202,6 +205,9 @@ const SECURE_CONTEXT_ONLY_INTERFACE_NAMES: &[&str] = &[
"ServiceWorkerContainer",
"ServiceWorkerRegistration",
"NavigationPreloadManager",
"PushManager",
"PushSubscription",
"PushSubscriptionOptions",
"Cache",
"CacheStorage",
"DeviceMotionEvent",
@@ -0,0 +1,139 @@
//! Native Push objects shared by Window and Worker bindings.
//!
//! The existing subscription store is local only. Until a push transport and
//! encryption backend exist, advertise no content encodings or key material.
use super::*;
use crate::service_worker_runtime::ServiceWorkerPushSubscriptionSnapshot;
use crate::util::{get_private_value, set_private_value};
use crate::{web_api_interfaces, webidl};
use moli_webapi_declare::WebApiObject;
const CONTENT_ENCODINGS: &str = "__moliPushSupportedContentEncodings";
#[derive(WebApiObject)]
#[webapi(interface = web_api_interfaces::PushManager)]
struct PushManagerObject<'s> {
#[webapi(prototype)]
prototype: v8::Local<'s, v8::Object>,
}
pub(super) fn install_template_bindings<'s>(
scope: &mut v8::PinScope<'s, '_, ()>,
template: v8::Local<'s, v8::FunctionTemplate>,
name: &str,
) {
if name != "PushManager" {
moli_webapi::push_values::install_subscription_template_bindings(scope, template, name);
return;
}
let getter = v8::FunctionTemplate::builder(supported_content_encodings)
.constructor_behavior(v8::ConstructorBehavior::Throw)
.build(scope);
getter.set_class_name(v8str(scope, "get supportedContentEncodings"));
template.set_accessor_property(
v8str(scope, "supportedContentEncodings").into(),
Some(getter),
None,
v8::PropertyAttribute::NONE,
);
}
pub(crate) fn build_manager<'s>(
scope: &mut v8::PinScope<'s, '_>,
) -> Option<v8::Local<'s, v8::Object>> {
let prototype = ensure_intrinsic_interface_prototype(scope, "PushManager").ok()?;
PushManagerObject::new(prototype).bind(scope).ok()
}
pub(crate) fn build_subscription<'s>(
scope: &mut v8::PinScope<'s, '_>,
snapshot: &ServiceWorkerPushSubscriptionSnapshot,
) -> Option<v8::Local<'s, v8::Object>> {
let options_prototype =
ensure_intrinsic_interface_prototype(scope, "PushSubscriptionOptions").ok()?;
let options = moli_webapi::push_values::new_subscription_options(
scope,
options_prototype,
snapshot.user_visible_only,
)?;
let prototype = ensure_intrinsic_interface_prototype(scope, "PushSubscription").ok()?;
moli_webapi::push_values::new_subscription(scope, prototype, &snapshot.endpoint, options)
}
fn supported_content_encodings<'s>(
scope: &mut v8::PinScope<'s, '_>,
_args: v8::FunctionCallbackArguments<'s>,
mut rv: v8::ReturnValue<'s, v8::Value>,
) {
let Ok(constructor) = ensure_intrinsic_interface_constructor(scope, "PushManager") else {
return;
};
if let Some(array) = get_private_value(scope, constructor.into(), CONTENT_ENCODINGS) {
rv.set(array);
return;
}
let array = v8::Array::new(scope, 0);
if array.set_integrity_level(scope, v8::IntegrityLevel::Frozen) != Some(true) {
return;
}
set_private_value(scope, constructor.into(), CONTENT_ENCODINGS, array.into());
rv.set(array.into());
}
#[derive(Default, webidl::WebIdlDictionary)]
#[webidl(prefix = "PushSubscriptionOptionsInit")]
pub(crate) struct PushSubscriptionOptionsInit {
#[webidl(name = "applicationServerKey", with = application_server_key_member)]
pub(crate) has_application_server_key: bool,
#[webidl(default = false)]
pub(crate) user_visible_only: bool,
}
fn application_server_key_member<'s>(
scope: &mut v8::PinScope<'s, '_>,
object: v8::Local<'s, v8::Object>,
_key: &str,
) -> Result<bool, webidl::WebIdlError> {
let context = webidl::Context::member("PushSubscriptionOptionsInit", "applicationServerKey");
let Some(value) = webidl::property_result(scope, object, "applicationServerKey", context)?
else {
return Ok(false);
};
if value.is_null_or_undefined() {
return Ok(false);
}
if value.is_array_buffer() || value.is_array_buffer_view() {
webidl::convert::<webidl::BufferSource>(scope, value, context)?;
} else {
webidl::convert::<webidl::DomString>(scope, value, context)?;
}
Ok(true)
}
#[derive(webidl::WebIdlArgs)]
#[webidl(prefix = "PushManager")]
struct ManagerArgs {
#[webidl(with = options_arg)]
options: PushSubscriptionOptionsInit,
}
fn options_arg<'s>(
scope: &mut v8::PinScope<'s, '_>,
args: &v8::FunctionCallbackArguments<'s>,
index: i32,
) -> Result<PushSubscriptionOptionsInit, webidl::WebIdlError> {
webidl::parse_dictionary(
scope,
args.get(index),
webidl::Context::argument("PushManager", (index + 1) as usize),
)
.map(Option::unwrap_or_default)
}
pub(crate) fn parse_options<'s>(
scope: &mut v8::PinScope<'s, '_>,
args: &v8::FunctionCallbackArguments<'s>,
) -> Option<PushSubscriptionOptionsInit> {
webidl::parse_args::<ManagerArgs>(scope, args).map(|parsed| parsed.options)
}
@@ -880,6 +880,18 @@ const CONSTRUCTOR_SPECS_BEFORE_STREAMS: &[ConstructorSpec] = &[
interface: web_api_interfaces::ServiceWorkerRegistration::DESCRIPTOR,
kind: ConstructorKind::Illegal,
},
ConstructorSpec {
interface: web_api_interfaces::PushManager::DESCRIPTOR,
kind: ConstructorKind::Illegal,
},
ConstructorSpec {
interface: web_api_interfaces::PushSubscription::DESCRIPTOR,
kind: ConstructorKind::Illegal,
},
ConstructorSpec {
interface: web_api_interfaces::PushSubscriptionOptions::DESCRIPTOR,
kind: ConstructorKind::Illegal,
},
ConstructorSpec {
interface: web_api_interfaces::NavigationPreloadManager::DESCRIPTOR,
kind: ConstructorKind::Illegal,
@@ -131,12 +131,13 @@ struct ServiceWorkerPeriodicSyncManagerDeclaration {
unregister: (),
}
#[derive(WebApiObject)]
#[webapi(interface = web_api_interfaces::PushManager)]
#[derive(WebApiFunctionTemplate)]
#[webapi(interface = web_api_interfaces::PushManager, enumerable)]
struct ServiceWorkerPushManagerDeclaration {
#[webapi(
method = "subscribe",
callback = service_worker_push_manager_subscribe_callback,
returns_promise,
length = 0
)]
subscribe: (),
@@ -144,6 +145,7 @@ struct ServiceWorkerPushManagerDeclaration {
#[webapi(
method = "getSubscription",
callback = service_worker_push_manager_get_subscription_callback,
returns_promise,
length = 0
)]
get_subscription: (),
@@ -151,11 +153,19 @@ struct ServiceWorkerPushManagerDeclaration {
#[webapi(
method = "permissionState",
callback = service_worker_push_manager_permission_state_callback,
returns_promise,
length = 0
)]
permission_state: (),
}
#[derive(WebApiFunctionTemplate)]
#[webapi(interface = web_api_interfaces::PushSubscription, enumerable)]
struct PushSubscriptionMethods {
#[webapi(method, callback = service_worker_push_subscription_unsubscribe_callback, length = 0, returns_promise)]
unsubscribe: (),
}
#[derive(WebApiFunctionTemplate)]
#[webapi(interface = web_api_interfaces::NavigationPreloadManager, enumerable)]
struct ServiceWorkerNavigationPreloadManagerDeclaration {
@@ -214,6 +224,12 @@ pub(in crate::context_bootstrap) fn install_service_worker_template_bindings<'s>
"ServiceWorker" => {
ServiceWorkerPrototypeDeclaration::initialize_prototype_template(scope, prototype)
}
"PushManager" => {
ServiceWorkerPushManagerDeclaration::initialize_prototype_template(scope, prototype)
}
"PushSubscription" => {
PushSubscriptionMethods::initialize_prototype_template(scope, prototype)
}
"NavigationPreloadManager" => {
ServiceWorkerNavigationPreloadManagerDeclaration::initialize_prototype_template(
scope, prototype,
@@ -1894,12 +1910,30 @@ fn service_worker_push_manager_subscribe_callback<'s>(
args: v8::FunctionCallbackArguments<'s>,
mut rv: v8::ReturnValue<'s, v8::Value>,
) {
let Some(options) = crate::context_bootstrap::push_interfaces::parse_options(scope, &args)
else {
return;
};
let Some(context) = args.this().get_creation_context(scope) else {
return;
};
let scope = &mut v8::ContextScope::new(scope, context);
let Some(resolver) = v8::PromiseResolver::new(scope) else {
return;
};
let promise = resolver.get_promise(scope);
rv.set(promise.into());
if options.has_application_server_key {
reject_service_worker_promise_with_dom_exception(
scope,
resolver,
"Push encryption and application server keys are not supported.",
"NotSupportedError",
);
return;
}
if service_worker_push_permission_state(scope) != "granted" {
reject_service_worker_promise_with_dom_exception(
scope,
@@ -1925,7 +1959,7 @@ fn service_worker_push_manager_subscribe_callback<'s>(
);
return;
};
let user_visible_only = service_worker_push_subscribe_user_visible_only(scope, args.get(0));
let user_visible_only = options.user_visible_only;
let host = unsafe { &*host_ptr };
let Some(subscription) = host.subscribe_service_worker_push(&scope_url, user_visible_only)
else {
@@ -1947,6 +1981,10 @@ fn service_worker_push_manager_get_subscription_callback<'s>(
args: v8::FunctionCallbackArguments<'s>,
mut rv: v8::ReturnValue<'s, v8::Value>,
) {
let Some(context) = args.this().get_creation_context(scope) else {
return;
};
let scope = &mut v8::ContextScope::new(scope, context);
let Some(resolver) = v8::PromiseResolver::new(scope) else {
return;
};
@@ -1982,9 +2020,16 @@ fn service_worker_push_manager_get_subscription_callback<'s>(
fn service_worker_push_manager_permission_state_callback<'s>(
scope: &mut v8::PinScope<'s, '_>,
_args: v8::FunctionCallbackArguments<'s>,
args: v8::FunctionCallbackArguments<'s>,
mut rv: v8::ReturnValue<'s, v8::Value>,
) {
if crate::context_bootstrap::push_interfaces::parse_options(scope, &args).is_none() {
return;
}
let Some(context) = args.this().get_creation_context(scope) else {
return;
};
let scope = &mut v8::ContextScope::new(scope, context);
let Some(resolver) = v8::PromiseResolver::new(scope) else {
return;
};
@@ -2013,18 +2058,6 @@ fn service_worker_push_permission_state(scope: &mut v8::PinScope<'_, '_>) -> Str
.to_owned()
}
fn service_worker_push_subscribe_user_visible_only(
scope: &mut v8::PinScope<'_, '_>,
value: v8::Local<'_, v8::Value>,
) -> bool {
let Ok(options) = v8::Local::<v8::Object>::try_from(value) else {
return false;
};
options
.get(scope, v8str(scope, "userVisibleOnly").into())
.is_some_and(|value| value.boolean_value(scope))
}
pub(crate) fn settle_service_worker_unregister_completion<'s>(
scope: &mut v8::PinScope<'s, '_>,
resolver: v8::Local<'s, v8::PromiseResolver>,
@@ -2505,10 +2538,9 @@ fn build_service_worker_push_manager<'s>(
scope: &mut v8::PinScope<'s, '_>,
scope_url: &str,
) -> Option<v8::Local<'s, v8::Object>> {
let declaration = ServiceWorkerPushManagerDeclaration::new();
let push_manager = bind_declared_service_worker_object(scope, &declaration);
let push_manager = crate::context_bootstrap::push_interfaces::build_manager(scope)?;
let scope_value = v8_string(scope, scope_url)?;
define_non_enumerable_value_property(
set_private_value(
scope,
push_manager,
SERVICE_WORKER_PUSH_MANAGER_SCOPE_SLOT,
@@ -2554,14 +2586,10 @@ fn build_service_worker_push_subscription_object<'s>(
scope_url: &url::Url,
snapshot: &crate::service_worker_runtime::ServiceWorkerPushSubscriptionSnapshot,
) -> Option<v8::Local<'s, v8::Object>> {
let subscription = moli_webapi::push_values::new_subscription(
scope,
&snapshot.endpoint,
snapshot.user_visible_only,
service_worker_push_subscription_unsubscribe_callback,
)?;
let subscription =
crate::context_bootstrap::push_interfaces::build_subscription(scope, snapshot)?;
let scope_value = v8_string(scope, scope_url.as_str())?;
define_non_enumerable_value_property(
set_private_value(
scope,
subscription,
SERVICE_WORKER_PUSH_SUBSCRIPTION_SCOPE_SLOT,
@@ -2575,6 +2603,10 @@ fn service_worker_push_subscription_unsubscribe_callback<'s>(
args: v8::FunctionCallbackArguments<'s>,
mut rv: v8::ReturnValue<'s, v8::Value>,
) {
let Some(context) = args.this().get_creation_context(scope) else {
return;
};
let scope = &mut v8::ContextScope::new(scope, context);
let Some(resolver) = v8::PromiseResolver::new(scope) else {
return;
};
@@ -2621,21 +2653,20 @@ fn service_worker_sync_manager_scope_from_this(
url::Url::parse(&scope_string).ok()
}
fn service_worker_push_manager_scope_from_this(
scope: &mut v8::PinScope<'_, '_>,
push_manager: v8::Local<'_, v8::Object>,
fn service_worker_push_manager_scope_from_this<'s>(
scope: &mut v8::PinScope<'s, '_>,
push_manager: v8::Local<'s, v8::Object>,
) -> Option<url::Url> {
let value =
object_own_hidden_value(scope, push_manager, SERVICE_WORKER_PUSH_MANAGER_SCOPE_SLOT)?;
let value = get_private_value(scope, push_manager, SERVICE_WORKER_PUSH_MANAGER_SCOPE_SLOT)?;
let scope_string = value.to_string(scope)?.to_rust_string_lossy(scope);
url::Url::parse(&scope_string).ok()
}
fn service_worker_push_subscription_scope_from_this(
scope: &mut v8::PinScope<'_, '_>,
subscription: v8::Local<'_, v8::Object>,
fn service_worker_push_subscription_scope_from_this<'s>(
scope: &mut v8::PinScope<'s, '_>,
subscription: v8::Local<'s, v8::Object>,
) -> Option<url::Url> {
let value = object_own_hidden_value(
let value = get_private_value(
scope,
subscription,
SERVICE_WORKER_PUSH_SUBSCRIPTION_SCOPE_SLOT,
@@ -2958,3 +2958,37 @@ async fn service_worker_native_interfaces_connect_window_and_worker_backends() {
assert_eq!(vm.eval("__serviceWorkerInterfaceDone").unwrap(), "true");
server.await.unwrap();
}
#[tokio::test]
async fn push_native_interfaces_connect_window_and_worker_backends() {
let (base_url, server) = spawn_service_worker_response_server(vec![(
"/app/worker.js",
"text/javascript",
include_str!("../../../push_interfaces_worker.js"),
)])
.await;
let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).expect("loader");
let (mut vm, runtime) = new_service_worker_page_test_vm_with_loader_and_browser_context_runtime(
&format!("{base_url}/app/page.html"),
&loader,
);
vm.eval("document.body.innerHTML = '<iframe id=child></iframe>'")
.unwrap();
vm.eval(&format!("({}).then(value => globalThis.__pushInterfaceDone = value, error => globalThis.__pushInterfaceDone = String(error));",
include_str!("../../../push_interfaces_registration.js"))).unwrap();
drain_service_worker_test_until_eval_equals(
&mut vm,
&runtime,
&loader,
"typeof __pushInterfaceDone",
"boolean",
)
.await;
assert_eq!(
vm.eval("JSON.stringify(__nodeReplacementResults.failures)")
.unwrap(),
"[]"
);
assert_eq!(vm.eval("__pushInterfaceDone").unwrap(), "true");
server.await.unwrap();
}
@@ -2442,6 +2442,7 @@ mod popup_root_window;
mod post_parse;
mod promise_jobs;
mod push_interfaces;
mod queue_microtask;
mod svg_gradient_native_receivers;
@@ -0,0 +1,76 @@
(async () => {
const rows = [];
const assert = (value, message) => { if (!value) throw Error(message); };
const check = async (name, run) => {
try { await run(); rows.push({ name, pass: true }); }
catch (e) { rows.push({ name, pass: false, message: String(e) }); }
};
const names = ['PushManager', 'PushSubscription', 'PushSubscriptionOptions'];
const popup = open();
const realms = [['main', window], ['child', document.getElementById('child').contentWindow], ['popup', popup]];
const methods = { PushManager: { subscribe: 0, getSubscription: 0, permissionState: 0 }, PushSubscription: { getKey: 1, unsubscribe: 0, toJSON: 0 } };
const attributes = { PushSubscription: ['endpoint', 'expirationTime', 'options'], PushSubscriptionOptions: ['userVisibleOnly', 'applicationServerKey'] };
try {
for (const [label, w] of realms) {
if (!w.isSecureContext) {
await check(label + '/insecure', () => assert(names.every(name => !(name in w)), 'secure globals hidden'));
continue;
}
for (const name of names) {
await check(label + '/' + name + '/constructor', () => {
const C = w[name], d = Object.getOwnPropertyDescriptor(w, name);
assert(typeof C === 'function' && C.length === 0 && C.name === name, 'constructor metadata');
assert(d.writable && d.configurable && !d.enumerable, 'global descriptor');
assert(Object.getPrototypeOf(C) === w.Function.prototype && Object.getPrototypeOf(C.prototype) === w.Object.prototype, 'intrinsic inheritance');
assert(C.prototype.constructor === C, 'prototype constructor');
const tag = Object.getOwnPropertyDescriptor(C.prototype, Symbol.toStringTag);
assert(tag.value === name && tag.configurable && !tag.writable && !tag.enumerable, 'prototype tag');
for (const call of [() => C(), () => new C()]) {
let error; try { call(); } catch (e) { error = e; }
assert(error instanceof w.TypeError, 'illegal constructor error realm');
}
});
for (const [method, length] of Object.entries(methods[name] || {})) {
await check(label + '/' + name + '/' + method, async () => {
const C = w[name], d = Object.getOwnPropertyDescriptor(C.prototype, method);
assert(d.value.length === length && d.enumerable && d.configurable && d.writable, 'method descriptor');
let conversions = 0, traps = 0;
const trap = () => { traps++; throw Error('author trap'); };
const value = { toString() { conversions++; return 'auth'; }, get applicationServerKey() { conversions++; return null; }, get userVisibleOnly() { conversions++; return false; } };
const revoked = Proxy.revocable({}, {}); revoked.revoke();
const promiseMethod = name === 'PushManager' || method === 'unsubscribe';
for (const receiver of [null, {}, C.prototype, Object.create(C.prototype), new Proxy({}, { get: trap, getPrototypeOf: trap }), revoked.proxy]) {
let error, returned;
try { returned = d.value.call(receiver, value); } catch (e) { error = e; }
if (promiseMethod) {
assert(!error && returned instanceof w.Promise, 'callee-realm rejection promise');
try { await returned; } catch (e) { error = e; }
}
assert(error instanceof w.TypeError, 'native receiver check');
}
assert(conversions === 0 && traps === 0, 'brand precedes arguments and traps');
});
}
for (const attribute of attributes[name] || []) {
await check(label + '/' + name + '/' + attribute, () => {
const d = Object.getOwnPropertyDescriptor(w[name].prototype, attribute);
assert(d.get.length === 0 && d.set === undefined && d.enumerable && d.configurable, 'readonly prototype accessor');
let error; try { d.get.call({}); } catch (e) { error = e; }
assert(error instanceof w.TypeError, 'getter receiver realm');
});
}
}
await check(label + '/encodings', () => {
const C = w.PushManager, d = Object.getOwnPropertyDescriptor(C, 'supportedContentEncodings');
const encodings = C.supportedContentEncodings;
assert(d.get.length === 0 && d.set === undefined && d.enumerable && d.configurable, 'static accessor descriptor');
assert(encodings instanceof w.Array && Object.isFrozen(encodings), 'realm frozen array');
assert(encodings === C.supportedContentEncodings && d.get.call(C) === encodings, 'static SameObject');
if (w !== window) assert(encodings !== PushManager.supportedContentEncodings, 'realm-specific identity');
assert(encodings.every(value => typeof value === 'string'), 'encoding values');
});
}
} finally { popup.close(); }
globalThis.__nodeReplacementResults = { rows, failures: rows.filter(row => !row.pass), passed: rows.filter(row => row.pass).length, total: rows.length };
return rows.every(row => row.pass);
})()
@@ -0,0 +1,120 @@
use super::*;
#[test]
fn push_interfaces_share_native_prototypes_and_receiver_policy() {
let mut vm = new_storage_page_task_executor_test_vm("https://push-interfaces.test/");
vm.eval("document.body.innerHTML = '<iframe id=child></iframe>'")
.unwrap();
vm.eval(&format!(
"({}).then(value => globalThis.__pushInterfaceDone = value, error => globalThis.__pushInterfaceDone = String(error));",
include_str!("push_interfaces.js")
)).unwrap();
assert_eq!(
vm.eval_after_selected_page_tasks("JSON.stringify(__nodeReplacementResults.failures)")
.unwrap(),
"[]"
);
assert_eq!(vm.eval("__pushInterfaceDone").unwrap(), "true");
}
#[test]
fn push_interface_globals_require_secure_contexts() {
let mut vm = new_storage_page_task_executor_test_vm("http://push-interfaces.test/");
vm.eval("document.body.innerHTML = '<iframe id=child></iframe>'")
.unwrap();
vm.eval(&format!(
"({}).then(value => globalThis.__pushInterfaceDone = value);",
include_str!("push_interfaces.js")
))
.unwrap();
assert_eq!(
vm.eval_after_selected_page_tasks("JSON.stringify(__nodeReplacementResults.failures)")
.unwrap(),
"[]"
);
assert_eq!(vm.eval("__pushInterfaceDone").unwrap(), "true");
}
#[test]
fn push_subscription_factories_keep_native_state_and_intrinsic_prototypes() {
let mut vm = new_storage_page_task_executor_test_vm("https://push-interfaces.test/");
vm.eval(
r#"
globalThis.PushTypes = [PushManager, PushSubscription, PushSubscriptionOptions];
globalThis.constructorReads = 0;
for (const name of ['PushManager', 'PushSubscription', 'PushSubscriptionOptions']) {
Object.defineProperty(globalThis, name, { configurable: true, get() {
constructorReads++; throw Error('author constructor');
} });
}
"#,
)
.unwrap();
let context_ptr: *const v8::Global<v8::Context> = &vm.page_default_context as *const _;
vm.renderer_document_isolate
.with_entered_renderer_document_isolate(move |isolate| {
let scope = std::pin::pin!(v8::HandleScope::new(isolate));
let scope = &mut scope.init();
let context = unsafe { v8::Local::new(scope, &*context_ptr) };
let scope = &mut v8::ContextScope::new(scope, context);
let object = crate::context_bootstrap::push_interfaces::build_subscription(
scope,
&crate::service_worker_runtime::ServiceWorkerPushSubscriptionSnapshot {
endpoint: "https://push-interfaces.test/local-subscription".to_owned(),
user_visible_only: true,
},
)
.unwrap();
let global = context.global(scope);
assert_eq!(
global.create_data_property(
scope,
crate::util::v8str(scope, "nativeSubscription").into(),
object.into()
),
Some(true)
);
Ok(())
})
.unwrap();
assert_eq!(vm.eval(r#"(() => {
const [Manager, Subscription, Options] = PushTypes, s = nativeSubscription;
const assert = (value, message) => { if (!value) throw Error(message); };
const throws = (run, expected) => { let error; try { run(); } catch (e) { error = e; }
assert(expected ? error === expected : error instanceof TypeError, 'expected exception'); };
assert(constructorReads === 0, 'intrinsic factories');
assert(Object.getPrototypeOf(s) === Subscription.prototype, 'subscription prototype');
assert(Object.getPrototypeOf(s.options) === Options.prototype && s.options === s.options, 'options identity and prototype');
assert(!Object.hasOwn(s, 'endpoint') && !Object.hasOwn(s, 'getKey') && !Object.hasOwn(s.options, 'userVisibleOnly'), 'shared members');
assert(s.options.userVisibleOnly && s.options.applicationServerKey === null && s.expirationTime === null, 'native state');
assert(s.getKey('auth') === null && s.getKey('p256dh') === null, 'unavailable key material');
for (const args of [[], ['other'], [Symbol()]]) throws(() => s.getKey(...args));
const sentinel = {};
throws(() => s.getKey({ toString() { throw sentinel; } }), sentinel);
let conversions = 0;
const revoked = Proxy.revocable(s, {}); revoked.revoke();
for (const receiver of [Object.create(s), new Proxy(s, {}), revoked.proxy]) {
throws(() => Subscription.prototype.getKey.call(receiver, { toString() { conversions++; return 'auth'; } }));
}
assert(conversions === 0, 'brand before conversion');
const endpoint = s.endpoint;
let getterCalls = 0, setterCalls = 0;
for (const name of ['endpoint', 'expirationTime', 'options']) {
Object.defineProperty(s, name, { configurable: true, get() { getterCalls++; throw Error('author getter'); } });
}
for (const name of ['endpoint', 'expirationTime', 'keys']) {
Object.defineProperty(Object.prototype, name, { configurable: true, set() { setterCalls++; } });
}
let json;
try { json = Subscription.prototype.toJSON.call(s); }
finally { for (const name of ['endpoint', 'expirationTime', 'keys']) delete Object.prototype[name]; }
assert(getterCalls === 0 && setterCalls === 0, 'serialization uses internal state and own data properties');
assert(Object.keys(json).join() === 'endpoint,expirationTime,keys' && json.endpoint === endpoint && json.expirationTime === null, 'JSON fields');
assert(Object.getPrototypeOf(json.keys) === Object.prototype && Object.keys(json.keys).length === 0, 'empty native key record');
const d = Object.getOwnPropertyDescriptor(json, 'endpoint');
assert(d.writable && d.enumerable && d.configurable, 'JSON dictionary descriptor');
const saved = s.getKey; Object.setPrototypeOf(s, null);
assert(saved.call(s, 'auth') === null && Subscription.prototype.toJSON.call(s).endpoint === endpoint, 'brand independent of author prototype');
return 'ok';
})()"#).unwrap(), "ok");
}
@@ -0,0 +1,55 @@
(async () => {
const rows = [], assert = (ok, message) => { if (!ok) throw Error(message); };
const check = async (name, run) => { try { await run(); rows.push({ name, pass: true }); } catch (error) { rows.push({ name, pass: false, message: String(error) }); } };
let registration;
try {
const C = PushManager, descriptor = Object.getOwnPropertyDescriptor(globalThis, 'PushManager');
let reads = 0;
Object.defineProperty(globalThis, 'PushManager', { configurable: true, get() { reads++; throw Error('author constructor'); } });
try { registration = await navigator.serviceWorker.register('/app/worker.js', { scope: '/app/' }); }
finally { Object.defineProperty(globalThis, 'PushManager', descriptor); }
const manager = registration.pushManager;
await check('manager/native-factory', () => assert(reads === 0 && Object.getPrototypeOf(manager) === C.prototype && manager === registration.pushManager && !Object.hasOwn(manager, 'subscribe'), 'native shared prototype and SameObject'));
for (const method of ['subscribe', 'permissionState']) {
await check('manager/' + method + '/conversion-order', async () => {
const order = [], sentinel = {};
let error;
const result = manager[method]({ get applicationServerKey() { order.push('key'); return null; }, get userVisibleOnly() { order.push('visible'); throw sentinel; } });
assert(result instanceof Promise, 'dictionary failures reject');
try { await result; } catch (e) { error = e; }
assert(error === sentinel && order.join() === 'key,visible', 'dictionary order and exception identity');
error = undefined; try { await manager[method](7); } catch (e) { error = e; }
assert(error instanceof TypeError, 'primitive dictionary rejected');
});
}
await check('manager/cross-realm', async () => {
const other = document.getElementById('child').contentWindow;
const promise = other.PushManager.prototype.getSubscription.call(manager);
assert(promise instanceof Promise && !(promise instanceof other.Promise), 'valid result belongs to receiver realm');
assert(await promise === null, 'native empty subscription store');
let error, conversions = 0;
const bad = other.PushManager.prototype.subscribe.call(new Proxy(manager, {}), { get userVisibleOnly() { conversions++; } });
assert(bad instanceof other.Promise, 'invalid result belongs to callee realm');
try { await bad; } catch (e) { error = e; }
assert(error instanceof other.TypeError && conversions === 0, 'author Proxy rejected before conversion');
});
const worker = registration.installing || registration.waiting || registration.active;
if (worker.state !== 'activated') await new Promise((resolve, reject) => {
const timeout = setTimeout(() => reject(Error('activation timeout')), 10000);
worker.onstatechange = () => { if (worker.state === 'activated') { clearTimeout(timeout); worker.onstatechange = null; resolve(); } };
});
await check('manager/worker', async () => {
const channel = new MessageChannel();
const result = await new Promise((resolve, reject) => {
const timeout = setTimeout(() => { channel.port1.close(); reject(Error('worker timeout')); }, 10000);
channel.port1.onmessage = event => { clearTimeout(timeout); channel.port1.close(); resolve(event.data); };
worker.postMessage('probe', [channel.port2]);
});
rows.push(...result);
assert(result.every(row => row.pass), JSON.stringify(result));
});
} catch (error) { rows.push({ name: 'registration/setup', pass: false, message: String(error) }); }
finally { if (registration) await registration.unregister(); }
globalThis.__nodeReplacementResults = { rows, failures: rows.filter(row => !row.pass), passed: rows.filter(row => row.pass).length, total: rows.length };
return rows.every(row => row.pass);
})()
@@ -0,0 +1,18 @@
self.addEventListener('install', event => event.waitUntil(self.skipWaiting()));
self.addEventListener('activate', event => event.waitUntil(self.clients.claim()));
self.addEventListener('message', event => event.waitUntil((async () => {
const rows = [], check = (name, pass) => rows.push({ name: 'worker/' + name, pass: !!pass });
const manager = self.registration.pushManager;
check('manager-prototype', Object.getPrototypeOf(manager) === PushManager.prototype && manager.subscribe === PushManager.prototype.subscribe);
check('secure-interfaces', typeof PushSubscription === 'function' && typeof PushSubscriptionOptions === 'function');
check('encodings', Object.isFrozen(PushManager.supportedContentEncodings) && PushManager.supportedContentEncodings === PushManager.supportedContentEncodings);
check('native-store', await manager.getSubscription() === null);
const sentinel = {}, order = []; let error;
try { await manager.subscribe({ get applicationServerKey() { order.push('key'); return null; }, get userVisibleOnly() { order.push('visible'); throw sentinel; } }); } catch (e) { error = e; }
check('dictionary-exception', error === sentinel && order.join() === 'key,visible');
let conversions = 0;
const rejected = PushManager.prototype.permissionState.call(new Proxy(manager, {}), { get userVisibleOnly() { conversions++; return false; } });
error = undefined; try { await rejected; } catch (e) { error = e; }
check('brand-before-conversion', rejected instanceof Promise && error instanceof TypeError && conversions === 0);
event.ports[0].postMessage(rows); event.ports[0].close();
})().catch(error => { event.ports[0].postMessage([{ name: 'worker/unexpected', pass: false, message: String(error) }]); event.ports[0].close(); })));
@@ -45,13 +45,8 @@ fn build_service_worker_global_registration<'s>(
}
.bind(scope)
.map_err(|error| anyhow!("failed to build service worker periodic sync manager: {error:?}"))?;
let push_manager = ServiceWorkerGlobalPushManagerDeclaration {
subscribe: (),
get_subscription: (),
permission_state: (),
}
.bind(scope)
.map_err(|error| anyhow!("failed to build service worker push manager: {error:?}"))?;
let push_manager = crate::context_bootstrap::push_interfaces::build_manager(scope)
.ok_or_else(|| anyhow!("failed to build service worker push manager"))?;
let navigation_preload =
build_service_worker_global_navigation_preload_manager(scope, scope_url)?;
let prototype = crate::context_bootstrap::ensure_intrinsic_interface_prototype(
@@ -1049,12 +1044,30 @@ pub(super) fn service_worker_push_manager_subscribe_callback<'s>(
args: v8::FunctionCallbackArguments<'s>,
mut rv: v8::ReturnValue<'s, v8::Value>,
) {
let Some(options) = crate::context_bootstrap::push_interfaces::parse_options(scope, &args)
else {
return;
};
let Some(context) = args.this().get_creation_context(scope) else {
return;
};
let scope = &mut v8::ContextScope::new(scope, context);
let Some(resolver) = v8::PromiseResolver::new(scope) else {
return;
};
let promise = resolver.get_promise(scope);
rv.set(promise.into());
if options.has_application_server_key {
let reason = worker_dom_exception_value(
scope,
"Push encryption and application server keys are not supported.",
"NotSupportedError",
);
let _ = resolver.reject(scope, reason);
return;
}
if service_worker_push_permission_state(scope) != "granted" {
let reason = worker_dom_exception_value(
scope,
@@ -1087,7 +1100,7 @@ pub(super) fn service_worker_push_manager_subscribe_callback<'s>(
let _ = resolver.reject(scope, v8::Exception::type_error(scope, message));
return;
};
let user_visible_only = service_worker_push_subscribe_user_visible_only(scope, args.get(0));
let user_visible_only = options.user_visible_only;
let request_id = {
let mut state = state.borrow_mut();
state.register_pending_service_worker_push_subscribe(v8::Global::new(scope, resolver))
@@ -1104,9 +1117,13 @@ pub(super) fn service_worker_push_manager_subscribe_callback<'s>(
pub(super) fn service_worker_push_manager_get_subscription_callback<'s>(
scope: &mut v8::PinScope<'s, '_>,
_args: v8::FunctionCallbackArguments<'s>,
args: v8::FunctionCallbackArguments<'s>,
mut rv: v8::ReturnValue<'s, v8::Value>,
) {
let Some(context) = args.this().get_creation_context(scope) else {
return;
};
let scope = &mut v8::ContextScope::new(scope, context);
let Some(resolver) = v8::PromiseResolver::new(scope) else {
return;
};
@@ -1152,9 +1169,16 @@ pub(super) fn service_worker_push_manager_get_subscription_callback<'s>(
pub(super) fn service_worker_push_manager_permission_state_callback<'s>(
scope: &mut v8::PinScope<'s, '_>,
_args: v8::FunctionCallbackArguments<'s>,
args: v8::FunctionCallbackArguments<'s>,
mut rv: v8::ReturnValue<'s, v8::Value>,
) {
if crate::context_bootstrap::push_interfaces::parse_options(scope, &args).is_none() {
return;
}
let Some(context) = args.this().get_creation_context(scope) else {
return;
};
let scope = &mut v8::ContextScope::new(scope, context);
let Some(resolver) = v8::PromiseResolver::new(scope) else {
return;
};
@@ -1167,18 +1191,6 @@ pub(super) fn service_worker_push_manager_permission_state_callback<'s>(
let _ = resolver.resolve(scope, value);
}
fn service_worker_push_subscribe_user_visible_only(
scope: &mut v8::PinScope<'_, '_>,
value: v8::Local<'_, v8::Value>,
) -> bool {
let Ok(options) = v8::Local::<v8::Object>::try_from(value) else {
return false;
};
options
.get(scope, v8str(scope, "userVisibleOnly").into())
.is_some_and(|value| value.boolean_value(scope))
}
fn service_worker_push_permission_state(scope: &mut v8::PinScope<'_, '_>) -> String {
let Some(state) = get_worker_state(scope) else {
return "prompt".to_owned();
@@ -1199,19 +1211,18 @@ pub(super) fn build_service_worker_push_subscription_object<'s>(
scope: &mut v8::PinScope<'s, '_>,
snapshot: &ServiceWorkerPushSubscriptionSnapshot,
) -> Option<v8::Local<'s, v8::Object>> {
moli_webapi::push_values::new_subscription(
scope,
&snapshot.endpoint,
snapshot.user_visible_only,
service_worker_push_subscription_unsubscribe_callback,
)
crate::context_bootstrap::push_interfaces::build_subscription(scope, snapshot)
}
pub(super) fn service_worker_push_subscription_unsubscribe_callback<'s>(
scope: &mut v8::PinScope<'s, '_>,
_args: v8::FunctionCallbackArguments<'s>,
args: v8::FunctionCallbackArguments<'s>,
mut rv: v8::ReturnValue<'s, v8::Value>,
) {
let Some(context) = args.this().get_creation_context(scope) else {
return;
};
let scope = &mut v8::ContextScope::new(scope, context);
let Some(resolver) = v8::PromiseResolver::new(scope) else {
return;
};
@@ -2024,6 +2035,12 @@ pub(crate) fn install_service_worker_interface_template_bindings<'s>(
"ServiceWorker" => {
ServiceWorkerPrototypeDeclaration::initialize_prototype_template(scope, prototype)
}
"PushManager" => ServiceWorkerGlobalPushManagerDeclaration::initialize_prototype_template(
scope, prototype,
),
"PushSubscription" => {
PushSubscriptionMethods::initialize_prototype_template(scope, prototype)
}
"NavigationPreloadManager" => {
ServiceWorkerGlobalNavigationPreloadManagerDeclaration::initialize_prototype_template(
scope, prototype,
@@ -2076,12 +2093,13 @@ struct ServiceWorkerGlobalPeriodicSyncManagerDeclaration {
unregister: (),
}
#[derive(WebApiObject)]
#[webapi(interface = web_api_interfaces::PushManager)]
#[derive(WebApiFunctionTemplate)]
#[webapi(interface = web_api_interfaces::PushManager, enumerable)]
struct ServiceWorkerGlobalPushManagerDeclaration {
#[webapi(
method = "subscribe",
callback = service_worker_push_manager_subscribe_callback,
returns_promise,
length = 0
)]
subscribe: (),
@@ -2089,6 +2107,7 @@ struct ServiceWorkerGlobalPushManagerDeclaration {
#[webapi(
method = "getSubscription",
callback = service_worker_push_manager_get_subscription_callback,
returns_promise,
length = 0
)]
get_subscription: (),
@@ -2096,11 +2115,19 @@ struct ServiceWorkerGlobalPushManagerDeclaration {
#[webapi(
method = "permissionState",
callback = service_worker_push_manager_permission_state_callback,
returns_promise,
length = 0
)]
permission_state: (),
}
#[derive(WebApiFunctionTemplate)]
#[webapi(interface = web_api_interfaces::PushSubscription, enumerable)]
struct PushSubscriptionMethods {
#[webapi(method, callback = service_worker_push_subscription_unsubscribe_callback, length = 0, returns_promise)]
unsubscribe: (),
}
#[derive(WebApiFunctionTemplate)]
#[webapi(interface = web_api_interfaces::NavigationPreloadManager, enumerable)]
struct ServiceWorkerGlobalNavigationPreloadManagerDeclaration {
@@ -55,9 +55,9 @@ self.addEventListener("message", event => {
const sub = await self.registration.pushManager.subscribe({ userVisibleOnly: true });
const options = sub.options;
const userVisibleOnlyDescriptor =
Object.getOwnPropertyDescriptor(options, "userVisibleOnly");
Object.getOwnPropertyDescriptor(PushSubscriptionOptions.prototype, "userVisibleOnly");
const applicationServerKeyDescriptor =
Object.getOwnPropertyDescriptor(options, "applicationServerKey");
Object.getOwnPropertyDescriptor(PushSubscriptionOptions.prototype, "applicationServerKey");
const readonlyWriteErrors = [];
for (const [key, value] of [
["userVisibleOnly", false],
@@ -93,15 +93,22 @@ self.addEventListener("message", event => {
sub.options.userVisibleOnly !== true ||
sub.options.applicationServerKey !== null ||
!userVisibleOnlyDescriptor ||
userVisibleOnlyDescriptor.writable !== false ||
typeof userVisibleOnlyDescriptor.get !== "function" ||
userVisibleOnlyDescriptor.set !== undefined ||
!applicationServerKeyDescriptor ||
applicationServerKeyDescriptor.writable !== false ||
typeof applicationServerKeyDescriptor.get !== "function" ||
applicationServerKeyDescriptor.set !== undefined ||
readonlyWriteErrors.join(",") !==
"userVisibleOnly:TypeError,applicationServerKey:TypeError" ||
typeof sub.unsubscribe !== "function" ||
json.endpoint !== sub.endpoint ||
json.expirationTime !== null ||
json.options.userVisibleOnly !== true ||
Object.keys(json).join(",") !== "endpoint,expirationTime,keys" ||
Object.keys(json.keys).length !== 0 ||
Object.getPrototypeOf(sub) !== PushSubscription.prototype ||
Object.getPrototypeOf(options) !== PushSubscriptionOptions.prototype ||
self.registration.pushManager.subscribe !== PushManager.prototype.subscribe ||
sub.getKey("auth") !== null || sub.getKey("p256dh") !== null ||
!endpointDescriptor ||
endpointDescriptor.value !== sub.endpoint ||
endpointDescriptor.writable !== true ||
+125 -45
View File
@@ -4,7 +4,8 @@ use moli_v8_util::{
array_buffer_from_bytes, get_private_value, new_uint8_array_from_bytes, set_private_value,
v8_string, v8str,
};
use moli_webapi_declare::{ObjectLiteralDeclaration, WebApiObject};
use moli_webapi_declare::{ObjectLiteralDeclaration, WebApiFunctionTemplate, WebApiObject};
use moli_webidl as webidl;
const SERVICE_WORKER_PUSH_MESSAGE_DATA_BYTES_SLOT: &str = "__lmServiceWorkerPushMessageDataBytes";
#[derive(WebApiObject)]
@@ -120,75 +121,154 @@ fn push_message_data_json_callback<'s>(
rv.set(value);
}
#[derive(WebApiObject)]
#[webapi(interface = web_api_interfaces::PushSubscriptionOptions, prototype = "Object")]
struct ServiceWorkerPushSubscriptionOptionsDeclaration<'scope> {
#[webapi(data_property = "userVisibleOnly", readonly)]
user_visible_only: bool,
const ENDPOINT: &str = "__moliPushSubscriptionEndpoint";
const EXPIRATION_TIME: &str = "__moliPushSubscriptionExpirationTime";
const OPTIONS: &str = "__moliPushSubscriptionOptions";
const USER_VISIBLE_ONLY: &str = "__moliPushUserVisibleOnly";
const APPLICATION_SERVER_KEY: &str = "__moliPushApplicationServerKey";
#[webapi(data_property = "applicationServerKey", readonly)]
application_server_key: v8::Local<'scope, v8::Value>,
#[derive(WebApiObject)]
#[webapi(interface = web_api_interfaces::PushSubscription)]
struct PushSubscriptionObject<'s> {
#[webapi(prototype)]
prototype: v8::Local<'s, v8::Object>,
#[webapi(slot = ENDPOINT)]
endpoint: String,
#[webapi(slot = EXPIRATION_TIME)]
expiration_time: v8::Local<'s, v8::Value>,
#[webapi(slot = OPTIONS)]
options: v8::Local<'s, v8::Object>,
}
#[derive(WebApiObject)]
#[webapi(interface = web_api_interfaces::PushSubscriptionOptions)]
struct PushSubscriptionOptionsObject<'s> {
#[webapi(prototype)]
prototype: v8::Local<'s, v8::Object>,
#[webapi(slot = USER_VISIBLE_ONLY)]
user_visible_only: bool,
#[webapi(slot = APPLICATION_SERVER_KEY)]
application_server_key: v8::Local<'s, v8::Value>,
}
#[derive(WebApiFunctionTemplate)]
#[webapi(interface = web_api_interfaces::PushSubscription, enumerable)]
struct SubscriptionAttributes {
#[webapi(accessor_property, getter = slot_getter, data = v8str(scope, ENDPOINT))]
endpoint: (),
#[webapi(accessor_property, getter = slot_getter, data = v8str(scope, EXPIRATION_TIME))]
expiration_time: (),
#[webapi(accessor_property, getter = slot_getter, data = v8str(scope, OPTIONS))]
options: (),
#[webapi(method, callback = get_key, length = 1)]
get_key: (),
#[webapi(method = "toJSON", callback = to_json, length = 0)]
to_json: (),
}
#[derive(WebApiFunctionTemplate)]
#[webapi(interface = web_api_interfaces::PushSubscriptionOptions, enumerable)]
struct OptionsAttributes {
#[webapi(accessor_property, getter = slot_getter, data = v8str(scope, USER_VISIBLE_ONLY))]
user_visible_only: (),
#[webapi(accessor_property, getter = slot_getter, data = v8str(scope, APPLICATION_SERVER_KEY))]
application_server_key: (),
}
pub fn install_subscription_template_bindings<'s>(
scope: &mut v8::PinScope<'s, '_, ()>,
template: v8::Local<'s, v8::FunctionTemplate>,
name: &str,
) {
let prototype = template.prototype_template(scope);
match name {
"PushSubscription" => {
SubscriptionAttributes::initialize_prototype_template(scope, prototype)
}
"PushSubscriptionOptions" => {
OptionsAttributes::initialize_prototype_template(scope, prototype)
}
_ => {}
}
}
pub fn new_subscription_options<'s>(
scope: &mut v8::PinScope<'s, '_>,
prototype: v8::Local<'s, v8::Object>,
user_visible_only: bool,
application_server_key: v8::Local<'s, v8::Value>,
) -> Option<v8::Local<'s, v8::Object>> {
ServiceWorkerPushSubscriptionOptionsDeclaration::new(user_visible_only, application_server_key)
PushSubscriptionOptionsObject::new(prototype, user_visible_only, v8::null(scope).into())
.bind(scope)
.ok()
}
#[derive(WebApiObject)]
#[webapi(interface = web_api_interfaces::PushSubscription)]
struct PushSubscriptionDeclaration<'s> {
#[webapi(data_property, readonly)]
endpoint: String,
#[webapi(data_property = "expirationTime", readonly)]
expiration_time: v8::Local<'s, v8::Value>,
#[webapi(data_property, readonly)]
options: v8::Local<'s, v8::Object>,
#[webapi(data_property)]
unsubscribe: v8::Local<'s, v8::Function>,
#[webapi(method = "toJSON", callback = subscription_to_json, length = 0)]
to_json: (),
}
/// Build the subscription surface with the caller's own registration operation.
pub fn new_subscription<'s>(
scope: &mut v8::PinScope<'s, '_>,
prototype: v8::Local<'s, v8::Object>,
endpoint: &str,
user_visible_only: bool,
unsubscribe: impl v8::MapFnTo<v8::FunctionCallback>,
options: v8::Local<'s, v8::Object>,
) -> Option<v8::Local<'s, v8::Object>> {
let options = new_subscription_options(scope, user_visible_only, v8::null(scope).into())?;
let unsubscribe = v8::Function::builder(unsubscribe)
.constructor_behavior(v8::ConstructorBehavior::Throw)
.build(scope)?;
unsubscribe.set_name(v8str(scope, "unsubscribe"));
PushSubscriptionDeclaration {
endpoint: endpoint.to_owned(),
expiration_time: v8::null(scope).into(),
PushSubscriptionObject::new(
prototype,
endpoint.to_owned(),
v8::null(scope).into(),
options,
unsubscribe,
to_json: (),
}
)
.bind(scope)
.ok()
}
fn subscription_to_json<'s>(
fn slot_getter<'s>(
scope: &mut v8::PinScope<'s, '_>,
args: v8::FunctionCallbackArguments<'s>,
mut rv: v8::ReturnValue<'s, v8::Value>,
) {
let slot = args.data().to_rust_string_lossy(scope);
if let Some(value) = get_private_value(scope, args.this(), &slot) {
rv.set(value);
}
}
#[derive(Clone, Copy, webidl::WebIdlEnum)]
#[webidl(name = "PushEncryptionKeyName")]
enum PushEncryptionKeyName {
#[webidl(token = "p256dh")]
P256dh,
#[webidl(token = "auth")]
Auth,
}
#[derive(webidl::WebIdlArgs)]
#[webidl(prefix = "PushSubscription.getKey")]
struct GetKeyArgs {
#[webidl(required, converter = "enum")]
name: PushEncryptionKeyName,
}
fn get_key<'s>(
scope: &mut v8::PinScope<'s, '_>,
args: v8::FunctionCallbackArguments<'s>,
mut rv: v8::ReturnValue<'s, v8::Value>,
) {
let Some(GetKeyArgs { name: _name }) = webidl::parse_args::<GetKeyArgs>(scope, &args) else {
return;
};
rv.set_null();
}
fn to_json<'s>(
scope: &mut v8::PinScope<'s, '_>,
args: v8::FunctionCallbackArguments<'s>,
mut rv: v8::ReturnValue<'s, v8::Value>,
) {
let object = ObjectLiteralDeclaration::bind(scope);
for name in ["endpoint", "expirationTime", "options"] {
let value = args
.this()
.get(scope, v8str(scope, name).into())
.unwrap_or_else(|| v8::undefined(scope).into());
for (name, slot) in [("endpoint", ENDPOINT), ("expirationTime", EXPIRATION_TIME)] {
let Some(value) = get_private_value(scope, args.this(), slot) else {
return;
};
object.set_string_property(scope, name, value);
}
let keys = ObjectLiteralDeclaration::bind(scope);
object.set_string_property(scope, "keys", keys.into_value());
rv.set(object.into_value());
}
+10 -5
View File
@@ -20,8 +20,9 @@ fn with_values(test: impl FnOnce(&mut v8::PinScope<'_, '_>)) {
interfaces::PushSubscriptionOptions::DESCRIPTOR,
] {
let template = v8::FunctionTemplate::new(scope, illegal_constructor);
if interface.name() == "EventCounts" {
event_counts::install(scope, template);
match interface.name() {
"EventCounts" => event_counts::install(scope, template),
name => push_values::install_subscription_template_bindings(scope, template, name),
}
finish_template(scope, interface, template);
}
@@ -112,8 +113,9 @@ fn standalone_push_values_preserve_byte_snapshots_and_need_no_worker_host() {
publish(scope, "message", message);
let invalid = push_values::new_push_message_data(scope, &[0xff]).unwrap();
publish(scope, "invalid", invalid);
let options =
push_values::new_subscription_options(scope, true, v8::null(scope).into()).unwrap();
let prototype =
moli_v8_util::global_constructor_prototype(scope, "PushSubscriptionOptions").unwrap();
let options = push_values::new_subscription_options(scope, prototype, true).unwrap();
assert!(interfaces::PushSubscriptionOptions::is_instance(
scope, options
));
@@ -126,7 +128,10 @@ fn standalone_push_values_preserve_byte_snapshots_and_need_no_worker_host() {
if(message.text()!=='{"value":42}' || message.bytes()[0]!==123)throw 'byte snapshot';
if(invalid.text()!=='\ufffd')throw 'utf8';
try{invalid.json();throw 'invalid json accepted'}catch(e){if(!(e instanceof SyntaxError))throw e;}
if(!options.userVisibleOnly || options.applicationServerKey!==null || Object.getOwnPropertyDescriptor(options,'userVisibleOnly').writable)throw 'options';
const visibleOnly=Object.getOwnPropertyDescriptor(PushSubscriptionOptions.prototype,'userVisibleOnly');
if(!options.userVisibleOnly || options.applicationServerKey!==null ||
Object.hasOwn(options,'userVisibleOnly') || typeof visibleOnly.get!=='function' ||
visibleOnly.set!==undefined)throw 'options';
"#,
);
});