Truly independent web browser
LibWeb: Remove the native WebCrypto algorithm bridge
Shannon Boothb578b2fad9cb
diff --git a/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_algorithms.rs b/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_algorithms.rsindex ea9f2a74a79..be31a79bb95 100644--- a/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_algorithms.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_algorithms.rs@@ -10,24 +10,23 @@*/use core::ffi::c_void;-use core::ptr::{NonNull, null, null_mut};+use core::ptr::{NonNull, null_mut};use std::collections::HashSet;use std::rc::Rc;use ak::{Span, SpanMut, Utf16String, Utf16StringUnits};use libjs_rust::api::{- ErrorKind, ErrorType, Gc, Object, PropertyKey, RawNativeFunctionResult, Realm, Trace, TypedArrayBase,- TypedArrayKind, Value, Vm,+ ErrorKind, ErrorType, Gc, Object, PropertyKey, Realm, Trace, TypedArrayBase, TypedArrayKind, Value, Vm,};use crate::bindings::conversions::{BufferSource, buffer_source_type_of, to_octet_enforcing_range, to_unsigned_long_enforcing_range,to_unsigned_short_enforcing_range,};-use crate::bindings::interface::{Ref, cell_from_abi, cell_into_abi};+use crate::bindings::interface::Ref;use crate::bindings::{CallContext, Exception, WebIdlResult};use crate::crypto::crypto::web_crypto_fill_with_random;-use crate::crypto::crypto_bindings::{CryptoKeyPair, JsonWebKey, RawJsonWebKey, crypto_key_from_value};+use crate::crypto::crypto_bindings::{CryptoKeyPair, JsonWebKey, crypto_key_from_value};use crate::crypto::crypto_key::{CryptoKey, InternalAlgorithmData, KEY_USAGES, KeyType, KeyUsage};use crate::crypto::subtle_crypto::{AlgorithmIdentifier, CryptoKeyOrCryptoKeyPair, KeyFormat, dom_error, get_a_copy_of_the_bytes,@@ -101,38 +100,9 @@ pub(crate) fn normalized_key_usages(usages: &[KeyUsage]) -> Vec<KeyUsage> {)}-/// # Safety-///-/// The spans and the receiver are valid for this call.-#[unsafe(no_mangle)]-pub unsafe extern "C" fn web_rust_crypto_usage_intersection(- a: Span<'_, KeyUsage>,- b: Span<'_, KeyUsage>,- state: *mut c_void,- receive: ReceiveUsages,-) {- let result = usage_intersection(a.as_slice(), b.as_slice());- // SAFETY: The caller supplies a receiver that takes the span only for the call.- unsafe { receive(state, Span::new(&result)) };-}--/// # Safety-///-/// The span and the receiver are valid for this call.-#[unsafe(no_mangle)]-pub unsafe extern "C" fn web_rust_crypto_normalized_key_usages(- usages: Span<'_, KeyUsage>,- state: *mut c_void,- receive: ReceiveUsages,-) {- let result = normalized_key_usages(usages.as_slice());- // SAFETY: The caller supplies a receiver that takes the span only for the call.- unsafe { receive(state, Span::new(&result)) };-}-#[derive(PartialEq, Eq)]#[repr(u8)]-pub enum Base64DecodeResult {+enum Base64DecodeResult {#[allow(dead_code, reason = "the native base64 decoder constructs this result")]Success,#[allow(dead_code, reason = "the native base64 decoder constructs this result")]@@ -143,7 +113,7 @@ pub enum Base64DecodeResult {#[derive(Clone, Copy)]#[repr(u8)]-pub enum Asn1Structure {+enum Asn1Structure {SubjectPublicKeyInfo,PrivateKeyInfo,OctetString,@@ -153,9 +123,8 @@ unsafe extern "C" {fn web_crypto_encode_base64url(bytes: Span<'_, u8>, receive: ReceiveBytes, state: *mut c_void) -> i32;fn web_crypto_decode_base64url(raw: usize,- out: *mut c_void,state: *mut c_void,- receive: Option<ReceiveBytes>,+ receive: ReceiveBytes,error_message: &mut usize,) -> Base64DecodeResult;fn web_crypto_decode_asn1_structure(@@ -188,25 +157,10 @@ fn base64_url_bytes_encode(bytes: &[u8]) -> Result<Utf16String, i32> {Ok(encoded.expect("LibWeb returns the base64url string"))}-/// # Safety-///-/// The span is live and the output is writable.-#[unsafe(no_mangle)]-pub unsafe extern "C" fn web_rust_crypto_base64_url_bytes_encode(bytes: Span<'_, u8>, out: &mut usize) -> i32 {- match base64_url_bytes_encode(bytes.as_slice()) {- Ok(encoded) => {- *out = encoded.into_raw();- 0- }- Err(error) => error,- }-}-unsafe fn decode_base64url(base64_url_string: &Utf16String,- out: *mut c_void,state: *mut c_void,- receive: Option<ReceiveBytes>,+ receive: ReceiveBytes,error_message: &mut usize,) -> Base64DecodeResult {let is_ascii = match base64_url_string.as_units() {@@ -218,9 +172,9 @@ unsafe fn decode_base64url(return Base64DecodeResult::NonAscii;}- // SAFETY: The caller passes a live native ByteBuffer as the output.+ // SAFETY: The caller supplies a receiver and a live output slot.let result =- unsafe { web_crypto_decode_base64url(base64_url_string.raw_identity(), out, state, receive, error_message) };+ unsafe { web_crypto_decode_base64url(base64_url_string.raw_identity(), state, receive, error_message) };if result == Base64DecodeResult::InvalidBase64 {// SAFETY: The decoder hands over an owned diagnostic string.let detail = unsafe { Utf16String::from_raw_owned(*error_message) };@@ -229,24 +183,6 @@ unsafe fn decode_base64url(result}-/// # Safety-///-/// The string is live and the output points to a live ByteBuffer.-#[unsafe(no_mangle)]-pub unsafe extern "C" fn web_rust_crypto_base64_url_bytes_decode(- raw: usize,- out: *mut c_void,- error_message: &mut usize,-) -> Base64DecodeResult {- // SAFETY: The caller lends a live string and we take our own reference.- let base64_url_string = unsafe {- ak::reference_utf16_string(raw);- Utf16String::from_raw_owned(raw)- };- // SAFETY: The caller supplies a live ByteBuffer.- unsafe { decode_base64url(&base64_url_string, out, null_mut(), None, error_message) }-}-// https://w3c.github.io/webcrypto/#concept-parse-an-asn1-structureunsafe fn parse_an_asn1_structure(data: Span<'_, u8>,@@ -302,41 +238,6 @@ unsafe fn parse_a_private_key_info(data: Span<'_, u8>, out: *mut c_void) -> Resuunsafe { parse_an_asn1_structure(data, Asn1Structure::PrivateKeyInfo, true, out) }}-/// # Safety-///-/// The span is live and the output points to a live native value of the specified structure.-#[unsafe(no_mangle)]-pub unsafe extern "C" fn web_rust_crypto_parse_an_asn1_structure(- data: Span<'_, u8>,- structure: Asn1Structure,- exact_data: bool,- out: *mut c_void,-) -> usize {- // SAFETY: The caller supplies a live value of the specified structure.- let result = unsafe {- match structure {- Asn1Structure::SubjectPublicKeyInfo => parse_a_subject_public_key_info(data, out),- Asn1Structure::PrivateKeyInfo => parse_a_private_key_info(data, out),- Asn1Structure::OctetString => parse_an_asn1_structure(data, structure, exact_data, out),- }- };- result.err().map_or(0, Utf16String::into_raw)-}--#[derive(Clone, Copy)]-#[repr(u8)]-#[allow(dead_code, reason = "the temporary native algorithm bridge is removed separately")]-pub(crate) enum AlgorithmId {- MlKem = 1,-}--#[derive(Clone, Copy)]-#[repr(u8)]-#[allow(dead_code, reason = "the temporary native algorithm bridge is removed separately")]-pub(crate) enum ParameterId {- AlgorithmParams,-}-#[derive(Clone, Trace)]#[gc(crate = libjs_rust)]pub(crate) struct Bytes(#[gc(untraced)] Rc<Vec<u8>>);@@ -377,213 +278,10 @@ pub(crate) struct EncapsulatedKeyData {pub(crate) ciphertext: Option<Bytes>,}-#[repr(C)]-#[derive(Default)]-struct OptionalLength {- has_value: bool,- value: u32,-}--impl From<Option<u32>> for OptionalLength {- fn from(value: Option<u32>) -> Self {- Self {- has_value: value.is_some(),- value: value.unwrap_or_default(),- }- }-}-type ReceiveBytes = unsafe extern "C" fn(*mut c_void, Span<'_, u8>);-type ReceiveUsages = unsafe extern "C" fn(*mut c_void, Span<'_, KeyUsage>);-type ReceiveJsonWebKey = unsafe extern "C" fn(*mut c_void, &RawJsonWebKey<'_>);unsafe extern "C" {- fn web_crypto_algorithm_from_value(- realm: *mut c_void,- method_id: AlgorithmId,- parameter_id: ParameterId,- value: u64,- name: usize,- out: &mut *mut c_void,- ) -> RawNativeFunctionResult;- fn web_crypto_algorithm_destroy(algorithm: *mut c_void);- fn web_crypto_algorithm_public_key_usages(algorithm: *mut c_void, state: *mut c_void, receive: ReceiveUsages);- fn web_crypto_public_key_for_private_key(key: *mut c_void) -> *mut c_void;- fn web_crypto_algorithm_encrypt(- realm: *mut c_void,- algorithm: *mut c_void,- key: *mut c_void,- data: Span<'_, u8>,- state: *mut c_void,- receive: ReceiveBytes,- ) -> RawNativeFunctionResult;- fn web_crypto_algorithm_decrypt(- realm: *mut c_void,- algorithm: *mut c_void,- key: *mut c_void,- data: Span<'_, u8>,- state: *mut c_void,- receive: ReceiveBytes,- ) -> RawNativeFunctionResult;- fn web_crypto_algorithm_sign(- realm: *mut c_void,- algorithm: *mut c_void,- key: *mut c_void,- data: Span<'_, u8>,- state: *mut c_void,- receive: ReceiveBytes,- ) -> RawNativeFunctionResult;- fn web_crypto_algorithm_verify(- realm: *mut c_void,- algorithm: *mut c_void,- key: *mut c_void,- signature: Span<'_, u8>,- data: Span<'_, u8>,- out: &mut bool,- ) -> RawNativeFunctionResult;- fn web_crypto_algorithm_derive_bits(- realm: *mut c_void,- algorithm: *mut c_void,- key: *mut c_void,- length: OptionalLength,- state: *mut c_void,- receive: ReceiveBytes,- ) -> RawNativeFunctionResult;- fn web_crypto_algorithm_import_key(- realm: *mut c_void,- algorithm: *mut c_void,- format: KeyFormat,- key_data: Span<'_, u8>,- jwk: *const c_void,- extractable: bool,- usages: Span<'_, KeyUsage>,- out: &mut *mut c_void,- ) -> RawNativeFunctionResult;- fn web_crypto_algorithm_generate_key(- realm: *mut c_void,- algorithm: *mut c_void,- extractable: bool,- usages: Span<'_, KeyUsage>,- out_key: &mut *mut c_void,- out_public_key: &mut *mut c_void,- out_private_key: &mut *mut c_void,- ) -> RawNativeFunctionResult;- fn web_crypto_algorithm_export_key(- realm: *mut c_void,- algorithm: *mut c_void,- format: KeyFormat,- key: *mut c_void,- state: *mut c_void,- receive_bytes: ReceiveBytes,- receive_jwk: ReceiveJsonWebKey,- ) -> RawNativeFunctionResult;- fn web_crypto_algorithm_get_key_length(- realm: *mut c_void,- algorithm: *mut c_void,- out: &mut OptionalLength,- ) -> RawNativeFunctionResult;- fn web_crypto_algorithm_get_shared_key_length(- realm: *mut c_void,- algorithm: *mut c_void,- out: &mut u32,- ) -> RawNativeFunctionResult;- fn web_crypto_algorithm_wrap_key(- realm: *mut c_void,- algorithm: *mut c_void,- key: *mut c_void,- data: Span<'_, u8>,- state: *mut c_void,- receive: ReceiveBytes,- ) -> RawNativeFunctionResult;- fn web_crypto_algorithm_unwrap_key(- realm: *mut c_void,- algorithm: *mut c_void,- key: *mut c_void,- data: Span<'_, u8>,- state: *mut c_void,- receive: ReceiveBytes,- ) -> RawNativeFunctionResult;- fn web_crypto_algorithm_encapsulate(- realm: *mut c_void,- algorithm: *mut c_void,- key: *mut c_void,- shared_key: *mut c_void,- ciphertext: *mut c_void,- receive: ReceiveBytes,- ) -> RawNativeFunctionResult;- fn web_crypto_algorithm_decapsulate(- realm: *mut c_void,- algorithm: *mut c_void,- key: *mut c_void,- data: Span<'_, u8>,- state: *mut c_void,- receive: ReceiveBytes,- ) -> RawNativeFunctionResult;- fn web_crypto_algorithm_validate_encrypt_parameters(- realm: *mut c_void,- algorithm: *mut c_void,- ) -> RawNativeFunctionResult;- fn web_crypto_algorithm_validate_decrypt_parameters(- realm: *mut c_void,- algorithm: *mut c_void,- ) -> RawNativeFunctionResult;- fn web_crypto_algorithm_validate_sign_parameters(- realm: *mut c_void,- algorithm: *mut c_void,- ) -> RawNativeFunctionResult;- fn web_crypto_algorithm_validate_verify_parameters(- realm: *mut c_void,- algorithm: *mut c_void,- ) -> RawNativeFunctionResult;- fn web_crypto_algorithm_validate_generate_key_parameters(- realm: *mut c_void,- algorithm: *mut c_void,- ) -> RawNativeFunctionResult;- fn web_crypto_algorithm_validate_import_key_parameters(- realm: *mut c_void,- algorithm: *mut c_void,- ) -> RawNativeFunctionResult;- fn web_crypto_algorithm_validate_derive_bits_parameters(- realm: *mut c_void,- algorithm: *mut c_void,- length: OptionalLength,- ) -> RawNativeFunctionResult;-}--#[derive(Trace)]-#[gc(crate = libjs_rust)]-pub(crate) struct CppAlgorithm(#[gc(untraced)] NonNull<c_void>);--impl Drop for CppAlgorithm {- fn drop(&mut self) {- // SAFETY: This object owns the C++ algorithm.- unsafe { web_crypto_algorithm_destroy(self.0.as_ptr()) };- }-}--impl CppAlgorithm {- pub(crate) fn from_value(- realm: Gc<Realm>,- method_id: AlgorithmId,- parameter_id: ParameterId,- value: Value,- name: &Utf16String,- ) -> WebIdlResult<Self> {- let mut out = null_mut();- // SAFETY: The realm and value are live, and the call borrows the name.- unsafe {- web_crypto_algorithm_from_value(- realm.as_ptr().cast(),- method_id,- parameter_id,- value.to_raw(),- name.raw_identity(),- &mut out,- )- }- .into_completion()?;- Ok(Self(NonNull::new(out).expect("LibWeb returns an algorithm")))- }+ fn web_crypto_public_key_for_private_key(key: *const c_void, name: usize, named_curve: usize) -> *mut c_void;}pub(crate) trait AlgorithmMethods: Trace {@@ -778,372 +476,6 @@ pub(crate) trait AlgorithmMethods: Trace {}}-impl AlgorithmMethods for CppAlgorithm {- fn public_key_usages(&self) -> Option<Vec<KeyUsage>> {- let mut usages = None;- // SAFETY: This object owns the algorithm and the state is writable for the call.- unsafe {- web_crypto_algorithm_public_key_usages(- self.0.as_ptr(),- core::ptr::from_mut(&mut usages).cast(),- receive_usages,- );- };- usages- }-- fn encrypt(&self, cx: &CallContext, key: Ref<CryptoKey>, data: &Bytes) -> WebIdlResult<Bytes> {- let realm = cx.realm();- let mut out: Option<Bytes> = None;- // SAFETY: The realm, algorithm and cells are live, and the other arguments are lent for the call.- unsafe {- web_crypto_algorithm_encrypt(- realm.as_ptr().cast(),- self.0.as_ptr(),- cell_into_abi(key),- Span::new(data.as_slice()),- core::ptr::from_mut(&mut out).cast(),- receive_bytes,- )- }- .into_completion()?;- Ok(out.expect("LibWeb returns bytes"))- }-- fn decrypt(&self, cx: &CallContext, key: Ref<CryptoKey>, data: &Bytes) -> WebIdlResult<Bytes> {- let realm = cx.realm();- let mut out: Option<Bytes> = None;- // SAFETY: The realm, algorithm and cells are live, and the other arguments are lent for the call.- unsafe {- web_crypto_algorithm_decrypt(- realm.as_ptr().cast(),- self.0.as_ptr(),- cell_into_abi(key),- Span::new(data.as_slice()),- core::ptr::from_mut(&mut out).cast(),- receive_bytes,- )- }- .into_completion()?;- Ok(out.expect("LibWeb returns bytes"))- }-- fn sign(- &self,- cx: &CallContext,- _algorithm: &AlgorithmParams,- key: Ref<CryptoKey>,- data: &Bytes,- ) -> WebIdlResult<Bytes> {- let realm = cx.realm();- let mut out: Option<Bytes> = None;- // SAFETY: The realm, algorithm and cells are live, and the other arguments are lent for the call.- unsafe {- web_crypto_algorithm_sign(- realm.as_ptr().cast(),- self.0.as_ptr(),- cell_into_abi(key),- Span::new(data.as_slice()),- core::ptr::from_mut(&mut out).cast(),- receive_bytes,- )- }- .into_completion()?;- Ok(out.expect("LibWeb returns bytes"))- }-- fn verify(- &self,- cx: &CallContext,- _algorithm: &AlgorithmParams,- key: Ref<CryptoKey>,- signature: &Bytes,- data: &Bytes,- ) -> WebIdlResult<bool> {- let realm = cx.realm();- let mut out = false;- // SAFETY: The realm, algorithm and cells are live, and the other arguments are lent for the call.- unsafe {- web_crypto_algorithm_verify(- realm.as_ptr().cast(),- self.0.as_ptr(),- cell_into_abi(key),- Span::new(signature.as_slice()),- Span::new(data.as_slice()),- &mut out,- )- }- .into_completion()?;- Ok(out)- }-- fn derive_bits(- &self,- cx: &CallContext,- _algorithm: &AlgorithmParams,- key: Ref<CryptoKey>,- length: Option<u32>,- ) -> WebIdlResult<Bytes> {- let realm = cx.realm();- let mut out: Option<Bytes> = None;- // SAFETY: The realm, algorithm and cells are live, and the other arguments are lent for the call.- unsafe {- web_crypto_algorithm_derive_bits(- realm.as_ptr().cast(),- self.0.as_ptr(),- cell_into_abi(key),- length.into(),- core::ptr::from_mut(&mut out).cast(),- receive_bytes,- )- }- .into_completion()?;- Ok(out.expect("LibWeb returns bytes"))- }-- fn import_key(- &self,- cx: &CallContext,- _algorithm: &AlgorithmParams,- format: KeyFormat,- key_data: ImportKeyData,- extractable: bool,- usages: &[KeyUsage],- ) -> WebIdlResult<Ref<CryptoKey>> {- let realm = cx.realm();- let mut out = null_mut();- let mut import = |data, jwk| {- // SAFETY: The realm and algorithm are live, and the input and output are lent for the call.- unsafe {- web_crypto_algorithm_import_key(- realm.as_ptr().cast(),- self.0.as_ptr(),- format,- data,- jwk,- extractable,- Span::new(usages),- &mut out,- )- }- .into_completion()- };- match key_data {- ImportKeyData::Bytes(bytes) => import(Span::new(bytes.as_slice()), null())?,- ImportKeyData::JsonWebKey(key) => {- key.with_raw_fields(|fields| import(Span::default(), core::ptr::from_ref(fields).cast()))?- }- };- // SAFETY: LibWeb returns a live CryptoKey cell.- Ok(unsafe { cell_from_abi(out) })- }-- fn generate_key(- &self,- cx: &CallContext,- _algorithm: &AlgorithmParams,- extractable: bool,- usages: &[KeyUsage],- ) -> WebIdlResult<CryptoKeyOrCryptoKeyPair> {- let realm = cx.realm();- let (mut key, mut public_key, mut private_key) = (null_mut(), null_mut(), null_mut());- // SAFETY: The realm, algorithm and cells are live, and the other arguments are lent for the call.- unsafe {- web_crypto_algorithm_generate_key(- realm.as_ptr().cast(),- self.0.as_ptr(),- extractable,- Span::new(usages),- &mut key,- &mut public_key,- &mut private_key,- )- }- .into_completion()?;- // SAFETY: LibWeb returns a live CryptoKey or two live CryptoKeys.- unsafe {- if !key.is_null() {- Ok(CryptoKeyOrCryptoKeyPair::CryptoKey(cell_from_abi(key)))- } else {- Ok(CryptoKeyOrCryptoKeyPair::CryptoKeyPair(CryptoKeyPair {- public_key: Some(cell_from_abi(public_key)),- private_key: Some(cell_from_abi(private_key)),- }))- }- }- }-- fn export_key(&self, cx: &CallContext, format: KeyFormat, key: Ref<CryptoKey>) -> WebIdlResult<ExportKeyResult> {- let realm = cx.realm();- let mut out: Option<ExportKeyResult> = None;- // SAFETY: The realm, algorithm and cells are live, and the other arguments are lent for the call.- unsafe {- web_crypto_algorithm_export_key(- realm.as_ptr().cast(),- self.0.as_ptr(),- format,- cell_into_abi(key),- core::ptr::from_mut(&mut out).cast(),- receive_export_bytes,- receive_export_jwk,- )- }- .into_completion()?;- Ok(out.expect("LibWeb returns an export result"))- }-- fn get_key_length(&self, realm: Gc<Realm>, _algorithm: &AlgorithmParams) -> WebIdlResult<Option<u32>> {- let mut out = OptionalLength::default();- // SAFETY: The realm, algorithm and cells are live, and the other arguments are lent for the call.- unsafe { web_crypto_algorithm_get_key_length(realm.as_ptr().cast(), self.0.as_ptr(), &mut out) }- .into_completion()?;- Ok(out.has_value.then_some(out.value))- }-- fn get_shared_key_length(&self, realm: Gc<Realm>) -> WebIdlResult<u32> {- let mut out = 0;- // SAFETY: The realm, algorithm and cells are live, and the other arguments are lent for the call.- unsafe { web_crypto_algorithm_get_shared_key_length(realm.as_ptr().cast(), self.0.as_ptr(), &mut out) }- .into_completion()?;- Ok(out)- }-- fn wrap_key(&self, realm: Gc<Realm>, key: Ref<CryptoKey>, data: &Bytes) -> WebIdlResult<Bytes> {- let mut out: Option<Bytes> = None;- // SAFETY: The realm, algorithm and cells are live, and the other arguments are lent for the call.- unsafe {- web_crypto_algorithm_wrap_key(- realm.as_ptr().cast(),- self.0.as_ptr(),- cell_into_abi(key),- Span::new(data.as_slice()),- core::ptr::from_mut(&mut out).cast(),- receive_bytes,- )- }- .into_completion()?;- Ok(out.expect("LibWeb returns bytes"))- }-- fn unwrap_key(&self, realm: Gc<Realm>, key: Ref<CryptoKey>, data: &Bytes) -> WebIdlResult<Bytes> {- let mut out: Option<Bytes> = None;- // SAFETY: The realm, algorithm and cells are live, and the other arguments are lent for the call.- unsafe {- web_crypto_algorithm_unwrap_key(- realm.as_ptr().cast(),- self.0.as_ptr(),- cell_into_abi(key),- Span::new(data.as_slice()),- core::ptr::from_mut(&mut out).cast(),- receive_bytes,- )- }- .into_completion()?;- Ok(out.expect("LibWeb returns bytes"))- }-- fn encapsulate(- &self,- realm: Gc<Realm>,- _params: &AlgorithmParams,- key: Ref<CryptoKey>,- ) -> WebIdlResult<EncapsulatedBitsData> {- let (mut shared_key, mut ciphertext): (Option<Bytes>, Option<Bytes>) = (None, None);- // SAFETY: The realm, algorithm and cells are live, and the other arguments are lent for the call.- unsafe {- web_crypto_algorithm_encapsulate(- realm.as_ptr().cast(),- self.0.as_ptr(),- cell_into_abi(key),- core::ptr::from_mut(&mut shared_key).cast(),- core::ptr::from_mut(&mut ciphertext).cast(),- receive_bytes,- )- }- .into_completion()?;- Ok(EncapsulatedBitsData { shared_key, ciphertext })- }-- fn decapsulate(- &self,- realm: Gc<Realm>,- _params: &AlgorithmParams,- key: Ref<CryptoKey>,- data: &Bytes,- ) -> WebIdlResult<Bytes> {- let mut out: Option<Bytes> = None;- // SAFETY: The realm, algorithm and cells are live, and the other arguments are lent for the call.- unsafe {- web_crypto_algorithm_decapsulate(- realm.as_ptr().cast(),- self.0.as_ptr(),- cell_into_abi(key),- Span::new(data.as_slice()),- core::ptr::from_mut(&mut out).cast(),- receive_bytes,- )- }- .into_completion()?;- Ok(out.expect("LibWeb returns bytes"))- }-- fn validate_encrypt_parameters(&self, realm: Gc<Realm>) -> WebIdlResult<()> {- // SAFETY: The realm, algorithm and cells are live, and the other arguments are lent for the call.- unsafe { web_crypto_algorithm_validate_encrypt_parameters(realm.as_ptr().cast(), self.0.as_ptr()) }- .into_completion()?;- Ok(())- }-- fn validate_decrypt_parameters(&self, realm: Gc<Realm>) -> WebIdlResult<()> {- // SAFETY: The realm, algorithm and cells are live, and the other arguments are lent for the call.- unsafe { web_crypto_algorithm_validate_decrypt_parameters(realm.as_ptr().cast(), self.0.as_ptr()) }- .into_completion()?;- Ok(())- }-- fn validate_sign_parameters(&self, realm: Gc<Realm>) -> WebIdlResult<()> {- // SAFETY: The realm, algorithm and cells are live, and the other arguments are lent for the call.- unsafe { web_crypto_algorithm_validate_sign_parameters(realm.as_ptr().cast(), self.0.as_ptr()) }- .into_completion()?;- Ok(())- }-- fn validate_verify_parameters(&self, realm: Gc<Realm>) -> WebIdlResult<()> {- // SAFETY: The realm, algorithm and cells are live, and the other arguments are lent for the call.- unsafe { web_crypto_algorithm_validate_verify_parameters(realm.as_ptr().cast(), self.0.as_ptr()) }- .into_completion()?;- Ok(())- }-- fn validate_generate_key_parameters(&self, realm: Gc<Realm>) -> WebIdlResult<()> {- // SAFETY: The realm, algorithm and cells are live, and the other arguments are lent for the call.- unsafe { web_crypto_algorithm_validate_generate_key_parameters(realm.as_ptr().cast(), self.0.as_ptr()) }- .into_completion()?;- Ok(())- }-- fn validate_import_key_parameters(&self, realm: Gc<Realm>) -> WebIdlResult<()> {- // SAFETY: The realm, algorithm and cells are live, and the other arguments are lent for the call.- unsafe { web_crypto_algorithm_validate_import_key_parameters(realm.as_ptr().cast(), self.0.as_ptr()) }- .into_completion()?;- Ok(())- }-- fn validate_derive_bits_parameters(- &self,- realm: Gc<Realm>,- _: &AlgorithmParams,- length: Option<u32>,- ) -> WebIdlResult<()> {- // SAFETY: The realm, algorithm and cells are live, and the other arguments are lent for the call.- unsafe {- web_crypto_algorithm_validate_derive_bits_parameters(realm.as_ptr().cast(), self.0.as_ptr(), length.into())- }- .into_completion()?;- Ok(())- }-}-#[repr(i32)]enum ShaHashKind {Sha1 = 4,@@ -1398,9 +730,8 @@ fn base64_url_bytes_decode(vm: &Vm, base64_url_string: &Utf16String) -> WebIdlRelet status = unsafe {decode_base64url(base64_url_string,- null_mut(),core::ptr::from_mut(&mut result).cast(),- Some(receive_bytes),+ receive_bytes,&mut error_message,)};@@ -6674,19 +6005,19 @@ unsafe extern "C" {state: *mut c_void,receive: ReceiveBytes,) -> bool;- fn web_crypto_rsa_parse_jwk_key(- realm: *mut c_void,- is_private: bool,- components: Span<'_, usize>,- out: &mut *mut c_void,- ) -> RawNativeFunctionResult;+ fn web_crypto_rsa_key_from_jwk_components(is_private: bool, components: Span<'_, Span<'_, u8>>) -> *mut c_void;fn web_crypto_rsa_export_der(key: *const c_void,is_public: bool,state: *mut c_void,receive: ReceiveBytes,) -> bool;- fn web_crypto_rsa_export_jwk_integer(key: *const c_void, component: RsaJwkInteger) -> usize;+ fn web_crypto_rsa_export_jwk_integer(+ key: *const c_void,+ component: RsaJwkInteger,+ state: *mut c_void,+ receive: ReceiveBytes,+ ) -> bool;fn web_crypto_rsa_oaep_cipher(encrypt: bool,hash_kind: ShaHashKind,@@ -6900,13 +6231,30 @@ fn rsa_key_metadata(vm: &Vm, key: Ref<CryptoKey>) -> WebIdlResult<(u32, Vec<u8>)))}-fn parse_jwk_rsa_key(realm: Gc<Realm>, jwk: &JsonWebKey, is_private: bool) -> WebIdlResult<UninstalledKey> {- let components = [&jwk.n, &jwk.e, &jwk.d, &jwk.p, &jwk.q, &jwk.dp, &jwk.dq, &jwk.qi]- .map(|field| field.as_ref().map_or(0, Utf16String::raw_identity));- let mut key = null_mut();- // SAFETY: The realm, strings and the output slot live for the call.- unsafe { web_crypto_rsa_parse_jwk_key(realm.as_ptr().cast(), is_private, Span::new(&components), &mut key) }- .into_completion()?;+fn parse_jwk_rsa_key(vm: &Vm, jwk: &JsonWebKey, is_private: bool) -> WebIdlResult<UninstalledKey> {+ let decode = |component: &Option<Utf16String>| {+ base64_url_bytes_decode(vm, component.as_ref().expect("the RSA JWK contains the component"))+ };+ let components = if is_private {+ let n = decode(&jwk.n)?;+ let d = decode(&jwk.d)?;+ let e = decode(&jwk.e)?;+ let mut components = vec![n, e, d];+ // We know that if any of the extra parameters are provided, all of them must be+ if jwk.p.is_some() {+ for component in [&jwk.p, &jwk.q, &jwk.dp, &jwk.dq, &jwk.qi] {+ components.push(decode(component)?);+ }+ }+ components+ } else {+ let e = decode(&jwk.e)?;+ let n = decode(&jwk.n)?;+ vec![n, e]+ };+ let components: Vec<_> = components.iter().map(|bytes| Span::new(bytes.as_slice())).collect();+ // SAFETY: The decoded bytes are lent for the call.+ let key = unsafe { web_crypto_rsa_key_from_jwk_components(is_private, Span::new(&components)) };Ok(UninstalledKey(NonNull::new(key).expect("LibCrypto returns an RSA key")))}@@ -6930,15 +6278,21 @@ fn rsa_export_der(vm: &Vm, key: Ref<CryptoKey>, is_public: bool) -> WebIdlResult}fn rsa_export_jwk_integer(vm: &Vm, key: Ref<CryptoKey>, component: RsaJwkInteger) -> WebIdlResult<Utf16String> {- // SAFETY: The key has the requested RSA component and lives for the call.- let raw = unsafe { web_crypto_rsa_export_jwk_integer(key.handle().as_ptr(), component) };- if raw == 0 {- return vm- .throw_completion(ErrorKind::InternalError, ErrorType::OutOfMemory, &[])- .map_err(Into::into);+ let mut bytes: Option<Bytes> = None;+ // SAFETY: The key handle and the output slot are lent for the call.+ let success = unsafe {+ web_crypto_rsa_export_jwk_integer(+ key.handle().as_ptr(),+ component,+ core::ptr::from_mut(&mut bytes).cast(),+ receive_bytes,+ )+ };+ if !success {+ return Err(out_of_memory(vm));}- // SAFETY: LibCrypto transfers an owned string.- Ok(unsafe { Utf16String::from_raw_owned(raw) })+ let bytes = bytes.expect("LibCrypto returns the exported integer");+ encode_jwk_bytes(vm, bytes.as_slice())}fn key_format_to_string(format: KeyFormat) -> &'static str {@@ -7459,7 +6813,7 @@ impl AlgorithmMethods for RsaOaep {}// 2. Let privateKey represent the RSA private key identified by interpreting jwk according to Section 6.3.2 of JSON Web Algorithms [JWA].- let private_key = parse_jwk_rsa_key(cx.realm(), &jwk, true)?;+ let private_key = parse_jwk_rsa_key(cx.vm(), &jwk, true)?;// 3. If privateKey can be determined to not be a valid RSA private key according to [RFC3447], then throw a DataError.let maybe_valid = private_key.is_valid();@@ -7484,7 +6838,7 @@ impl AlgorithmMethods for RsaOaep {}// 2. Let publicKey represent the RSA public key identified by interpreting jwk according to Section 6.3.1 of JSON Web Algorithms [JWA].- let public_key = parse_jwk_rsa_key(cx.realm(), &jwk, false)?;+ let public_key = parse_jwk_rsa_key(cx.vm(), &jwk, false)?;// 3. If publicKey can be determined to not be a valid RSA public key according to [RFC3447], then throw a DataError.let maybe_valid = public_key.is_valid();@@ -8166,7 +7520,7 @@ impl AlgorithmMethods for RsaPss {}// 2. Let privateKey represent the RSA private key identified by interpreting jwk according to Section 6.3.2 of JSON Web Algorithms [JWA].- let private_key = parse_jwk_rsa_key(cx.realm(), &jwk, true)?;+ let private_key = parse_jwk_rsa_key(cx.vm(), &jwk, true)?;// 3. If privateKey can be determined to not be a valid RSA private key according to [RFC3447], then throw a DataError.let maybe_valid = private_key.is_valid();@@ -8191,7 +7545,7 @@ impl AlgorithmMethods for RsaPss {}// 2. Let publicKey represent the RSA public key identified by interpreting jwk according to Section 6.3.1 of JSON Web Algorithms [JWA].- let public_key = parse_jwk_rsa_key(cx.realm(), &jwk, false)?;+ let public_key = parse_jwk_rsa_key(cx.vm(), &jwk, false)?;// 3. If publicKey can be determined to not be a valid RSA public key according to [RFC3447], then throw a DataError.let maybe_valid = public_key.is_valid();@@ -8864,7 +8218,7 @@ impl AlgorithmMethods for RsassaPkcs1 {}// 2. Let privateKey represent the RSA private key identified by interpreting jwk according to Section 6.3.2 of JSON Web Algorithms [JWA].- let private_key = parse_jwk_rsa_key(cx.realm(), &jwk, true)?;+ let private_key = parse_jwk_rsa_key(cx.vm(), &jwk, true)?;// 3. If privateKey can be determined to not be a valid RSA private key according to [RFC3447], then throw a DataError.let maybe_valid = private_key.is_valid();@@ -8889,7 +8243,7 @@ impl AlgorithmMethods for RsassaPkcs1 {}// 2. Let publicKey represent the RSA public key identified by interpreting jwk according to Section 6.3.1 of JSON Web Algorithms [JWA].- let public_key = parse_jwk_rsa_key(cx.realm(), &jwk, false)?;+ let public_key = parse_jwk_rsa_key(cx.vm(), &jwk, false)?;// 3. If publicKey can be determined to not be a valid RSA public key according to [RFC3447], then throw a DataError.let maybe_valid = public_key.is_valid();@@ -15742,28 +15096,19 @@ unsafe extern "C" fn receive_bytes(state: *mut c_void, bytes: Span<'_, u8>) {unsafe { *state.cast::<Option<Bytes>>() = Some(Bytes::new(bytes.as_slice().to_vec())) };}-unsafe extern "C" fn receive_usages(state: *mut c_void, usages: Span<'_, KeyUsage>) {- // SAFETY: The state is the caller's slot, and the service lends the usages.- unsafe { *state.cast::<Option<Vec<KeyUsage>>>() = Some(usages.as_slice().to_vec()) };-}--unsafe extern "C" fn receive_export_bytes(state: *mut c_void, bytes: Span<'_, u8>) {- // SAFETY: The state is the caller's slot, and the service lends the bytes.- unsafe {- *state.cast::<Option<ExportKeyResult>>() = Some(ExportKeyResult::Bytes(Bytes::new(bytes.as_slice().to_vec())));- };-}--unsafe extern "C" fn receive_export_jwk(state: *mut c_void, key: &RawJsonWebKey<'_>) {- // SAFETY: The state is the caller's slot, and the service lends the fields.- unsafe {- *state.cast::<Option<ExportKeyResult>>() = Some(ExportKeyResult::JsonWebKey(JsonWebKey::from_raw_fields(key)));+pub(crate) fn public_key_for_private_key(vm: &Vm, key: Ref<CryptoKey>) -> Option<Ref<CryptoKey>> {+ let name = key.algorithm_name();+ let algorithm = key.internal_algorithm();+ let named_curve = if let InternalAlgorithmData::Ec { named_curve, .. } = &*algorithm {+ named_curve.raw_identity()+ } else {+ 0};-}--pub(crate) fn public_key_for_private_key(key: Ref<CryptoKey>) -> Option<Ref<CryptoKey>> {- // SAFETY: The key is live.- let public_key = unsafe { web_crypto_public_key_for_private_key(cell_into_abi(key)) };- // SAFETY: A non-null pointer returned by LibWeb is a live CryptoKey cell.- NonNull::new(public_key).map(|key| unsafe { cell_from_abi(key.as_ptr()) })+ // SAFETY: The key handle and algorithm metadata are lent for the call.+ let public_key =+ unsafe { web_crypto_public_key_for_private_key(key.handle().as_ptr(), name.raw_identity(), named_curve) };+ NonNull::new(public_key).map(|handle| {+ // SAFETY: The service transfers ownership of the native key.+ unsafe { CryptoKey::create_with_handle(vm, handle) }+ })}diff --git a/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_bindings.rs b/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_bindings.rsindex c24912af3d2..bf6a5ff0481 100644--- a/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_bindings.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_bindings.rs@@ -6,15 +6,13 @@* SPDX-License-Identifier: BSD-2-Clause*/-use core::ffi::c_void;--use ak::{Span, Utf16String};+use ak::Utf16String;use libjs_rust::api::{- ArrayBuffer, ArrayBufferShared, ErrorKind, ErrorType, Gc, PropertyKey, RawNativeFunctionResult, Realm,- ThrowCompletionOr, Trace, Utf16View, Value, Vm,+ ArrayBuffer, ArrayBufferShared, ErrorKind, ErrorType, Gc, PropertyKey, Realm, ThrowCompletionOr, Trace, Utf16View,+ Value, Vm,};-use crate::bindings::interface::{Ref, cell_into_abi, create_dictionary_object, implementation_if_wrapper, wrap};+use crate::bindings::interface::{Ref, create_dictionary_object, implementation_if_wrapper, wrap};use crate::bindings::promise::{WebIdlPromise, resolve_promise};use crate::bindings::{CallContext, Exception, WebIdlResult};use crate::crypto::crypto_algorithms::{Bytes, EncapsulatedBitsData, EncapsulatedKeyData};@@ -68,140 +66,6 @@ pub(crate) struct EncapsulatedBits {pub(crate) ciphertext: Option<Gc<ArrayBuffer>>,}-#[repr(C)]-struct RawRsaOtherPrimesInfo {- d: usize,- r: usize,- t: usize,-}--#[repr(C)]-pub(crate) struct RawJsonWebKey<'a> {- alg: usize,- crv: usize,- d: usize,- dp: usize,- dq: usize,- e: usize,- k: usize,- kty: usize,- n: usize,- p: usize,- r#priv: usize,- r#pub: usize,- q: usize,- qi: usize,- r#use: usize,- x: usize,- y: usize,- ext: u8,- has_key_ops: bool,- key_ops: Span<'a, usize>,- has_oth: bool,- oth: Span<'a, RawRsaOtherPrimesInfo>,-}--fn raw_string(string: Option<&Utf16String>) -> usize {- string.map_or(0, Utf16String::raw_identity)-}--unsafe fn string_from_raw(raw: usize) -> Option<Utf16String> {- if raw == 0 {- return None;- }- // SAFETY: The caller lends a valid string reference.- unsafe { ak::reference_utf16_string(raw) };- // SAFETY: The reference taken above belongs to the new owner.- Some(unsafe { Utf16String::from_raw_owned(raw) })-}--impl JsonWebKey {- pub(crate) fn with_raw_fields<T>(&self, steps: impl FnOnce(&RawJsonWebKey<'_>) -> T) -> T {- let key_ops: Vec<_> = self.key_ops.iter().flatten().map(Utf16String::raw_identity).collect();- let oth: Vec<_> = self- .oth- .iter()- .flatten()- .map(|prime| RawRsaOtherPrimesInfo {- d: raw_string(prime.d.as_ref()),- r: raw_string(prime.r.as_ref()),- t: raw_string(prime.t.as_ref()),- })- .collect();- steps(&RawJsonWebKey {- alg: raw_string(self.alg.as_ref()),- crv: raw_string(self.crv.as_ref()),- d: raw_string(self.d.as_ref()),- dp: raw_string(self.dp.as_ref()),- dq: raw_string(self.dq.as_ref()),- e: raw_string(self.e.as_ref()),- k: raw_string(self.k.as_ref()),- kty: raw_string(self.kty.as_ref()),- n: raw_string(self.n.as_ref()),- p: raw_string(self.p.as_ref()),- r#priv: raw_string(self.r#priv.as_ref()),- r#pub: raw_string(self.r#pub.as_ref()),- q: raw_string(self.q.as_ref()),- qi: raw_string(self.qi.as_ref()),- r#use: raw_string(self.r#use.as_ref()),- x: raw_string(self.x.as_ref()),- y: raw_string(self.y.as_ref()),- ext: self.ext.map_or(0, |ext| if ext { 2 } else { 1 }),- has_key_ops: self.key_ops.is_some(),- key_ops: Span::new(&key_ops),- has_oth: self.oth.is_some(),- oth: Span::new(&oth),- })- }-- /// # Safety- ///- /// Every nonzero string word must be a live AK::Utf16String.- pub(crate) unsafe fn from_raw_fields(raw: &RawJsonWebKey<'_>) -> Self {- // SAFETY: The caller lends the strings and spans for the call.- unsafe {- Self {- alg: string_from_raw(raw.alg),- crv: string_from_raw(raw.crv),- d: string_from_raw(raw.d),- dp: string_from_raw(raw.dp),- dq: string_from_raw(raw.dq),- e: string_from_raw(raw.e),- k: string_from_raw(raw.k),- kty: string_from_raw(raw.kty),- n: string_from_raw(raw.n),- p: string_from_raw(raw.p),- r#priv: string_from_raw(raw.r#priv),- r#pub: string_from_raw(raw.r#pub),- q: string_from_raw(raw.q),- qi: string_from_raw(raw.qi),- r#use: string_from_raw(raw.r#use),- x: string_from_raw(raw.x),- y: string_from_raw(raw.y),- ext: (raw.ext != 0).then_some(raw.ext == 2),- key_ops: raw.has_key_ops.then(|| {- raw.key_ops- .as_slice()- .iter()- .map(|&word| string_from_raw(word).expect("a key usage is a string"))- .collect()- }),- oth: raw.has_oth.then(|| {- raw.oth- .as_slice()- .iter()- .map(|prime| RsaOtherPrimesInfo {- d: string_from_raw(prime.d),- r: string_from_raw(prime.r),- t: string_from_raw(prime.t),- })- .collect()- }),- }- }- }-}-// https://w3c.github.io/webcrypto/#concept-parse-a-jwkpub(crate) fn parse_json_web_key(vm: &Vm, data: &[u8]) -> WebIdlResult<JsonWebKey> {// 1. Let data be the sequence of bytes to be parsed.@@ -333,20 +197,3 @@ pub(super) fn crypto_key_from_value(vm: &Vm, value: Value) -> ThrowCompletionOr<};Ok(key)}--/// # Safety-///-/// The VM and value must be live and the output pointer must be writable.-#[unsafe(no_mangle)]-pub unsafe extern "C" fn web_rust_crypto_key_from_value(- vm: *const c_void,- value: u64,- out: &mut *mut c_void,-) -> RawNativeFunctionResult {- // SAFETY: The caller supplies the live VM and value.- let (vm, value) = unsafe { (&*vm.cast::<Vm>(), Value::from_raw(value)) };- RawNativeFunctionResult::from_completion(crypto_key_from_value(vm, value).map(|key| {- *out = cell_into_abi(key);- Value::UNDEFINED- }))-}diff --git a/Libraries/LibWeb/Bindings/Rust/src/crypto/subtle_crypto.rs b/Libraries/LibWeb/Bindings/Rust/src/crypto/subtle_crypto.rsindex 793f16dd9c4..e4338a65d1d 100644--- a/Libraries/LibWeb/Bindings/Rust/src/crypto/subtle_crypto.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/crypto/subtle_crypto.rs@@ -9,7 +9,6 @@use core::ops::Deref;use std::collections::HashMap;-use std::rc::Rc;use std::sync::LazyLock;use ak::Utf16String;@@ -31,11 +30,11 @@ use crate::bindings::promise::{};use crate::bindings::{CallContext, Exception, MustNotThrow, WebIdlResult};use crate::crypto::crypto_algorithms::{- AesCbc, AesCtr, AesGcm, AesKw, AesOcb, AesParameterType, AlgorithmId, AlgorithmMethods, AlgorithmParams, Argon2,- Argon2Params, Bytes, CShakeParams, ChaCha20Poly1305, CppAlgorithm, EcParameterType, Ecdh, Ecdsa, Ed448, Ed25519,- EncapsulatedKeyData, ExportKeyResult, Hkdf, HkdfParams, Hmac, HmacImportParams, HmacKeyGenParams, ImportKeyData,- Kmac, KmacImportParams, KmacKeyGenParams, KmacParams, MlDsa, MlKem, ParameterId, Pbkdf2, Pbkdf2Params, RsaOaep,- RsaParameterType, RsaPss, RsassaPkcs1, Sha, X448, X25519, normalized_key_usages, public_key_for_private_key,+ AesCbc, AesCtr, AesGcm, AesKw, AesOcb, AesParameterType, AlgorithmMethods, AlgorithmParams, Argon2, Argon2Params,+ Bytes, CShakeParams, ChaCha20Poly1305, EcParameterType, Ecdh, Ecdsa, Ed448, Ed25519, EncapsulatedKeyData,+ ExportKeyResult, Hkdf, HkdfParams, Hmac, HmacImportParams, HmacKeyGenParams, ImportKeyData, Kmac, KmacImportParams,+ KmacKeyGenParams, KmacParams, MlDsa, MlKem, Pbkdf2, Pbkdf2Params, RsaOaep, RsaParameterType, RsaPss, RsassaPkcs1,+ Sha, X448, X25519, normalized_key_usages, public_key_for_private_key,};#[allow(unused_imports,@@ -88,8 +87,6 @@ pub(crate) enum KeyFormat {#[derive(Clone, Copy)]enum RegisteredAlgorithm {- #[allow(dead_code, reason = "the temporary native algorithm bridge is removed separately")]- Cpp(AlgorithmId, ParameterId),Sha,Hmac,HmacKeyGen,@@ -131,7 +128,6 @@ type SupportedAlgorithmsMap = HashMap<&'static str, RegisteredAlgorithms>;#[derive(Clone, Trace)]#[gc(crate = libjs_rust)]enum AlgorithmImplementation {- Cpp(#[gc(untraced)] Rc<CppAlgorithm>),Sha(Sha),Hmac(Hmac),HmacKeyGen(HmacKeyGenParams),@@ -171,7 +167,6 @@ impl Deref for AlgorithmImplementation {fn deref(&self) -> &Self::Target {match self {- Self::Cpp(algorithm) => algorithm.as_ref(),Self::Sha(algorithm) => algorithm,Self::Hmac(algorithm) => algorithm,Self::HmacKeyGen(algorithm) => algorithm,@@ -375,15 +370,6 @@ pub(crate) fn normalize_an_algorithm(// 12. For each dictionary dictionary in dictionaries:// Note: All of these steps are handled by the create_methods and parameter_from_value methods.let methods = match desired_type {- RegisteredAlgorithm::Cpp(method_id, parameter_id) => {- AlgorithmImplementation::Cpp(Rc::new(CppAlgorithm::from_value(- realm,- method_id,- parameter_id,- Value::from_object(*algorithm),- &algorithm_name,- )?))- }RegisteredAlgorithm::Sha => AlgorithmImplementation::Sha(Sha),RegisteredAlgorithm::Hmac => AlgorithmImplementation::Hmac(Hmac),RegisteredAlgorithm::HmacKeyGen => {@@ -2569,7 +2555,7 @@ impl SubtleCrypto {// 10. Let publicKey be a new CryptoKey representing the public key corresponding to the private key represented// by the [[handle]] internal slot of key.- let public_key_data = public_key_for_private_key(key);+ let public_key_data = public_key_for_private_key(vm, key);// 11. If an error occurred, then throw a OperationError.if public_key_data.is_none() {diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txtindex 981b30eab8d..5a82c200ae5 100644--- a/Libraries/LibWeb/CMakeLists.txt+++ b/Libraries/LibWeb/CMakeLists.txt@@ -65,9 +65,7 @@ set(SOURCESCredentialManagement/PasswordCredentialOperations.cppCrypto/Crypto.cppCrypto/CryptoAlgorithms.cpp- Crypto/CryptoBindings.cppCrypto/CryptoKey.cpp- Crypto/SubtleCrypto.cppCSS/Angle.cppCSS/ComputedStyleWorkingSet.cppCSS/ComputedValues.cppdiff --git a/Libraries/LibWeb/Crypto/CryptoAlgorithms.cpp b/Libraries/LibWeb/Crypto/CryptoAlgorithms.cppindex 71ee6a5b25a..d546ec3dbea 100644--- a/Libraries/LibWeb/Crypto/CryptoAlgorithms.cpp+++ b/Libraries/LibWeb/Crypto/CryptoAlgorithms.cpp@@ -30,28 +30,18 @@#include <LibCrypto/PK/MLDSA.h>#include <LibCrypto/PK/MLKEM.h>#include <LibCrypto/PK/RSA.h>-#include <LibJS/HostClassBuilder.h>#include <LibJS/Runtime/Array.h>#include <LibJS/Runtime/ArrayBuffer.h>#include <LibJS/Runtime/DataView.h>#include <LibJS/Runtime/TypedArray.h>#include <LibJS/Runtime/ValueInlines.h>-#include <LibWeb/Bindings/RustSerialization.h>-#include <LibWeb/Bindings/Wrappable.h>-#include <LibWeb/Crypto/CryptoAlgorithms.h>-#include <LibWeb/WebIDL/AbstractOperations.h>-#include <LibWeb/WebIDL/ExceptionOrUtils.h>+#include <LibWeb/Crypto/CryptoKey.h>namespace Web::Crypto {extern "C" {-using ReceiveKeyUsages = void (*)(void*, ReadonlySpan<KeyUsage>);-void web_rust_crypto_usage_intersection(ReadonlySpan<KeyUsage>, ReadonlySpan<KeyUsage>, void*, ReceiveKeyUsages);-void web_rust_crypto_normalized_key_usages(ReadonlySpan<KeyUsage>, void*, ReceiveKeyUsages);-using ReceiveEncodedBytes = void (*)(void*, ReadonlyBytes);int web_crypto_encode_base64url(ReadonlyBytes, ReceiveEncodedBytes, void*);-int web_rust_crypto_base64_url_bytes_encode(ReadonlyBytes, FlatPtr*);enum class Base64DecodeResult : u8 {Success,@@ -59,8 +49,7 @@ enum class Base64DecodeResult : u8 {InvalidBase64,NonAscii,};-Base64DecodeResult web_crypto_decode_base64url(FlatPtr, ByteBuffer*, void*, ReceiveEncodedBytes, FlatPtr*);-Base64DecodeResult web_rust_crypto_base64_url_bytes_decode(FlatPtr, ByteBuffer*, FlatPtr*);+Base64DecodeResult web_crypto_decode_base64url(FlatPtr, void*, ReceiveEncodedBytes, FlatPtr*);enum class Asn1Structure : u8 {SubjectPublicKeyInfo,@@ -68,24 +57,8 @@ enum class Asn1Structure : u8 {OctetString,};FlatPtr web_crypto_decode_asn1_structure(ReadonlyBytes, Asn1Structure, void*, bool*);-FlatPtr web_rust_crypto_parse_an_asn1_structure(ReadonlyBytes, Asn1Structure, bool, void*);-}--static void receive_key_usages(void* state, ReadonlySpan<KeyUsage> usages)-{- *static_cast<Vector<KeyUsage>*>(state) = Vector<KeyUsage>(usages);-}--Vector<KeyUsage> normalized_key_usages(ReadonlySpan<KeyUsage> usages)-{- Vector<KeyUsage> result;- web_rust_crypto_normalized_key_usages(usages, &result, receive_key_usages);- return result;}-// Out of line to ensure this class has a key function-AlgorithmMethods::~AlgorithmMethods() = default;-int web_crypto_encode_base64url(ReadonlyBytes bytes, ReceiveEncodedBytes receive, void* state){auto encoded = encode_base64url(bytes, AK::OmitPadding::Yes);@@ -95,29 +68,7 @@ int web_crypto_encode_base64url(ReadonlyBytes bytes, ReceiveEncodedBytes receivereturn 0;}-static ErrorOr<Utf16String> base64_url_bytes_encode(ReadonlyBytes bytes)-{- FlatPtr encoded = 0;- if (auto error = web_rust_crypto_base64_url_bytes_encode(bytes, &encoded); error != 0)- return Error::from_errno(error);- return Utf16String::adopt_raw(encoded);-}--ErrorOr<Utf16String> base64_url_uint_encode(::Crypto::UnsignedBigInteger integer)-{- // The representation of a positive or zero integer value as the- // base64url encoding of the value's unsigned big-endian- // representation as an octet sequence. The octet sequence MUST- // utilize the minimum number of octets needed to represent the- // value. Zero is represented as BASE64URL(single zero-valued- // octet), which is "AA".-- auto bytes = TRY(ByteBuffer::create_uninitialized(integer.byte_length()));- auto result = integer.export_data(bytes.span());- return TRY(base64_url_bytes_encode(result));-}--Base64DecodeResult web_crypto_decode_base64url(FlatPtr raw, ByteBuffer* bytes, void* state, ReceiveEncodedBytes receive, FlatPtr* error_message)+Base64DecodeResult web_crypto_decode_base64url(FlatPtr raw, void* state, ReceiveEncodedBytes receive, FlatPtr* error_message){auto base64_url_string = Utf16String::from_raw(raw);auto base64_bytes_or_error = decode_base64url(base64_url_string.to_byte_string(), AK::LastChunkHandling::Loose);@@ -127,37 +78,10 @@ Base64DecodeResult web_crypto_decode_base64url(FlatPtr raw, ByteBuffer* bytes, v*error_message = Utf16String::formatted("{}", base64_bytes_or_error.release_error()).into_raw();return Base64DecodeResult::InvalidBase64;}- if (receive)- receive(state, base64_bytes_or_error.value());- else- *bytes = base64_bytes_or_error.release_value();+ receive(state, base64_bytes_or_error.value());return Base64DecodeResult::Success;}-WebIDL::ExceptionOr<ByteBuffer> base64_url_bytes_decode(JS::Realm& realm, Utf16String const& base64_url_string)-{- auto& vm = realm.vm();- ByteBuffer bytes;- FlatPtr error_message = 0;- switch (web_rust_crypto_base64_url_bytes_decode(base64_url_string.raw_identity(), &bytes, &error_message)) {- case Base64DecodeResult::Success:- return bytes;- case Base64DecodeResult::NonAscii:- return WebIDL::DataError::create(realm, "base64 decode: invalid base64url"_utf16);- case Base64DecodeResult::OutOfMemory:- return vm.throw_completion<JS::InternalError>(vm.error_message(::JS::VM::ErrorMessage::OutOfMemory));- case Base64DecodeResult::InvalidBase64:- return WebIDL::DataError::create(Utf16String::adopt_raw(error_message));- }- VERIFY_NOT_REACHED();-}--WebIDL::ExceptionOr<::Crypto::UnsignedBigInteger> base64_url_uint_decode(JS::Realm& realm, Utf16String const& base64_url_string)-{- auto base64_bytes_be = TRY(base64_url_bytes_decode(realm, base64_url_string));- return ::Crypto::UnsignedBigInteger::import_data(base64_bytes_be);-}-FlatPtr web_crypto_decode_asn1_structure(ReadonlyBytes data, Asn1Structure structure, void* out, bool* all_consumed){::Crypto::ASN1::Decoder decoder(data);@@ -188,35 +112,6 @@ FlatPtr web_crypto_decode_asn1_structure(ReadonlyBytes data, Asn1Structure strucreturn 0;}-static WebIDL::ExceptionOr<::Crypto::PK::RSAPrivateKey> parse_jwk_rsa_private_key(JS::Realm& realm, JsonWebKey const& jwk)-{- auto n = TRY(base64_url_uint_decode(realm, *jwk.n));- auto d = TRY(base64_url_uint_decode(realm, *jwk.d));- auto e = TRY(base64_url_uint_decode(realm, *jwk.e));-- // We know that if any of the extra parameters are provided, all of them must be- if (!jwk.p.has_value())- return ::Crypto::PK::RSAPrivateKey(move(n), move(d), move(e));-- auto p = TRY(base64_url_uint_decode(realm, *jwk.p));- auto q = TRY(base64_url_uint_decode(realm, *jwk.q));- auto dp = TRY(base64_url_uint_decode(realm, *jwk.dp));- auto dq = TRY(base64_url_uint_decode(realm, *jwk.dq));- auto qi = TRY(base64_url_uint_decode(realm, *jwk.qi));-- return ::Crypto::PK::RSAPrivateKey(move(n), move(d), move(e), move(p), move(q), move(dp), move(dq), move(qi));-}--static WebIDL::ExceptionOr<::Crypto::PK::RSAPublicKey> parse_jwk_rsa_public_key(JS::Realm& realm, JsonWebKey const& jwk)-{- auto e = TRY(base64_url_uint_decode(realm, *jwk.e));- auto n = TRY(base64_url_uint_decode(realm, *jwk.n));-- return ::Crypto::PK::RSAPublicKey(move(n), move(e));-}--AlgorithmParams::~AlgorithmParams() = default;-extern "C" {void* web_crypto_asn1_allocate_key_info(Asn1Structure);void web_crypto_asn1_delete_key_info(Asn1Structure, void*);@@ -229,9 +124,9 @@ bool web_crypto_rsa_validate_modulus_length(u32);bool web_crypto_rsa_generate_key_pair(u32, ReadonlyBytes, CryptoKey::InternalKeyData**, CryptoKey::InternalKeyData**);bool web_crypto_rsa_export_public_exponent(ReadonlyBytes, void*, ReceiveEncodedBytes);bool web_crypto_rsa_read_key_metadata(CryptoKey::InternalKeyData const*, u32*, void*, ReceiveEncodedBytes);-JSCompletion web_crypto_rsa_parse_jwk_key(JS::Realm*, bool, ReadonlySpan<FlatPtr>, CryptoKey::InternalKeyData**);+CryptoKey::InternalKeyData* web_crypto_rsa_key_from_jwk_components(bool, ReadonlySpan<ReadonlyBytes>);bool web_crypto_rsa_export_der(CryptoKey::InternalKeyData const*, bool, void*, ReceiveEncodedBytes);-FlatPtr web_crypto_rsa_export_jwk_integer(CryptoKey::InternalKeyData const*, u8);+bool web_crypto_rsa_export_jwk_integer(CryptoKey::InternalKeyData const*, u8, void*, ReceiveEncodedBytes);bool web_crypto_rsa_oaep_cipher(bool, ::Crypto::Hash::HashKind, CryptoKey::InternalKeyData const*, ReadonlyBytes, ReadonlyBytes, void*, ReceiveEncodedBytes);bool web_crypto_rsa_pss_sign(::Crypto::Hash::HashKind, CryptoKey::InternalKeyData const*, u32, ReadonlyBytes, void*, ReceiveEncodedBytes);bool web_crypto_rsa_pss_verify(::Crypto::Hash::HashKind, CryptoKey::InternalKeyData const*, u32, ReadonlyBytes, ReadonlyBytes, bool*);@@ -352,34 +247,23 @@ bool web_crypto_rsa_read_key_metadata(CryptoKey::InternalKeyData const* key, u32return true;}-JSCompletion web_crypto_rsa_parse_jwk_key(JS::Realm* realm, bool is_private, ReadonlySpan<FlatPtr> components, CryptoKey::InternalKeyData** out)+CryptoKey::InternalKeyData* web_crypto_rsa_key_from_jwk_components(bool is_private, ReadonlySpan<ReadonlyBytes> components){- auto component = [&](size_t index) -> Optional<Utf16String> {- if (!components[index])- return {};- return Utf16String::from_raw(components[index]);- };- JsonWebKey jwk;- jwk.n = component(0);- jwk.e = component(1);- jwk.d = component(2);- jwk.p = component(3);- jwk.q = component(4);- jwk.dp = component(5);- jwk.dq = component(6);- jwk.qi = component(7);- if (is_private) {- auto result = parse_jwk_rsa_private_key(*realm, jwk);- if (result.is_exception())- return Bindings::completion_to_abi(*realm, result.release_error());- *out = new CryptoKey::InternalKeyData(result.release_value());- } else {- auto result = parse_jwk_rsa_public_key(*realm, jwk);- if (result.is_exception())- return Bindings::completion_to_abi(*realm, result.release_error());- *out = new CryptoKey::InternalKeyData(result.release_value());- }- return JS::HostABI::normal_completion_to_abi(0);+ auto n = ::Crypto::UnsignedBigInteger::import_data(components[0]);+ auto e = ::Crypto::UnsignedBigInteger::import_data(components[1]);+ if (!is_private)+ return new CryptoKey::InternalKeyData(::Crypto::PK::RSAPublicKey(move(n), move(e)));++ auto d = ::Crypto::UnsignedBigInteger::import_data(components[2]);+ if (components.size() == 3)+ return new CryptoKey::InternalKeyData(::Crypto::PK::RSAPrivateKey(move(n), move(d), move(e)));++ auto p = ::Crypto::UnsignedBigInteger::import_data(components[3]);+ auto q = ::Crypto::UnsignedBigInteger::import_data(components[4]);+ auto dp = ::Crypto::UnsignedBigInteger::import_data(components[5]);+ auto dq = ::Crypto::UnsignedBigInteger::import_data(components[6]);+ auto qi = ::Crypto::UnsignedBigInteger::import_data(components[7]);+ return new CryptoKey::InternalKeyData(::Crypto::PK::RSAPrivateKey(move(n), move(d), move(e), move(p), move(q), move(dp), move(dq), move(qi)));}bool web_crypto_rsa_export_der(CryptoKey::InternalKeyData const* key, bool is_public, void* state, ReceiveEncodedBytes receive)@@ -393,7 +277,7 @@ bool web_crypto_rsa_export_der(CryptoKey::InternalKeyData const* key, bool is_pureturn true;}-FlatPtr web_crypto_rsa_export_jwk_integer(CryptoKey::InternalKeyData const* key, u8 component)+bool web_crypto_rsa_export_jwk_integer(CryptoKey::InternalKeyData const* key, u8 component, void* state, ReceiveEncodedBytes receive){auto const& integer = key->visit([&](::Crypto::PK::RSAPublicKey const& public_key) -> ::Crypto::UnsignedBigInteger const& {@@ -422,10 +306,11 @@ FlatPtr web_crypto_rsa_export_jwk_integer(CryptoKey::InternalKeyData const* key,VERIFY_NOT_REACHED();},[](auto const&) -> ::Crypto::UnsignedBigInteger const& { VERIFY_NOT_REACHED(); });- auto result = base64_url_uint_encode(integer);- if (result.is_error())- return 0;- return result.release_value().into_raw();+ auto bytes = ByteBuffer::create_uninitialized(integer.byte_length());+ if (bytes.is_error())+ return false;+ receive(state, integer.export_data(bytes.value().span()));+ return true;}bool web_crypto_rsa_oaep_cipher(bool encrypt, ::Crypto::Hash::HashKind hash_kind, CryptoKey::InternalKeyData const* key, ReadonlyBytes label, ReadonlyBytes input, void* state, ReceiveEncodedBytes receive)@@ -1296,4 +1181,58 @@ bool web_crypto_kmac_sign(::Crypto::Authentication::KMACKind kind, ReadonlyBytesreturn true;}+extern "C" CryptoKey::InternalKeyData* web_crypto_public_key_for_private_key(CryptoKey::InternalKeyData const*, FlatPtr name, FlatPtr named_curve);++CryptoKey::InternalKeyData* web_crypto_public_key_for_private_key(CryptoKey::InternalKeyData const* key, FlatPtr raw_name, FlatPtr raw_named_curve)+{+ auto result = key->visit(+ [](::Crypto::PK::RSAPrivateKey const& private_key) -> ErrorOr<CryptoKey::InternalKeyData> {+ return ::Crypto::PK::RSAPublicKey { private_key.modulus(), private_key.public_exponent() };+ },+ [&](::Crypto::PK::ECPrivateKey const& private_key) -> ErrorOr<CryptoKey::InternalKeyData> {+ if (private_key.public_key().has_value())+ return *private_key.public_key();++ VERIFY(raw_named_curve);+ auto named_curve = Utf16String::from_raw(raw_named_curve);+ auto point = TRY([&] -> ErrorOr<::Crypto::Curves::SECPxxxr1Point> {+ if (named_curve == "P-256"_utf16)+ return ::Crypto::Curves::SECP256r1 {}.generate_public_key(private_key.d());+ if (named_curve == "P-384"_utf16)+ return ::Crypto::Curves::SECP384r1 {}.generate_public_key(private_key.d());+ if (named_curve == "P-521"_utf16)+ return ::Crypto::Curves::SECP521r1 {}.generate_public_key(private_key.d());+ return Error::from_string_literal("Unsupported named curve");+ }());+ return ::Crypto::PK::ECPublicKey { move(point) };+ },+ [](::Crypto::PK::MLDSAPrivateKey const& private_key) -> ErrorOr<CryptoKey::InternalKeyData> {+ return ::Crypto::PK::MLDSAPublicKey { private_key.public_key() };+ },+ [](::Crypto::PK::MLKEMPrivateKey const& private_key) -> ErrorOr<CryptoKey::InternalKeyData> {+ return ::Crypto::PK::MLKEMPublicKey { private_key.public_key() };+ },+ [&](OKPPrivateKey const& private_key) -> ErrorOr<CryptoKey::InternalKeyData> {+ auto name = Utf16String::from_raw(raw_name);+ auto public_key = TRY([&] -> ErrorOr<ByteBuffer> {+ if (name == "Ed25519"_utf16)+ return ::Crypto::Curves::Ed25519 {}.generate_public_key(private_key.bytes);+ if (name == "Ed448"_utf16)+ return ::Crypto::Curves::Ed448 {}.generate_public_key(private_key.bytes);+ if (name == "X25519"_utf16)+ return ::Crypto::Curves::X25519 {}.generate_public_key(private_key.bytes);+ if (name == "X448"_utf16)+ return ::Crypto::Curves::X448 {}.generate_public_key(private_key.bytes);+ return Error::from_string_literal("Unsupported algorithm");+ }());+ return OKPPublicKey { move(public_key) };+ },+ [](auto const&) -> ErrorOr<CryptoKey::InternalKeyData> {+ return Error::from_string_literal("Key is not a private key");+ });+ if (result.is_error())+ return nullptr;+ return new CryptoKey::InternalKeyData(result.release_value());+}+}diff --git a/Libraries/LibWeb/Crypto/CryptoAlgorithms.h b/Libraries/LibWeb/Crypto/CryptoAlgorithms.hdeleted file mode 100644index 87094fc9017..00000000000--- a/Libraries/LibWeb/Crypto/CryptoAlgorithms.h+++ /dev/null@@ -1,152 +0,0 @@-/*- * Copyright (c) 2024, Andrew Kaster <[email protected]>- * Copyright (c) 2024, stelar7 <[email protected]>- * Copyright (c) 2024, Jelle Raaijmakers <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/EnumBits.h>-#include <AK/String.h>-#include <AK/Utf16String.h>-#include <LibCrypto/BigInt/UnsignedBigInteger.h>-#include <LibGC/Forward.h>-#include <LibGC/Ptr.h>-#include <LibJS/Forward.h>-#include <LibWeb/Crypto/CryptoBindings.h>-#include <LibWeb/Crypto/CryptoKey.h>-#include <LibWeb/WebIDL/Buffers.h>-#include <LibWeb/WebIDL/ExceptionOr.h>-#include <LibWebCommon/WebIDL/Types.h>--namespace Web::Crypto {--using NamedCurve = Utf16String;-using ExportKeyResult = Variant<ByteBuffer, JsonWebKey>;--// https://wicg.github.io/webcrypto-modern-algos/#encapsulation-struct EncapsulatedBits {- Optional<ByteBuffer> shared_key;- Optional<ByteBuffer> ciphertext;-};--// https://w3c.github.io/webcrypto/#algorithm-overview-struct AlgorithmParams {- AK_ALLOC_WITH_KMALLOC;-- virtual ~AlgorithmParams();- explicit AlgorithmParams()- {- }-- // NOTE: this is initialized when normalizing the algorithm name as the spec requests.- // It must not be set in `from_value`.- Utf16String name;-};--class AlgorithmMethods {-public:- AK_ALLOC_WITH_KMALLOC;-- virtual ~AlgorithmMethods();-- virtual WebIDL::ExceptionOr<ByteBuffer> encrypt(JS::Realm&, AlgorithmParams const&, GC::Ref<CryptoKey>, ByteBuffer const&)- {- return WebIDL::NotSupportedError::create("encrypt is not supported"_utf16);- }-- virtual WebIDL::ExceptionOr<ByteBuffer> decrypt(JS::Realm&, AlgorithmParams const&, GC::Ref<CryptoKey>, ByteBuffer const&)- {- return WebIDL::NotSupportedError::create("decrypt is not supported"_utf16);- }-- virtual WebIDL::ExceptionOr<ByteBuffer> sign(JS::Realm&, AlgorithmParams const&, GC::Ref<CryptoKey>, ByteBuffer const&)- {- return WebIDL::NotSupportedError::create("sign is not supported"_utf16);- }-- virtual WebIDL::ExceptionOr<bool> verify(JS::Realm&, AlgorithmParams const&, GC::Ref<CryptoKey>, ByteBuffer const&, ByteBuffer const&)- {- return WebIDL::NotSupportedError::create("verify is not supported"_utf16);- }-- virtual WebIDL::ExceptionOr<ByteBuffer> derive_bits(JS::Realm&, AlgorithmParams const&, GC::Ref<CryptoKey>, Optional<u32>)- {- return WebIDL::NotSupportedError::create("deriveBits is not supported"_utf16);- }-- virtual WebIDL::ExceptionOr<GC::Ref<CryptoKey>> import_key(JS::Realm&, AlgorithmParams const&, KeyFormat, CryptoKey::ImportKeyData, bool, Vector<KeyUsage> const&)- {- return WebIDL::NotSupportedError::create("importKey is not supported"_utf16);- }-- virtual WebIDL::ExceptionOr<Variant<GC::Ref<CryptoKey>, CryptoKeyPair>> generate_key(JS::Realm&, AlgorithmParams const&, bool, Vector<KeyUsage> const&)- {- return WebIDL::NotSupportedError::create("generateKey is not supported"_utf16);- }-- virtual WebIDL::ExceptionOr<ExportKeyResult> export_key(JS::Realm&, KeyFormat, GC::Ref<CryptoKey>)- {- return WebIDL::NotSupportedError::create("exportKey is not supported"_utf16);- }-- virtual WebIDL::ExceptionOr<Optional<u32>> get_key_length(JS::Realm&, AlgorithmParams const&)- {- return WebIDL::NotSupportedError::create("getKeyLength is not supported"_utf16);- }-- virtual WebIDL::ExceptionOr<u32> get_shared_key_length(AlgorithmParams const&) const- {- return WebIDL::NotSupportedError::create("getSharedKeyLength is not supported"_utf16);- }-- virtual WebIDL::ExceptionOr<ByteBuffer> wrap_key(JS::Realm&, AlgorithmParams const&, GC::Ref<CryptoKey>, ByteBuffer const&)- {- return WebIDL::NotSupportedError::create("wrapKey is not supported"_utf16);- }-- virtual WebIDL::ExceptionOr<ByteBuffer> unwrap_key(JS::Realm&, AlgorithmParams const&, GC::Ref<CryptoKey>, ByteBuffer const&)- {- return WebIDL::NotSupportedError::create("unwwrapKey is not supported"_utf16);- }-- virtual WebIDL::ExceptionOr<EncapsulatedBits> encapsulate(JS::Realm&, AlgorithmParams const&, GC::Ref<CryptoKey>)- {- return WebIDL::NotSupportedError::create("encapsulate is not supported"_utf16);- }-- virtual WebIDL::ExceptionOr<ByteBuffer> decapsulate(JS::Realm&, AlgorithmParams const&, GC::Ref<CryptoKey>, ByteBuffer const&)- {- return WebIDL::NotSupportedError::create("decalpsulate is not supported"_utf16);- }-- virtual WebIDL::ExceptionOr<void> validate_encrypt_parameters(AlgorithmParams const&) const { return {}; }- virtual WebIDL::ExceptionOr<void> validate_decrypt_parameters(AlgorithmParams const&) const { return {}; }- virtual WebIDL::ExceptionOr<void> validate_sign_parameters(AlgorithmParams const&) const { return {}; }- virtual WebIDL::ExceptionOr<void> validate_verify_parameters(AlgorithmParams const&) const { return {}; }- virtual WebIDL::ExceptionOr<void> validate_generate_key_parameters(AlgorithmParams const&) const { return {}; }- virtual WebIDL::ExceptionOr<void> validate_import_key_parameters(AlgorithmParams const&) const { return {}; }- virtual WebIDL::ExceptionOr<void> validate_derive_bits_parameters(AlgorithmParams const&, Optional<u32>) const { return {}; }-- virtual Optional<ReadonlySpan<KeyUsage>> public_key_usages() const { return {}; }-- static NonnullOwnPtr<AlgorithmMethods> create() { return adopt_own(*new AlgorithmMethods); }--protected:- AlgorithmMethods() = default;-};--// https://wicg.github.io/webcrypto-modern-algos/#cshake-params-// https://wicg.github.io/webcrypto-modern-algos/#dfn-AeadParams-// NOTE: The AeadParams dictionary is identical to the AesGcmParams-Vector<KeyUsage> normalized_key_usages(ReadonlySpan<KeyUsage>);--ErrorOr<Utf16String> base64_url_uint_encode(::Crypto::UnsignedBigInteger);-WebIDL::ExceptionOr<ByteBuffer> base64_url_bytes_decode(JS::Realm&, Utf16String const& base64_url_string);-WebIDL::ExceptionOr<::Crypto::UnsignedBigInteger> base64_url_uint_decode(JS::Realm&, Utf16String const& base64_url_string);--}--GC_UNTRACED_CAPTURE(Web::Crypto::EncapsulatedBits);diff --git a/Libraries/LibWeb/Crypto/CryptoBindings.cpp b/Libraries/LibWeb/Crypto/CryptoBindings.cppdeleted file mode 100644index 1c95e4ae913..00000000000--- a/Libraries/LibWeb/Crypto/CryptoBindings.cpp+++ /dev/null@@ -1,23 +0,0 @@-/*- * Copyright (c) 2024, Andrew Kaster <[email protected]>- * Copyright (c) 2024, Altomani Gianluca <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibJS/HostClassBuilder.h>-#include <LibWeb/Crypto/CryptoKey.h>--namespace Web::Crypto {--extern "C" JSCompletion web_rust_crypto_key_from_value(JSVM*, JSValue, CryptoKey**);--JS::ThrowCompletionOr<GC::Ref<CryptoKey>> crypto_key_from_value(JS::VM& vm, JS::Value value)-{- CryptoKey* key = nullptr;- TRY(JS::HostABI::completion_from_abi<void>(web_rust_crypto_key_from_value(- JS::HostABI::vm_to_abi(vm), JS::HostABI::value_to_abi(value), &key)));- return GC::Ref { *key };-}--}diff --git a/Libraries/LibWeb/Crypto/CryptoBindings.h b/Libraries/LibWeb/Crypto/CryptoBindings.hdeleted file mode 100644index 661f32ee213..00000000000--- a/Libraries/LibWeb/Crypto/CryptoBindings.h+++ /dev/null@@ -1,52 +0,0 @@-/*- * Copyright (c) 2023, stelar7 <[email protected]>- * Copyright (c) 2024, Andrew Kaster <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/Optional.h>-#include <AK/String.h>-#include <AK/Utf16String.h>-#include <AK/Vector.h>-#include <LibWeb/Bindings/SubtleCrypto.h>-#include <LibWeb/WebIDL/ExceptionOr.h>--namespace Web::Crypto {--using KeyFormat = Bindings::KeyFormat;--struct RsaOtherPrimesInfo {- Optional<Utf16String> d {};- Optional<Utf16String> r {};- Optional<Utf16String> t {};-};--struct JsonWebKey {- Optional<Utf16String> alg {};- Optional<Utf16String> crv {};- Optional<Utf16String> d {};- Optional<Utf16String> dp {};- Optional<Utf16String> dq {};- Optional<Utf16String> e {};- Optional<bool> ext {};- Optional<Utf16String> k {};- Optional<Vector<Utf16String>> key_ops {};- Optional<Utf16String> kty {};- Optional<Utf16String> n {};- Optional<Vector<RsaOtherPrimesInfo>> oth {};- Optional<Utf16String> p {};- Optional<Utf16String> priv {};- Optional<Utf16String> pub {};- Optional<Utf16String> q {};- Optional<Utf16String> qi {};- Optional<Utf16String> use {};- Optional<Utf16String> x {};- Optional<Utf16String> y {};-};--JS::ThrowCompletionOr<GC::Ref<CryptoKey>> crypto_key_from_value(JS::VM&, JS::Value);--}diff --git a/Libraries/LibWeb/Crypto/CryptoKey.cpp b/Libraries/LibWeb/Crypto/CryptoKey.cppindex 53291b8f0ad..7ddc28a016e 100644--- a/Libraries/LibWeb/Crypto/CryptoKey.cpp+++ b/Libraries/LibWeb/Crypto/CryptoKey.cpp@@ -185,28 +185,12 @@ void CryptoKey::set_type(KeyType type)web_rust_crypto_key_set_type(this, to_underlying(type));}-CryptoKey::InternalAlgorithmData CryptoKey::internal_algorithm() const+CryptoKey::EcKeyAlgorithmData CryptoKey::ec_algorithm() const{CryptoKeyAlgorithmFields fields;web_rust_crypto_key_get_algorithm(this, &fields);- auto name = Utf16String::from_raw(fields.name);- switch (static_cast<SerializedKeyAlgorithmType>(fields.type)) {- case SerializedKeyAlgorithmType::Key:- return KeyAlgorithmData { move(name) };- case SerializedKeyAlgorithmType::Rsa:- return RsaKeyAlgorithmData { move(name), fields.modulus_length, MUST(ByteBuffer::copy(fields.public_exponent)) };- case SerializedKeyAlgorithmType::RsaHashed:- return RsaHashedKeyAlgorithmData { move(name), fields.modulus_length, MUST(ByteBuffer::copy(fields.public_exponent)), Utf16String::from_raw(fields.hash) };- case SerializedKeyAlgorithmType::Ec:- return EcKeyAlgorithmData { move(name), Utf16String::from_raw(fields.named_curve) };- case SerializedKeyAlgorithmType::Aes:- return AesKeyAlgorithmData { move(name), static_cast<u16>(fields.length) };- case SerializedKeyAlgorithmType::Hmac:- return HmacKeyAlgorithmData { move(name), Utf16String::from_raw(fields.hash), fields.length };- case SerializedKeyAlgorithmType::Kmac:- return KmacKeyAlgorithmData { move(name), fields.length };- }- VERIFY_NOT_REACHED();+ VERIFY(fields.type == to_underlying(SerializedKeyAlgorithmType::Ec));+ return { Utf16String::from_raw(fields.name), Utf16String::from_raw(fields.named_curve) };}Vector<KeyUsage> CryptoKey::internal_usages() constdiff --git a/Libraries/LibWeb/Crypto/CryptoKey.h b/Libraries/LibWeb/Crypto/CryptoKey.hindex 0ef204dbbf3..b32bd39dc31 100644--- a/Libraries/LibWeb/Crypto/CryptoKey.h+++ b/Libraries/LibWeb/Crypto/CryptoKey.h@@ -14,7 +14,6 @@#include <LibJS/Forward.h>#include <LibWeb/Bindings/CryptoKey.h>#include <LibWeb/Bindings/RustInterface.h>-#include <LibWeb/Crypto/CryptoBindings.h>#include <LibWebCommon/WebIDL/Types.h>namespace Web::Bindings {@@ -46,7 +45,6 @@ class WEB_API CryptoKey final : public Bindings::RustInterfaceCell {WEB_RUST_INTERFACE(CryptoKey, crypto_key)public:- using ImportKeyData = Variant<ByteBuffer, JsonWebKey>;using InternalKeyData = Variant<ByteBuffer, ::Crypto::PK::RSAPublicKey, ::Crypto::PK::RSAPrivateKey, ::Crypto::PK::ECPublicKey, ::Crypto::PK::ECPrivateKey, ::Crypto::PK::MLDSAPublicKey, ::Crypto::PK::MLDSAPrivateKey, ::Crypto::PK::MLKEMPublicKey, ::Crypto::PK::MLKEMPrivateKey, OKPPublicKey, OKPPrivateKey>;struct KeyAlgorithmData {@@ -118,10 +116,8 @@ public:bool extractable() const;KeyType type() const;- InternalAlgorithmData internal_algorithm() const;Vector<KeyUsage> internal_usages() const;- RsaHashedKeyAlgorithmData rsa_hashed_algorithm() const { return internal_algorithm().get<RsaHashedKeyAlgorithmData>(); }- EcKeyAlgorithmData ec_algorithm() const { return internal_algorithm().get<EcKeyAlgorithmData>(); }+ EcKeyAlgorithmData ec_algorithm() const;void set_extractable(bool);void set_type(KeyType);@@ -132,11 +128,6 @@ public:Utf16String algorithm_name() const;};-struct CryptoKeyPair {- GC::Ref<CryptoKey> public_key;- GC::Ref<CryptoKey> private_key;-};-}namespace Web::Bindings {diff --git a/Libraries/LibWeb/Crypto/SubtleCrypto.cpp b/Libraries/LibWeb/Crypto/SubtleCrypto.cppdeleted file mode 100644index abfaa9b6693..00000000000--- a/Libraries/LibWeb/Crypto/SubtleCrypto.cpp+++ /dev/null@@ -1,498 +0,0 @@-/*- * Copyright (c) 2021-2022, Linus Groh <[email protected]>- * Copyright (c) 2023-2024, stelar7 <[email protected]>- * Copyright (c) 2024, Jelle Raaijmakers <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibCrypto/Curves/EdwardsCurve.h>-#include <LibCrypto/Curves/SECPxxxr1.h>-#include <LibJS/HostClassBuilder.h>-#include <LibJS/Runtime/Realm.h>-#include <LibWeb/Bindings/RustSerialization.h>-#include <LibWeb/Crypto/SubtleCrypto.h>--namespace Web::Crypto {--enum class AlgorithmId : u8 {- MLKEM = 1,-};--enum class ParameterId : u8 {- AlgorithmParams,-};--struct RawRsaOtherPrimesInfo {- FlatPtr d;- FlatPtr r;- FlatPtr t;-};--struct RawJsonWebKey {- FlatPtr alg;- FlatPtr crv;- FlatPtr d;- FlatPtr dp;- FlatPtr dq;- FlatPtr e;- FlatPtr k;- FlatPtr kty;- FlatPtr n;- FlatPtr p;- FlatPtr priv;- FlatPtr pub;- FlatPtr q;- FlatPtr qi;- FlatPtr use;- FlatPtr x;- FlatPtr y;- u8 ext;- bool has_key_ops;- ReadonlySpan<FlatPtr> key_ops;- bool has_oth;- ReadonlySpan<RawRsaOtherPrimesInfo> oth;-};--struct OptionalLength {- bool has_value;- u32 value;-- Optional<u32> to_optional() const- {- if (has_value)- return value;- return {};- }-};--using ReceiveBytes = void (*)(void*, ReadonlyBytes);-using ReceiveJsonWebKey = void (*)(void*, RawJsonWebKey const&);-using ReceiveUsages = void (*)(void*, ReadonlySpan<KeyUsage>);--extern "C" {-JSCompletion web_crypto_algorithm_from_value(JS::Realm*, AlgorithmId, ParameterId, JSValue, FlatPtr, NormalizedAlgorithmAndParameter**);-void web_crypto_algorithm_destroy(NormalizedAlgorithmAndParameter*);-void web_crypto_algorithm_public_key_usages(NormalizedAlgorithmAndParameter const*, void*, ReceiveUsages);-CryptoKey* web_crypto_public_key_for_private_key(CryptoKey const*);-JSCompletion web_crypto_algorithm_encrypt(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, CryptoKey* key, ReadonlyBytes data, void* state, ReceiveBytes receive);-JSCompletion web_crypto_algorithm_decrypt(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, CryptoKey* key, ReadonlyBytes data, void* state, ReceiveBytes receive);-JSCompletion web_crypto_algorithm_sign(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, CryptoKey* key, ReadonlyBytes data, void* state, ReceiveBytes receive);-JSCompletion web_crypto_algorithm_verify(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, CryptoKey* key, ReadonlyBytes signature, ReadonlyBytes data, bool* out);-JSCompletion web_crypto_algorithm_derive_bits(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, CryptoKey* key, OptionalLength length, void* state, ReceiveBytes receive);-JSCompletion web_crypto_algorithm_import_key(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, KeyFormat format, ReadonlyBytes key_data, RawJsonWebKey const* jwk, bool extractable, ReadonlySpan<KeyUsage> usages, CryptoKey** out);-JSCompletion web_crypto_algorithm_generate_key(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, bool extractable, ReadonlySpan<KeyUsage> usages, CryptoKey** out_key, CryptoKey** out_public_key, CryptoKey** out_private_key);-JSCompletion web_crypto_algorithm_export_key(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, KeyFormat format, CryptoKey* key, void* state, ReceiveBytes receive_bytes, ReceiveJsonWebKey receive_jwk);-JSCompletion web_crypto_algorithm_get_key_length(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, OptionalLength* out);-JSCompletion web_crypto_algorithm_get_shared_key_length(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, u32* out);-JSCompletion web_crypto_algorithm_wrap_key(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, CryptoKey* key, ReadonlyBytes data, void* state, ReceiveBytes receive);-JSCompletion web_crypto_algorithm_unwrap_key(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, CryptoKey* key, ReadonlyBytes data, void* state, ReceiveBytes receive);-JSCompletion web_crypto_algorithm_encapsulate(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, CryptoKey* key, void* shared_key, void* ciphertext, ReceiveBytes receive);-JSCompletion web_crypto_algorithm_decapsulate(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, CryptoKey* key, ReadonlyBytes data, void* state, ReceiveBytes receive);-JSCompletion web_crypto_algorithm_validate_encrypt_parameters(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm);-JSCompletion web_crypto_algorithm_validate_decrypt_parameters(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm);-JSCompletion web_crypto_algorithm_validate_sign_parameters(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm);-JSCompletion web_crypto_algorithm_validate_verify_parameters(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm);-JSCompletion web_crypto_algorithm_validate_generate_key_parameters(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm);-JSCompletion web_crypto_algorithm_validate_import_key_parameters(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm);-JSCompletion web_crypto_algorithm_validate_derive_bits_parameters(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, OptionalLength length);-}--static Optional<Utf16String> string_from_raw(FlatPtr raw)-{- if (raw)- return Utf16String::from_raw(raw);- return {};-}--static JsonWebKey json_web_key_from_raw(RawJsonWebKey const& raw)-{- JsonWebKey key;- key.alg = string_from_raw(raw.alg);- key.crv = string_from_raw(raw.crv);- key.d = string_from_raw(raw.d);- key.dp = string_from_raw(raw.dp);- key.dq = string_from_raw(raw.dq);- key.e = string_from_raw(raw.e);- key.k = string_from_raw(raw.k);- key.kty = string_from_raw(raw.kty);- key.n = string_from_raw(raw.n);- key.p = string_from_raw(raw.p);- key.priv = string_from_raw(raw.priv);- key.pub = string_from_raw(raw.pub);- key.q = string_from_raw(raw.q);- key.qi = string_from_raw(raw.qi);- key.use = string_from_raw(raw.use);- key.x = string_from_raw(raw.x);- key.y = string_from_raw(raw.y);- if (raw.ext)- key.ext = raw.ext == 2;- if (raw.has_key_ops) {- key.key_ops = Vector<Utf16String> {};- for (auto value : raw.key_ops)- key.key_ops->append(Utf16String::from_raw(value));- }- if (raw.has_oth) {- key.oth = Vector<RsaOtherPrimesInfo> {};- for (auto const& prime : raw.oth)- key.oth->append(RsaOtherPrimesInfo { string_from_raw(prime.d), string_from_raw(prime.r), string_from_raw(prime.t) });- }- return key;-}--static FlatPtr raw_string(Optional<Utf16String> const& string)-{- return string.has_value() ? string->raw_identity() : 0;-}--static void with_raw_json_web_key(JsonWebKey const& key, void* state, ReceiveJsonWebKey receive)-{- Vector<FlatPtr> key_ops;- if (key.key_ops.has_value()) {- for (auto const& value : *key.key_ops)- key_ops.append(value.raw_identity());- }- Vector<RawRsaOtherPrimesInfo> oth;- if (key.oth.has_value()) {- for (auto const& prime : *key.oth)- oth.append(RawRsaOtherPrimesInfo { raw_string(prime.d), raw_string(prime.r), raw_string(prime.t) });- }- RawJsonWebKey raw {- raw_string(key.alg),- raw_string(key.crv),- raw_string(key.d),- raw_string(key.dp),- raw_string(key.dq),- raw_string(key.e),- raw_string(key.k),- raw_string(key.kty),- raw_string(key.n),- raw_string(key.p),- raw_string(key.priv),- raw_string(key.pub),- raw_string(key.q),- raw_string(key.qi),- raw_string(key.use),- raw_string(key.x),- raw_string(key.y),- static_cast<u8>(key.ext.has_value() ? (*key.ext ? 2 : 1) : 0),- key.key_ops.has_value(),- key_ops.span(),- key.oth.has_value(),- oth.span(),- };- receive(state, raw);-}--JSCompletion web_crypto_algorithm_from_value(JS::Realm*, AlgorithmId method_id, ParameterId parameter_id, JSValue, FlatPtr name, NormalizedAlgorithmAndParameter** out)-{- auto methods = [&]() -> NonnullOwnPtr<AlgorithmMethods> {- switch (method_id) {- case AlgorithmId::MLKEM:- VERIFY_NOT_REACHED();- }- VERIFY_NOT_REACHED();- }();- auto parameter_or_error = [&]() -> JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> {- switch (parameter_id) {- case ParameterId::AlgorithmParams:- return adopt_own(*new AlgorithmParams {});- }- VERIFY_NOT_REACHED();- }();- if (parameter_or_error.is_error())- return JS::HostABI::throw_completion_to_abi(parameter_or_error.release_error().value());- auto parameter = parameter_or_error.release_value();- VERIFY(parameter->name.is_empty());- parameter->name = Utf16String::from_raw(name);- *out = new NormalizedAlgorithmAndParameter { move(methods), move(parameter) };- return JS::HostABI::normal_completion_to_abi(0);-}--void web_crypto_algorithm_destroy(NormalizedAlgorithmAndParameter* algorithm)-{- delete algorithm;-}--void web_crypto_algorithm_public_key_usages(NormalizedAlgorithmAndParameter const* algorithm, void* state, ReceiveUsages receive)-{- if (auto usages = algorithm->methods->public_key_usages(); usages.has_value())- receive(state, *usages);-}--static ErrorOr<CryptoKey::InternalKeyData> public_key_for_private_key(CryptoKey const& key)-{- return key.handle().visit(- [](::Crypto::PK::RSAPrivateKey const& private_key) -> ErrorOr<CryptoKey::InternalKeyData> {- return ::Crypto::PK::RSAPublicKey { private_key.modulus(), private_key.public_exponent() };- },- [&](::Crypto::PK::ECPrivateKey const& private_key) -> ErrorOr<CryptoKey::InternalKeyData> {- if (private_key.public_key().has_value())- return *private_key.public_key();-- auto algorithm = key.ec_algorithm();- auto const& named_curve = algorithm.named_curve();- auto point = TRY([&] -> ErrorOr<::Crypto::Curves::SECPxxxr1Point> {- if (named_curve == "P-256"_utf16)- return ::Crypto::Curves::SECP256r1 {}.generate_public_key(private_key.d());- if (named_curve == "P-384"_utf16)- return ::Crypto::Curves::SECP384r1 {}.generate_public_key(private_key.d());- if (named_curve == "P-521"_utf16)- return ::Crypto::Curves::SECP521r1 {}.generate_public_key(private_key.d());- return Error::from_string_literal("Unsupported named curve");- }());- return ::Crypto::PK::ECPublicKey { move(point) };- },- [](::Crypto::PK::MLDSAPrivateKey const& private_key) -> ErrorOr<CryptoKey::InternalKeyData> {- return ::Crypto::PK::MLDSAPublicKey { private_key.public_key() };- },- [](::Crypto::PK::MLKEMPrivateKey const& private_key) -> ErrorOr<CryptoKey::InternalKeyData> {- return ::Crypto::PK::MLKEMPublicKey { private_key.public_key() };- },- [&](OKPPrivateKey const& private_key) -> ErrorOr<CryptoKey::InternalKeyData> {- auto const& name = key.algorithm_name();- auto public_key = TRY([&] -> ErrorOr<ByteBuffer> {- if (name == "Ed25519"_utf16)- return ::Crypto::Curves::Ed25519 {}.generate_public_key(private_key.bytes);- if (name == "Ed448"_utf16)- return ::Crypto::Curves::Ed448 {}.generate_public_key(private_key.bytes);- if (name == "X25519"_utf16)- return ::Crypto::Curves::X25519 {}.generate_public_key(private_key.bytes);- if (name == "X448"_utf16)- return ::Crypto::Curves::X448 {}.generate_public_key(private_key.bytes);- return Error::from_string_literal("Unsupported algorithm");- }());- return OKPPublicKey { move(public_key) };- },- [](auto const&) -> ErrorOr<CryptoKey::InternalKeyData> {- return Error::from_string_literal("Key is not a private key");- });-}--CryptoKey* web_crypto_public_key_for_private_key(CryptoKey const* key)-{- auto data = public_key_for_private_key(*key);- if (data.is_error())- return nullptr;- return CryptoKey::create(data.release_value()).ptr();-}--JSCompletion web_crypto_algorithm_encrypt(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, CryptoKey* key, ReadonlyBytes data, void* state, ReceiveBytes receive)-{- auto& realm = *realm_pointer;- auto result = algorithm->methods->encrypt(realm, *algorithm->parameter, *key, MUST(ByteBuffer::copy(data)));- if (result.is_exception())- return Bindings::completion_to_abi(realm, result.release_error());- receive(state, result.value().span());- return JS::HostABI::normal_completion_to_abi(0);-}--JSCompletion web_crypto_algorithm_decrypt(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, CryptoKey* key, ReadonlyBytes data, void* state, ReceiveBytes receive)-{- auto& realm = *realm_pointer;- auto result = algorithm->methods->decrypt(realm, *algorithm->parameter, *key, MUST(ByteBuffer::copy(data)));- if (result.is_exception())- return Bindings::completion_to_abi(realm, result.release_error());- receive(state, result.value().span());- return JS::HostABI::normal_completion_to_abi(0);-}--JSCompletion web_crypto_algorithm_sign(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, CryptoKey* key, ReadonlyBytes data, void* state, ReceiveBytes receive)-{- auto& realm = *realm_pointer;- auto result = algorithm->methods->sign(realm, *algorithm->parameter, *key, MUST(ByteBuffer::copy(data)));- if (result.is_exception())- return Bindings::completion_to_abi(realm, result.release_error());- receive(state, result.value().span());- return JS::HostABI::normal_completion_to_abi(0);-}--JSCompletion web_crypto_algorithm_verify(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, CryptoKey* key, ReadonlyBytes signature, ReadonlyBytes data, bool* out)-{- auto& realm = *realm_pointer;- auto result = algorithm->methods->verify(realm, *algorithm->parameter, *key, MUST(ByteBuffer::copy(signature)), MUST(ByteBuffer::copy(data)));- if (result.is_exception())- return Bindings::completion_to_abi(realm, result.release_error());- *out = result.value();- return JS::HostABI::normal_completion_to_abi(0);-}--JSCompletion web_crypto_algorithm_derive_bits(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, CryptoKey* key, OptionalLength length, void* state, ReceiveBytes receive)-{- auto& realm = *realm_pointer;- auto result = algorithm->methods->derive_bits(realm, *algorithm->parameter, *key, length.to_optional());- if (result.is_exception())- return Bindings::completion_to_abi(realm, result.release_error());- receive(state, result.value().span());- return JS::HostABI::normal_completion_to_abi(0);-}--JSCompletion web_crypto_algorithm_import_key(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, KeyFormat format, ReadonlyBytes key_data, RawJsonWebKey const* jwk, bool extractable, ReadonlySpan<KeyUsage> usages, CryptoKey** out)-{- auto& realm = *realm_pointer;- Vector<KeyUsage> usage_vector;- usage_vector.append(usages.data(), usages.size());- CryptoKey::ImportKeyData data = jwk ? CryptoKey::ImportKeyData { json_web_key_from_raw(*jwk) } : CryptoKey::ImportKeyData { MUST(ByteBuffer::copy(key_data)) };- auto result = algorithm->methods->import_key(realm, *algorithm->parameter, format, move(data), extractable, usage_vector);- if (result.is_exception())- return Bindings::completion_to_abi(realm, result.release_error());- *out = result.value().ptr();- return JS::HostABI::normal_completion_to_abi(0);-}--JSCompletion web_crypto_algorithm_generate_key(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, bool extractable, ReadonlySpan<KeyUsage> usages, CryptoKey** out_key, CryptoKey** out_public_key, CryptoKey** out_private_key)-{- auto& realm = *realm_pointer;- Vector<KeyUsage> usage_vector;- usage_vector.append(usages.data(), usages.size());- auto result = algorithm->methods->generate_key(realm, *algorithm->parameter, extractable, usage_vector);- if (result.is_exception())- return Bindings::completion_to_abi(realm, result.release_error());- result.value().visit(- [&](GC::Ref<CryptoKey> const& key) { *out_key = key.ptr(); },- [&](CryptoKeyPair const& pair) {- *out_public_key = pair.public_key.ptr();- *out_private_key = pair.private_key.ptr();- });- return JS::HostABI::normal_completion_to_abi(0);-}--JSCompletion web_crypto_algorithm_export_key(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, KeyFormat format, CryptoKey* key, void* state, ReceiveBytes receive_bytes, ReceiveJsonWebKey receive_jwk)-{- auto& realm = *realm_pointer;- auto result = algorithm->methods->export_key(realm, format, *key);- if (result.is_exception())- return Bindings::completion_to_abi(realm, result.release_error());- result.value().visit(- [&](ByteBuffer const& bytes) { receive_bytes(state, bytes.span()); },- [&](JsonWebKey const& key) { with_raw_json_web_key(key, state, receive_jwk); });- return JS::HostABI::normal_completion_to_abi(0);-}--JSCompletion web_crypto_algorithm_get_key_length(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, OptionalLength* out)-{- auto& realm = *realm_pointer;- auto result = algorithm->methods->get_key_length(realm, *algorithm->parameter);- if (result.is_exception())- return Bindings::completion_to_abi(realm, result.release_error());- *out = { result.value().has_value(), result.value().value_or(0) };- return JS::HostABI::normal_completion_to_abi(0);-}--JSCompletion web_crypto_algorithm_get_shared_key_length(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, u32* out)-{- auto& realm = *realm_pointer;- auto result = algorithm->methods->get_shared_key_length(*algorithm->parameter);- if (result.is_exception())- return Bindings::completion_to_abi(realm, result.release_error());- *out = result.value();- return JS::HostABI::normal_completion_to_abi(0);-}--JSCompletion web_crypto_algorithm_wrap_key(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, CryptoKey* key, ReadonlyBytes data, void* state, ReceiveBytes receive)-{- auto& realm = *realm_pointer;- auto result = algorithm->methods->wrap_key(realm, *algorithm->parameter, *key, MUST(ByteBuffer::copy(data)));- if (result.is_exception())- return Bindings::completion_to_abi(realm, result.release_error());- receive(state, result.value().span());- return JS::HostABI::normal_completion_to_abi(0);-}--JSCompletion web_crypto_algorithm_unwrap_key(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, CryptoKey* key, ReadonlyBytes data, void* state, ReceiveBytes receive)-{- auto& realm = *realm_pointer;- auto result = algorithm->methods->unwrap_key(realm, *algorithm->parameter, *key, MUST(ByteBuffer::copy(data)));- if (result.is_exception())- return Bindings::completion_to_abi(realm, result.release_error());- receive(state, result.value().span());- return JS::HostABI::normal_completion_to_abi(0);-}--JSCompletion web_crypto_algorithm_encapsulate(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, CryptoKey* key, void* shared_key, void* ciphertext, ReceiveBytes receive)-{- auto& realm = *realm_pointer;- auto result = algorithm->methods->encapsulate(realm, *algorithm->parameter, *key);- if (result.is_exception())- return Bindings::completion_to_abi(realm, result.release_error());- if (result.value().shared_key.has_value())- receive(shared_key, result.value().shared_key->span());- if (result.value().ciphertext.has_value())- receive(ciphertext, result.value().ciphertext->span());- return JS::HostABI::normal_completion_to_abi(0);-}--JSCompletion web_crypto_algorithm_decapsulate(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, CryptoKey* key, ReadonlyBytes data, void* state, ReceiveBytes receive)-{- auto& realm = *realm_pointer;- auto result = algorithm->methods->decapsulate(realm, *algorithm->parameter, *key, MUST(ByteBuffer::copy(data)));- if (result.is_exception())- return Bindings::completion_to_abi(realm, result.release_error());- receive(state, result.value().span());- return JS::HostABI::normal_completion_to_abi(0);-}--JSCompletion web_crypto_algorithm_validate_encrypt_parameters(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm)-{- auto& realm = *realm_pointer;- auto result = algorithm->methods->validate_encrypt_parameters(*algorithm->parameter);- if (result.is_exception())- return Bindings::completion_to_abi(realm, result.release_error());- return JS::HostABI::normal_completion_to_abi(0);-}--JSCompletion web_crypto_algorithm_validate_decrypt_parameters(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm)-{- auto& realm = *realm_pointer;- auto result = algorithm->methods->validate_decrypt_parameters(*algorithm->parameter);- if (result.is_exception())- return Bindings::completion_to_abi(realm, result.release_error());- return JS::HostABI::normal_completion_to_abi(0);-}--JSCompletion web_crypto_algorithm_validate_sign_parameters(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm)-{- auto& realm = *realm_pointer;- auto result = algorithm->methods->validate_sign_parameters(*algorithm->parameter);- if (result.is_exception())- return Bindings::completion_to_abi(realm, result.release_error());- return JS::HostABI::normal_completion_to_abi(0);-}--JSCompletion web_crypto_algorithm_validate_verify_parameters(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm)-{- auto& realm = *realm_pointer;- auto result = algorithm->methods->validate_verify_parameters(*algorithm->parameter);- if (result.is_exception())- return Bindings::completion_to_abi(realm, result.release_error());- return JS::HostABI::normal_completion_to_abi(0);-}--JSCompletion web_crypto_algorithm_validate_generate_key_parameters(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm)-{- auto& realm = *realm_pointer;- auto result = algorithm->methods->validate_generate_key_parameters(*algorithm->parameter);- if (result.is_exception())- return Bindings::completion_to_abi(realm, result.release_error());- return JS::HostABI::normal_completion_to_abi(0);-}--JSCompletion web_crypto_algorithm_validate_import_key_parameters(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm)-{- auto& realm = *realm_pointer;- auto result = algorithm->methods->validate_import_key_parameters(*algorithm->parameter);- if (result.is_exception())- return Bindings::completion_to_abi(realm, result.release_error());- return JS::HostABI::normal_completion_to_abi(0);-}--JSCompletion web_crypto_algorithm_validate_derive_bits_parameters(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, OptionalLength length)-{- auto& realm = *realm_pointer;- auto result = algorithm->methods->validate_derive_bits_parameters(*algorithm->parameter, length.to_optional());- if (result.is_exception())- return Bindings::completion_to_abi(realm, result.release_error());- return JS::HostABI::normal_completion_to_abi(0);-}--}diff --git a/Libraries/LibWeb/Crypto/SubtleCrypto.h b/Libraries/LibWeb/Crypto/SubtleCrypto.hdeleted file mode 100644index fabbc35ee78..00000000000--- a/Libraries/LibWeb/Crypto/SubtleCrypto.h+++ /dev/null@@ -1,21 +0,0 @@-/*- * Copyright (c) 2021-2022, Linus Groh <[email protected]>- * Copyright (c) 2023, stelar7 <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <LibWeb/Crypto/CryptoAlgorithms.h>--namespace Web::Crypto {--struct NormalizedAlgorithmAndParameter {- AK_ALLOC_WITH_KMALLOC;-- NonnullOwnPtr<AlgorithmMethods> methods;- NonnullOwnPtr<AlgorithmParams> parameter;-};--}diff --git a/Meta/Generators/libweb_bindings/glue_headers.py b/Meta/Generators/libweb_bindings/glue_headers.pyindex e8aa3bccd48..e7a970e6250 100644--- a/Meta/Generators/libweb_bindings/glue_headers.py+++ b/Meta/Generators/libweb_bindings/glue_headers.py@@ -46,7 +46,6 @@ def bindings_glue_header_for_interface(interface: Interface, wrapper_interface_ndirect_headers = {"AnimationFrameProvider": "LibWeb/HTML/Window.h","Element": "LibWeb/DOM/Element.h",- "SubtleCrypto": "LibWeb/Crypto/SubtleCrypto.h","Window": "LibWeb/HTML/Window.h",}if name in direct_headers:diff --git a/Meta/Linters/check_libweb_realm_mentions.py b/Meta/Linters/check_libweb_realm_mentions.pyindex 36dc93bdae0..ad8feea6a60 100755--- a/Meta/Linters/check_libweb_realm_mentions.py+++ b/Meta/Linters/check_libweb_realm_mentions.py@@ -44,13 +44,7 @@ ALLOWED_REALM_MENTIONS = {"Clipboard": (4, 16, "clipboard item/data callbacks still materialize JS values in caller-selected realms"),"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"),- "Crypto": (- 5,- 70,- "WebCrypto algorithms still use realms for buffer/key/promise materialization and for normalizing algorithm "- "dictionaries. The native CryptoKey wrapper "- "uses the caller's realm and wrapper world",- ),+ "Crypto": (2, 4, "native Crypto and CryptoKey wrappers use the caller's realm and wrapper world"),"DOM": (10,35,