Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

fix(webauthn): add native credential members and capability queries

ldm0cda25f93396e
diff --git a/moli-renderer-v8/src/context_bootstrap/exposed_interfaces/metadata.rs b/moli-renderer-v8/src/context_bootstrap/exposed_interfaces/metadata.rs
index 2cf928cf6..284f91602 100644
--- a/moli-renderer-v8/src/context_bootstrap/exposed_interfaces/metadata.rs
+++ b/moli-renderer-v8/src/context_bootstrap/exposed_interfaces/metadata.rs
@@ -101,6 +101,11 @@ pub(in crate::context_bootstrap) const WORKER_SHARED_INTERFACE_NAMES: &[&str] =
];
const SECURE_CONTEXT_ONLY_INTERFACE_NAMES: &[&str] = &[
+ "AuthenticatorAssertionResponse",
+ "AuthenticatorAttestationResponse",
+ "AuthenticatorResponse",
+ "PublicKeyCredential",
+ "Credential",
"MIDIPort",
"MIDIAccess",
"MIDIInput",
diff --git a/moli-renderer-v8/src/context_bootstrap/navigator_runtime.rs b/moli-renderer-v8/src/context_bootstrap/navigator_runtime.rs
index b9a934d64..1c2a9a602 100644
--- a/moli-renderer-v8/src/context_bootstrap/navigator_runtime.rs
+++ b/moli-renderer-v8/src/context_bootstrap/navigator_runtime.rs
@@ -1,5 +1,6 @@
mod clipboard;
mod collections;
+mod credentials;
mod gamepad;
mod geolocation;
mod media_capabilities;
diff --git a/moli-renderer-v8/src/context_bootstrap/navigator_runtime/credentials.rs b/moli-renderer-v8/src/context_bootstrap/navigator_runtime/credentials.rs
new file mode 100644
index 000000000..f70c040ba
--- /dev/null
+++ b/moli-renderer-v8/src/context_bootstrap/navigator_runtime/credentials.rs
@@ -0,0 +1,158 @@
+//! Secure Window credential surfaces without an authenticator backend.
+//!
+//! Availability queries describe the capabilities actually supported by Moli.
+//! Response objects cannot be produced yet; keep their native members and brand
+//! checks without manufacturing credential identifiers, signatures, or keys.
+
+use moli_webapi_declare::WebApiFunctionTemplate;
+
+use crate::{native_bridge::throw_dom_exception, util::v8str, web_api_interfaces};
+
+#[derive(WebApiFunctionTemplate)]
+#[webapi(interface = web_api_interfaces::Credential, enumerable, receiver)]
+struct CredentialDeclaration {
+ #[webapi(accessor_property, getter = credential_unavailable)]
+ id: (),
+ #[webapi(accessor_property = "type", getter = credential_unavailable)]
+ credential_type: (),
+ #[webapi(static_method, returns_promise, length = 0, callback = unavailable_capability)]
+ is_conditional_mediation_available: (),
+}
+
+#[derive(WebApiFunctionTemplate)]
+#[webapi(interface = web_api_interfaces::PublicKeyCredential, enumerable, receiver)]
+struct PublicKeyCredentialDeclaration {
+ #[webapi(accessor_property, getter = credential_unavailable)]
+ raw_id: (),
+ #[webapi(accessor_property, getter = credential_unavailable)]
+ response: (),
+ #[webapi(accessor_property, getter = credential_unavailable)]
+ authenticator_attachment: (),
+ #[webapi(method, length = 0, callback = credential_unavailable)]
+ get_client_extension_results: (),
+ #[webapi(method = "toJSON", length = 0, callback = credential_unavailable)]
+ to_json: (),
+ #[webapi(static_method, returns_promise, length = 0, callback = unavailable_capability)]
+ is_conditional_mediation_available: (),
+ #[webapi(static_method, returns_promise, length = 0, callback = unavailable_capability)]
+ is_user_verifying_platform_authenticator_available: (),
+ #[webapi(static_method, returns_promise, length = 0, callback = client_capabilities)]
+ get_client_capabilities: (),
+}
+
+#[derive(WebApiFunctionTemplate)]
+#[webapi(interface = web_api_interfaces::AuthenticatorResponse, enumerable, receiver)]
+struct AuthenticatorResponseDeclaration {
+ #[webapi(accessor_property = "clientDataJSON", getter = credential_unavailable)]
+ client_data_json: (),
+}
+
+#[derive(WebApiFunctionTemplate)]
+#[webapi(interface = web_api_interfaces::AuthenticatorAttestationResponse, enumerable, receiver)]
+struct AuthenticatorAttestationResponseDeclaration {
+ #[webapi(accessor_property, getter = credential_unavailable)]
+ attestation_object: (),
+ #[webapi(method, length = 0, callback = credential_unavailable)]
+ get_transports: (),
+ #[webapi(method, length = 0, callback = credential_unavailable)]
+ get_authenticator_data: (),
+ #[webapi(method, length = 0, callback = credential_unavailable)]
+ get_public_key: (),
+ #[webapi(method, length = 0, callback = credential_unavailable)]
+ get_public_key_algorithm: (),
+}
+
+#[derive(WebApiFunctionTemplate)]
+#[webapi(interface = web_api_interfaces::AuthenticatorAssertionResponse, enumerable, receiver)]
+struct AuthenticatorAssertionResponseDeclaration {
+ #[webapi(accessor_property, getter = credential_unavailable)]
+ authenticator_data: (),
+ #[webapi(accessor_property, getter = credential_unavailable)]
+ signature: (),
+ #[webapi(accessor_property, getter = credential_unavailable)]
+ user_handle: (),
+}
+
+pub(super) fn install<'s>(
+ scope: &mut v8::PinScope<'s, '_, ()>,
+ template: v8::Local<'s, v8::FunctionTemplate>,
+ interface_name: &str,
+) {
+ // Static members are installed on the constructor template by the derive.
+ let prototype = template.prototype_template(scope);
+ match interface_name {
+ "Credential" => {
+ CredentialDeclaration::initialize_template(scope, template);
+ CredentialDeclaration::initialize_prototype_template(scope, prototype);
+ }
+ "PublicKeyCredential" => {
+ PublicKeyCredentialDeclaration::initialize_template(scope, template);
+ PublicKeyCredentialDeclaration::initialize_prototype_template(scope, prototype);
+ }
+ "AuthenticatorResponse" => {
+ AuthenticatorResponseDeclaration::initialize_prototype_template(scope, prototype);
+ }
+ "AuthenticatorAttestationResponse" => {
+ AuthenticatorAttestationResponseDeclaration::initialize_prototype_template(
+ scope, prototype,
+ );
+ }
+ "AuthenticatorAssertionResponse" => {
+ AuthenticatorAssertionResponseDeclaration::initialize_prototype_template(
+ scope, prototype,
+ );
+ }
+ _ => {}
+ }
+}
+
+fn credential_unavailable<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ _args: v8::FunctionCallbackArguments<'s>,
+ _rv: v8::ReturnValue<'s>,
+) {
+ throw_dom_exception(
+ scope,
+ "NotSupportedError",
+ 9,
+ "Credential responses are unavailable without an authenticator backend.",
+ );
+}
+
+fn unavailable_capability<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ _args: v8::FunctionCallbackArguments<'s>,
+ mut rv: v8::ReturnValue<'s>,
+) {
+ let value = v8::Boolean::new(scope, false).into();
+ super::super::stream_adapter::set_resolved_promise(scope, &mut rv, value);
+}
+
+fn client_capabilities<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ _args: v8::FunctionCallbackArguments<'s>,
+ mut rv: v8::ReturnValue<'s>,
+) {
+ let result = v8::Object::new(scope);
+ // WebAuthn's ClientCapability values in lexicographical order. No platform
+ // backend, ceremony UI, signal operations, or extensions are supported yet.
+ // Each call returns a fresh record in the function's realm.
+ let unavailable = v8::Boolean::new(scope, false);
+ for name in [
+ "conditionalCreate",
+ "conditionalGet",
+ "hybridTransport",
+ "passkeyPlatformAuthenticator",
+ "relatedOrigins",
+ "signalAllAcceptedCredentials",
+ "signalCurrentUserDetails",
+ "signalUnknownCredential",
+ "userVerifyingPlatformAuthenticator",
+ ] {
+ let key = v8str(scope, name);
+ if result.create_data_property(scope, key.into(), unavailable.into()) != Some(true) {
+ return;
+ }
+ }
+ super::super::stream_adapter::set_resolved_promise(scope, &mut rv, result.into());
+}
diff --git a/moli-renderer-v8/src/context_bootstrap/navigator_runtime/navigator.rs b/moli-renderer-v8/src/context_bootstrap/navigator_runtime/navigator.rs
index 0f57c2d9a..2ea2c0b71 100644
--- a/moli-renderer-v8/src/context_bootstrap/navigator_runtime/navigator.rs
+++ b/moli-renderer-v8/src/context_bootstrap/navigator_runtime/navigator.rs
@@ -895,6 +895,7 @@ pub(in crate::context_bootstrap) fn install_navigator_template_bindings<'s>(
install_navigator_collection_template_bindings(scope, template, interface_name);
super::gamepad::install(scope, template, interface_name);
install_media_capabilities_template_bindings(scope, template, interface_name);
+ super::credentials::install(scope, template, interface_name);
let prototype = template.prototype_template(scope);
match interface_name {
"MediaDevices" | "MediaDeviceInfo" | "InputDeviceInfo" => {
diff --git a/moli-renderer-v8/src/context_bootstrap/specs/registry.rs b/moli-renderer-v8/src/context_bootstrap/specs/registry.rs
index 9215e3a0d..229f1c3d8 100644
--- a/moli-renderer-v8/src/context_bootstrap/specs/registry.rs
+++ b/moli-renderer-v8/src/context_bootstrap/specs/registry.rs
@@ -4,6 +4,26 @@ use crate::web_api_interfaces;
use std::collections::HashSet;
const CONSTRUCTOR_SPECS_BEFORE_STREAMS: &[ConstructorSpec] = &[
+ ConstructorSpec {
+ interface: web_api_interfaces::AuthenticatorAssertionResponse::DESCRIPTOR,
+ kind: ConstructorKind::Illegal,
+ },
+ ConstructorSpec {
+ interface: web_api_interfaces::AuthenticatorAttestationResponse::DESCRIPTOR,
+ kind: ConstructorKind::Illegal,
+ },
+ ConstructorSpec {
+ interface: web_api_interfaces::AuthenticatorResponse::DESCRIPTOR,
+ kind: ConstructorKind::Illegal,
+ },
+ ConstructorSpec {
+ interface: web_api_interfaces::PublicKeyCredential::DESCRIPTOR,
+ kind: ConstructorKind::Illegal,
+ },
+ ConstructorSpec {
+ interface: web_api_interfaces::Credential::DESCRIPTOR,
+ kind: ConstructorKind::Illegal,
+ },
ConstructorSpec {
interface: web_api_interfaces::ModelContext::DESCRIPTOR,
kind: ConstructorKind::Illegal,
diff --git a/moli-renderer-v8/src/script_vm/tests/credential_interfaces.rs b/moli-renderer-v8/src/script_vm/tests/credential_interfaces.rs
new file mode 100644
index 000000000..4ced85a3a
--- /dev/null
+++ b/moli-renderer-v8/src/script_vm/tests/credential_interfaces.rs
@@ -0,0 +1,130 @@
+use super::*;
+
+#[test]
+fn credential_members_preserve_native_receiver_inheritance_and_error_realms() {
+ let mut vm = new_storage_page_task_executor_test_vm("https://credential-interfaces.test/");
+ vm.eval("document.body.innerHTML = '<iframe id=child></iframe>'")
+ .unwrap();
+ let context_ptr = &vm.page_default_context as *const _;
+ vm.with_context_scope_by_ptr_and_checkpoint_for_test(context_ptr, |scope, _| {
+ let global = scope.get_current_context().global(scope);
+ let objects = v8::Object::new(scope);
+ let proxies = v8::Object::new(scope);
+ for interface in [
+ "Credential",
+ "PublicKeyCredential",
+ "AuthenticatorResponse",
+ "AuthenticatorAttestationResponse",
+ "AuthenticatorAssertionResponse",
+ ] {
+ let prototype =
+ crate::context_bootstrap::ensure_intrinsic_interface_prototype(scope, interface)?;
+ let object = v8::Object::new(scope);
+ assert_eq!(object.set_prototype(scope, prototype.into()), Some(true));
+ // Native identity fixtures only, not produced credentials or authentication results.
+ moli_webapi_declare::initialize_web_api_object(scope, object, interface).unwrap();
+ let handler = crate::util::new_null_prototype_object(scope);
+ let proxy = v8::Proxy::new(scope, object, handler).unwrap();
+ moli_webapi_declare::register_web_api_proxy(scope, proxy).unwrap();
+ let key = crate::util::v8str(scope, interface);
+ assert_eq!(
+ objects.create_data_property(scope, key.into(), object.into()),
+ Some(true)
+ );
+ assert_eq!(
+ proxies.create_data_property(scope, key.into(), proxy.into()),
+ Some(true)
+ );
+ }
+ for (name, object) in [
+ ("nativeCredentials", objects),
+ ("nativeCredentialProxies", proxies),
+ ] {
+ let key = crate::util::v8str(scope, name);
+ assert_eq!(
+ global.create_data_property(scope, key.into(), object.into()),
+ Some(true)
+ );
+ }
+ Ok(())
+ })
+ .unwrap();
+ assert_eq!(vm.eval(r#"(() => {
+ const foreign=document.getElementById('child').contentWindow;
+ const members=[
+ ['Credential',['id','type'],[]],
+ ['PublicKeyCredential',['rawId','response','authenticatorAttachment'],['getClientExtensionResults','toJSON']],
+ ['AuthenticatorResponse',['clientDataJSON'],[]],
+ ['AuthenticatorAttestationResponse',['attestationObject'],['getTransports','getAuthenticatorData','getPublicKey','getPublicKeyAlgorithm']],
+ ['AuthenticatorAssertionResponse',['authenticatorData','signature','userHandle'],[]]
+ ];
+ for(const [name,attributes,methods] of members) {
+ const callbacks=[...attributes.map(key=>Object.getOwnPropertyDescriptor(foreign[name].prototype,key)?.get),...methods.map(key=>foreign[name].prototype[key])];
+ const native=nativeCredentials[name],proxy=nativeCredentialProxies[name];
+ Object.setPrototypeOf(native,null);
+ globalThis[name]=function AuthorConstructor(){throw Error('author constructor');};
+ const derived=name==='Credential'?['PublicKeyCredential']:name==='AuthenticatorResponse'?['AuthenticatorAttestationResponse','AuthenticatorAssertionResponse']:[];
+ const valid=[native,proxy,...derived.flatMap(key=>[nativeCredentials[key],nativeCredentialProxies[key]])];
+ for(const callback of callbacks) {
+ if(typeof callback!=='function') throw Error('Missing native member');
+ for(const value of valid) {
+ let error;try{callback.call(value);}catch(e){error=e;}
+ if(!(error instanceof foreign.DOMException)||error.name!=='NotSupportedError'||error.code!==9) throw Error('Native brand or error realm');
+ }
+ let traps=0;const trap=()=>{traps++;throw Error('author trap');};
+ const revoked=Proxy.revocable(native,{});revoked.revoke();
+ for(const value of [{},Object.create(native),new Proxy(native,{get:trap,getPrototypeOf:trap}),revoked.proxy,new Event('wrong-interface')]) {
+ let error;try{callback.call(value);}catch(e){error=e;}
+ if(!(error instanceof foreign.TypeError)) throw Error('Invalid receiver accepted');
+ }
+ if(traps!==0) throw Error('Brand check executed author trap');
+ }
+ }
+ return true;
+ })()"#).unwrap(), "true");
+}
+
+#[test]
+fn credential_availability_queries_use_native_promises_and_callee_records() {
+ let mut vm = new_storage_page_task_executor_test_vm("https://credential-capabilities.test/");
+ vm.eval("document.body.innerHTML = '<iframe id=child></iframe>'")
+ .unwrap();
+ vm.eval(r#"(async () => {
+ const assert=(ok,message)=>{if(!ok)throw Error(message);};
+ const foreign=document.getElementById('child').contentWindow;
+ const PromiseCtor=foreign.Promise,ObjectPrototype=foreign.Object.prototype;
+ const conditional=foreign.PublicKeyCredential.isConditionalMediationAvailable;
+ const platform=foreign.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable;
+ const capabilities=foreign.PublicKeyCredential.getClientCapabilities;
+ const baseConditional=foreign.Credential.isConditionalMediationAvailable;
+ const keys=['conditionalCreate','conditionalGet','hybridTransport','passkeyPlatformAuthenticator','relatedOrigins','signalAllAcceptedCredentials','signalCurrentUserDetails','signalUnknownCredential','userVerifyingPlatformAuthenticator'];
+ foreign.PublicKeyCredential=function AuthorConstructor(){throw Error('author constructor');};
+ foreign.Credential=function AuthorConstructor(){throw Error('author constructor');};
+ foreign.Promise=function AuthorPromise(){throw Error('author Promise');};
+ let traps=0;const trap=()=>{traps++;throw Error('author trap');};
+ const revoked=Proxy.revocable({},{});revoked.revoke();
+ for(const thisArg of [null,{},revoked.proxy,new Proxy({}, {get:trap,getPrototypeOf:trap})]) {
+ for(const query of [conditional,platform,baseConditional]) {
+ const promise=query.call(thisArg,{toString:trap});
+ assert(promise instanceof PromiseCtor,'Promise belongs to callee intrinsic realm');
+ let called=false;promise.then(()=>{called=true;});assert(!called,'Promise callbacks are asynchronous');
+ assert(await promise===false,'No unsupported authentication capability advertised');
+ }
+ const promise=capabilities.call(thisArg);
+ assert(promise instanceof PromiseCtor,'Capabilities promise belongs to callee realm');
+ const first=await promise,second=await capabilities();
+ assert(Object.getPrototypeOf(first)===ObjectPrototype,'Record belongs to callee realm');
+ assert(JSON.stringify(Object.keys(first))===JSON.stringify(keys),'Sorted capability keys');
+ assert(keys.every(key=>first[key]===false),'All unsupported capabilities are false');
+ first.conditionalGet=true;
+ assert(first!==second&&second.conditionalGet===false,'No shared mutable capability record');
+ }
+ assert(traps===0,'No author receiver or argument conversion');
+ globalThis.__credentialAvailabilityDone=true;
+ })().catch(error=>globalThis.__credentialAvailabilityDone=String(error))"#).unwrap();
+ assert_eq!(
+ vm.eval_after_selected_page_tasks("__credentialAvailabilityDone")
+ .unwrap(),
+ "true"
+ );
+}
diff --git a/moli-renderer-v8/src/script_vm/tests/mod.rs b/moli-renderer-v8/src/script_vm/tests/mod.rs
index c9e3ec12e..fcd199abc 100644
--- a/moli-renderer-v8/src/script_vm/tests/mod.rs
+++ b/moli-renderer-v8/src/script_vm/tests/mod.rs
@@ -2139,6 +2139,7 @@ mod canvas_paths;
mod canvas_transform_snapshots;
mod canvas_webgl;
mod child_dynamic_inline_scripts;
+mod credential_interfaces;
mod device_events;
mod gamepad_interfaces;
diff --git a/moli-renderer-v8/src/web_api_interfaces.rs b/moli-renderer-v8/src/web_api_interfaces.rs
index 70d5c16af..add869b46 100644
--- a/moli-renderer-v8/src/web_api_interfaces.rs
+++ b/moli-renderer-v8/src/web_api_interfaces.rs
@@ -20,6 +20,11 @@ macro_rules! interfaces {
}
interfaces! {
+ AuthenticatorAssertionResponse: AuthenticatorResponse;
+ AuthenticatorAttestationResponse: AuthenticatorResponse;
+ AuthenticatorResponse;
+ PublicKeyCredential: Credential;
+ Credential;
AbortController;
AbortSignal: EventTarget;
AbstractRange;