Truly independent web browser
LibWeb: Share WebCrypto registration and boundary code
Shannon Booth27923440e7de
diff --git a/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_algorithms.rs b/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_algorithms.rsindex ec5ed75ee3d..456bb1f4d6b 100644--- a/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_algorithms.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_algorithms.rs@@ -280,6 +280,12 @@ pub(crate) struct EncapsulatedKeyData {type ReceiveBytes = unsafe extern "C" fn(*mut c_void, Span<'_, u8>);+fn receive_native_bytes<T>(call: impl FnOnce(*mut c_void, ReceiveBytes) -> T) -> (T, Option<Bytes>) {+ let mut bytes: Option<Bytes> = None;+ let status = call(core::ptr::from_mut(&mut bytes).cast(), receive_bytes);+ (status, bytes)+}+unsafe extern "C" {fn web_crypto_public_key_for_private_key(key: *const c_void, name: usize, named_curve: usize) -> *mut c_void;}@@ -630,16 +636,10 @@ impl AlgorithmMethods for Sha {));};- let mut result_buffer: Option<Bytes> = None;// SAFETY: The input and the output slot live for the call.- let success = unsafe {- web_crypto_sha_digest(- hash_kind,- Span::new(data.as_slice()),- core::ptr::from_mut(&mut result_buffer).cast(),- receive_bytes,- )- };+ let (success, result_buffer) = receive_native_bytes(|state, receive| unsafe {+ web_crypto_sha_digest(hash_kind, Span::new(data.as_slice()), state, receive)+ });// 2. If performing the operation results in an error, then throw an OperationError.if !success {return Err(Exception::Dom(@@ -711,19 +711,18 @@ impl AlgorithmMethods for CShakeParams {unreachable!("the algorithm is cSHAKE128 or cSHAKE256");};- let mut result: Option<Bytes> = None;// SAFETY: The input and the output slot live for the call.- let maybe_result = unsafe {+ let (maybe_result, result) = receive_native_bytes(|state, receive| unsafe {web_crypto_cshake_digest(kind,Span::new(data.as_slice()),output_length,customization.into(),function_name.into(),- core::ptr::from_mut(&mut result).cast(),- receive_bytes,+ state,+ receive,)- };+ });// 5. If performing the operation results in an error, then throw an OperationError.if maybe_result != 0 {@@ -952,17 +951,10 @@ fn hmac_calculate_message_digest(hash_name: &Utf16String, key: &[u8], message: &));};- let mut mac: Option<Bytes> = None;// SAFETY: The input and output are lent for the duration of the call.- unsafe {- web_crypto_hmac_sign(- hash_kind,- Span::new(key),- Span::new(message),- core::ptr::from_mut(&mut mac).cast(),- receive_bytes,- );- }+ let ((), mac) = receive_native_bytes(|state, receive| unsafe {+ web_crypto_hmac_sign(hash_kind, Span::new(key), Span::new(message), state, receive);+ });Ok(mac.expect("LibCrypto returns a MAC"))}@@ -1007,19 +999,18 @@ fn kmac_calculate_mac(return Err(dom_error("OperationError", b"Unsupported KMAC algorithm"));};- let mut mac: Option<Bytes> = None;// SAFETY: The input and output are lent for the duration of the call.- let success = unsafe {+ let (success, mac) = receive_native_bytes(|state, receive| unsafe {web_crypto_kmac_sign(kind,Span::new(key),Span::new(message),output_length_bits,customization.into(),- core::ptr::from_mut(&mut mac).cast(),- receive_bytes,+ state,+ receive,)- };+ });if !success {return Err(dom_error("OperationError", b"KMAC operation failed"));}@@ -2444,19 +2435,18 @@ impl AlgorithmMethods for HkdfParams {return Ok(Bytes::new(Vec::new()));}- let mut result: Option<Bytes> = None;// SAFETY: The inputs and output are lent for this call.- let success = unsafe {+ let (success, result) = receive_native_bytes(|state, receive| unsafe {web_crypto_hkdf_derive_key(hash_kind,Span::new(normalized_algorithm.salt.as_slice()),Span::new(key_derivation_key),Span::new(normalized_algorithm.info.as_slice()),length / 8,- core::ptr::from_mut(&mut result).cast(),- receive_bytes,+ state,+ receive,)- };+ });// 6. If the key derivation operation fails, then throw an OperationError.if !success {@@ -2533,19 +2523,18 @@ impl AlgorithmMethods for Pbkdf2Params {let hash_kind =sha_hash_kind(hash_algorithm).map_err(|message| Exception::Dom("NotSupportedError", message))?;- let mut result: Option<Bytes> = None;// SAFETY: The inputs and output are lent for this call.- let success = unsafe {+ let (success, result) = receive_native_bytes(|state, receive| unsafe {web_crypto_pbkdf2_derive_key(hash_kind,Span::new(password),Span::new(salt.as_slice()),iterations,derived_key_length_bytes,- core::ptr::from_mut(&mut result).cast(),- receive_bytes,+ state,+ receive,)- };+ });// 6. If the key derivation operation fails, then throw an OperationError.if !success {@@ -2782,11 +2771,10 @@ impl AlgorithmMethods for Argon2Params {associated_data: associated_data.into(),tag_length: length.expect("validation requires a length") / 8,};- let mut result: Option<Bytes> = None;// SAFETY: The inputs and output are lent for this call.- let maybe_result = unsafe {- web_crypto_argon2_derive_key(kind, &inputs, core::ptr::from_mut(&mut result).cast(), receive_bytes)- };+ let (maybe_result, result) = receive_native_bytes(|state, receive| unsafe {+ web_crypto_argon2_derive_key(kind, &inputs, state, receive)+ });// 10. If the key derivation operation fails, then throw an OperationError.if maybe_result != 0 {@@ -2847,51 +2835,6 @@ impl AesCtrParams {}}-#[derive(Clone, Trace)]-#[gc(crate = libjs_rust)]-struct AesGcmParams {- iv: Bytes,- additional_data: Option<Bytes>,- tag_length: Option<u8>,-}--impl AesGcmParams {- fn from_value(vm: &Vm, object: Gc<Object>) -> WebIdlResult<Self> {- let iv_value = object.get(vm, &PropertyKey::from_utf8("iv"))?;- let Some(iv_source) = buffer_source_type_of(iv_value) else {- return vm- .throw_completion(ErrorKind::TypeError, ErrorType::NotAnObjectOfType, &[&"BufferSource"])- .map_err(Into::into);- };- let iv = get_a_copy_of_the_bytes(vm, iv_source)?;-- let mut additional_data = None;- let additional_data_property = PropertyKey::from_utf8("additionalData");- if object.has_property(vm, &additional_data_property)? {- let additional_data_value = object.get(vm, &additional_data_property)?;- let Some(additional_data_source) = buffer_source_type_of(additional_data_value) else {- return vm- .throw_completion(ErrorKind::TypeError, ErrorType::NotAnObjectOfType, &[&"BufferSource"])- .map_err(Into::into);- };- additional_data = Some(get_a_copy_of_the_bytes(vm, additional_data_source)?);- }-- let mut tag_length = None;- let tag_length_property = PropertyKey::from_utf8("tagLength");- if object.has_property(vm, &tag_length_property)? {- let tag_length_value = object.get(vm, &tag_length_property)?;- tag_length = Some(to_octet_enforcing_range(vm, tag_length_value)?);- }-- Ok(Self {- iv,- additional_data,- tag_length,- })- }-}-#[derive(Clone, Trace)]#[gc(crate = libjs_rust)]struct AesKeyGenParams {@@ -2984,7 +2927,7 @@ enum AesParameters {Base,Cbc(AesCbcParams),Ctr(AesCtrParams),- Gcm(AesGcmParams),+ Gcm(AeadParams),KeyGen(AesKeyGenParams),DerivedKey(AesDerivedKeyParams),Aead(AeadParams),@@ -2996,7 +2939,7 @@ impl AesParameters {AesParameterType::Base => Self::Base,AesParameterType::Cbc => Self::Cbc(AesCbcParams::from_value(vm, object)?),AesParameterType::Ctr => Self::Ctr(AesCtrParams::from_value(vm, object)?),- AesParameterType::Gcm => Self::Gcm(AesGcmParams::from_value(vm, object)?),+ AesParameterType::Gcm => Self::Gcm(AeadParams::from_value(vm, object)?),AesParameterType::KeyGen => Self::KeyGen(AesKeyGenParams::from_value(vm, object)?),AesParameterType::DerivedKey => Self::DerivedKey(AesDerivedKeyParams::from_value(vm, object)?),AesParameterType::Aead => Self::Aead(AeadParams::from_value(vm, object)?),@@ -3101,18 +3044,17 @@ impl AlgorithmMethods for AesCbc {// 3. Let ciphertext be the result of performing the CBC Encryption operation described in Section 6.2 of// [NIST-SP800-38A] using AES as the block cipher, the iv member of normalizedAlgorithm as the IV input// parameter and paddedPlaintext as the input plaintext.- let mut ciphertext: Option<Bytes> = None;// SAFETY: The input and output slots live for the call.- let maybe_ciphertext = unsafe {+ let (maybe_ciphertext, ciphertext) = receive_native_bytes(|state, receive| unsafe {web_crypto_aes_cbc_cipher(true,Span::new(key.byte_handle_bytes()),Span::new(plaintext.as_slice()),Span::new(normalized_algorithm.iv.as_slice()),- core::ptr::from_mut(&mut ciphertext).cast(),- receive_bytes,+ state,+ receive,)- };+ });if !maybe_ciphertext {return Err(dom_error("OperationError", b"Failed to encrypt"));}@@ -3156,18 +3098,17 @@ impl AlgorithmMethods for AesCbc {// 4. Let p be the value of the last octet of paddedPlaintext.// 5. If p is zero or greater than 16, or if any of the last p octets of paddedPlaintext have a value which is not p, then throw an OperationError.// 6. Let plaintext be the result of removing p octets from the end of paddedPlaintext.- let mut plaintext: Option<Bytes> = None;// SAFETY: The input and output slots live for the call.- let maybe_plaintext = unsafe {+ let (maybe_plaintext, plaintext) = receive_native_bytes(|state, receive| unsafe {web_crypto_aes_cbc_cipher(false,Span::new(key.byte_handle_bytes()),Span::new(ciphertext.as_slice()),Span::new(normalized_algorithm.iv.as_slice()),- core::ptr::from_mut(&mut plaintext).cast(),- receive_bytes,+ state,+ receive,)- };+ });if !maybe_plaintext {return Err(dom_error("OperationError", b"Failed to decrypt"));}@@ -3910,18 +3851,17 @@ impl AlgorithmMethods for AesCtr {// value of the counter block, the length member of normalizedAlgorithm as the input parameter m to the// standard counter block incrementing function defined in Appendix B.1 of [NIST-SP800-38A] and plaintext as// the input plaintext.- let mut ciphertext: Option<Bytes> = None;// SAFETY: The input and output slots live for the call.- let maybe_ciphertext = unsafe {+ let (maybe_ciphertext, ciphertext) = receive_native_bytes(|state, receive| unsafe {web_crypto_aes_ctr_cipher(true,Span::new(key.byte_handle_bytes()),Span::new(plaintext.as_slice()),Span::new(counter.as_slice()),- core::ptr::from_mut(&mut ciphertext).cast(),- receive_bytes,+ state,+ receive,)- };+ });if !maybe_ciphertext {return Err(dom_error("OperationError", b"Encryption failed"));}@@ -3964,18 +3904,17 @@ impl AlgorithmMethods for AesCtr {// value of the counter block, the length member of normalizedAlgorithm as the input parameter m to the// standard counter block incrementing function defined in Appendix B.1 of [NIST-SP800-38A] and ciphertext as// the input ciphertext.- let mut plaintext: Option<Bytes> = None;// SAFETY: The input and output slots live for the call.- let maybe_plaintext = unsafe {+ let (maybe_plaintext, plaintext) = receive_native_bytes(|state, receive| unsafe {web_crypto_aes_ctr_cipher(false,Span::new(key.byte_handle_bytes()),Span::new(ciphertext.as_slice()),Span::new(counter.as_slice()),- core::ptr::from_mut(&mut plaintext).cast(),- receive_bytes,+ state,+ receive,)- };+ });if !maybe_plaintext {return Err(dom_error("OperationError", b"Decryption failed"));}@@ -4441,19 +4380,18 @@ impl AlgorithmMethods for AesGcm {// input parameter, tagLength as the t pre-requisite, actualCiphertext as the input ciphertext, C and tag as// the authentication tag, T.// If the result of the algorithm is the indication of inauthenticity, "FAIL": throw an OperationError- let mut plaintext: Option<Bytes> = None;// SAFETY: The inputs and output slot live for the call.- let maybe_plaintext = unsafe {+ let (maybe_plaintext, plaintext) = receive_native_bytes(|state, receive| unsafe {web_crypto_aes_gcm_decrypt(Span::new(key.byte_handle_bytes()),Span::new(&actual_ciphertext),Span::new(normalized_algorithm.iv.as_slice()),Span::new(additional_data),Span::new(&tag),- core::ptr::from_mut(&mut plaintext).cast(),- receive_bytes,+ state,+ receive,)- };+ });if !maybe_plaintext {return Err(dom_error("OperationError", b"Decryption failed"));@@ -4898,17 +4836,16 @@ impl AlgorithmMethods for AesKw {// 2. Let ciphertext be the result of performing the Key Wrap operation described in Section 2.2.1 of [RFC3394]// with plaintext as the plaintext to be wrapped and using the default Initial Value defined in Section 2.2.3.1 of the same document.- let mut ciphertext: Option<Bytes> = None;// SAFETY: The input and output slots live for the call.- let maybe_ciphertext = unsafe {+ let (maybe_ciphertext, ciphertext) = receive_native_bytes(|state, receive| unsafe {web_crypto_aes_kw_cipher(true,Span::new(key.byte_handle_bytes()),Span::new(plaintext.as_slice()),- core::ptr::from_mut(&mut ciphertext).cast(),- receive_bytes,+ state,+ receive,)- };+ });if !maybe_ciphertext {return Err(dom_error("OperationError", b"Key wrap failed"));}@@ -4928,17 +4865,16 @@ impl AlgorithmMethods for AesKw {// with ciphertext as the input ciphertext and using the default Initial Value defined in Section 2.2.3.1 of// the same document.// 2. If the Key Unwrap operation returns an error, then throw an OperationError.- let mut plaintext: Option<Bytes> = None;// SAFETY: The input and output slots live for the call.- let maybe_plaintext = unsafe {+ let (maybe_plaintext, plaintext) = receive_native_bytes(|state, receive| unsafe {web_crypto_aes_kw_cipher(false,Span::new(key.byte_handle_bytes()),Span::new(ciphertext.as_slice()),- core::ptr::from_mut(&mut plaintext).cast(),- receive_bytes,+ state,+ receive,)- };+ });if !maybe_plaintext {return Err(dom_error("OperationError", b"Key unwrap failed"));}@@ -5017,9 +4953,8 @@ impl AlgorithmMethods for AesOcb {// additionalData as the A input parameter,// plaintext as the P input parameter,// and tagLength as the TAGLEN global parameter.- let mut ciphertext: Option<Bytes> = None;// SAFETY: The inputs and output slot live for the call.- let maybe_ciphertext = unsafe {+ let (maybe_ciphertext, ciphertext) = receive_native_bytes(|state, receive| unsafe {web_crypto_aes_ocb_cipher(true,Span::new(key.byte_handle_bytes()),@@ -5027,10 +4962,10 @@ impl AlgorithmMethods for AesOcb {Span::new(normalized_algorithm.iv.as_slice()),Span::new(additional_data),tag_length,- core::ptr::from_mut(&mut ciphertext).cast(),- receive_bytes,+ state,+ receive,)- };+ });if maybe_ciphertext != 0 {// SAFETY: LibCrypto transfers an ownership reference.@@ -5104,9 +5039,8 @@ impl AlgorithmMethods for AesOcb {// additionalData as the A input parameter,// ciphertext as the C input parameter,// and tagLength as the TAGLEN global parameter.- let mut plaintext: Option<Bytes> = None;// SAFETY: The inputs and output slot live for the call.- let maybe_plaintext = unsafe {+ let (maybe_plaintext, plaintext) = receive_native_bytes(|state, receive| unsafe {web_crypto_aes_ocb_cipher(false,Span::new(key.byte_handle_bytes()),@@ -5114,10 +5048,10 @@ impl AlgorithmMethods for AesOcb {Span::new(normalized_algorithm.iv.as_slice()),Span::new(additional_data),tag_length,- core::ptr::from_mut(&mut plaintext).cast(),- receive_bytes,+ state,+ receive,)- };+ });// 5. Perform the OCB-DECRYPT function described in Section 4.3 of [RFC7253] using AES as the block cipher,// using the key represented by [[handle]] internal slot of key as the K input parameter, the iv member of@@ -5548,19 +5482,18 @@ impl AlgorithmMethods for ChaCha20Poly1305 {// described in Section 2.8 of [RFC8439], using the key represented by [[handle]] internal slot of key as the// key input parameter, the iv member of normalizedAlgorithm as the nonce input parameter, plaintext as the// plaintext input parameter, and additionalData as the additional authenticated data (AAD) input parameter.- let mut ciphertext: Option<Bytes> = None;// SAFETY: The inputs and output slot live for the call.- let maybe_ciphertext = unsafe {+ let (maybe_ciphertext, ciphertext) = receive_native_bytes(|state, receive| unsafe {web_crypto_chacha20_poly1305_cipher(true,Span::new(key.byte_handle_bytes()),Span::new(normalized_algorithm.iv.as_slice()),Span::new(plaintext.as_slice()),Span::new(additional_data),- core::ptr::from_mut(&mut ciphertext).cast(),- receive_bytes,+ state,+ receive,)- };+ });if maybe_ciphertext != 0 {// SAFETY: LibCrypto transfers an ownership reference.@@ -5614,19 +5547,18 @@ impl AlgorithmMethods for ChaCha20Poly1305 {// represented by [[handle]] internal slot of key as the key input parameter, the iv member of normalizedAlgorithm// as the nonce input parameter, ciphertext as the ciphertext input parameter, and additionalData as the additional// authenticated data (AAD) input parameter.- let mut plaintext: Option<Bytes> = None;// SAFETY: The inputs and output slot live for the call.- let maybe_plaintext = unsafe {+ let (maybe_plaintext, plaintext) = receive_native_bytes(|state, receive| unsafe {web_crypto_chacha20_poly1305_cipher(false,Span::new(key.byte_handle_bytes()),Span::new(normalized_algorithm.iv.as_slice()),Span::new(ciphertext.as_slice()),Span::new(additional_data),- core::ptr::from_mut(&mut plaintext).cast(),- receive_bytes,+ state,+ receive,)- };+ });// If the result of the algorithm is the indication of authentication failure:// throw an OperationError@@ -6261,15 +6193,10 @@ fn validate_rsa_key_generation_parameters(normalized_algorithm: &RsaKeyGenParams}fn export_public_exponent(vm: &Vm, exponent: &Bytes) -> WebIdlResult<Vec<u8>> {- let mut result: Option<Bytes> = None;// SAFETY: The exponent and the output slot are lent for the call.- let success = unsafe {- web_crypto_rsa_export_public_exponent(- Span::new(exponent.as_slice()),- core::ptr::from_mut(&mut result).cast(),- receive_bytes,- )- };+ let (success, result) = receive_native_bytes(|state, receive| unsafe {+ web_crypto_rsa_export_public_exponent(Span::new(exponent.as_slice()), state, receive)+ });if !success {return vm.throw_completion(ErrorKind::InternalError, ErrorType::OutOfMemory, &[])@@ -6280,16 +6207,10 @@ fn export_public_exponent(vm: &Vm, exponent: &Bytes) -> WebIdlResult<Vec<u8>> {fn rsa_key_metadata(vm: &Vm, key: Ref<CryptoKey>) -> WebIdlResult<(u32, Vec<u8>)> {let mut modulus_length = 0;- let mut exponent: Option<Bytes> = None;// SAFETY: The key handle and the output slots are lent for the call.- let success = unsafe {- web_crypto_rsa_read_key_metadata(- key.handle().as_ptr(),- &mut modulus_length,- core::ptr::from_mut(&mut exponent).cast(),- receive_bytes,- )- };+ let (success, exponent) = receive_native_bytes(|state, receive| unsafe {+ web_crypto_rsa_read_key_metadata(key.handle().as_ptr(), &mut modulus_length, state, receive)+ });if !success {return vm.throw_completion(ErrorKind::InternalError, ErrorType::OutOfMemory, &[])@@ -6329,16 +6250,10 @@ fn parse_jwk_rsa_key(vm: &Vm, jwk: &JsonWebKey, is_private: bool) -> WebIdlResul}fn rsa_export_der(vm: &Vm, key: Ref<CryptoKey>, is_public: bool) -> WebIdlResult<Bytes> {- let mut result: Option<Bytes> = None;// SAFETY: The key handle and the output slot are lent for the call.- let success = unsafe {- web_crypto_rsa_export_der(- key.handle().as_ptr(),- is_public,- core::ptr::from_mut(&mut result).cast(),- receive_bytes,- )- };+ let (success, result) = receive_native_bytes(|state, receive| unsafe {+ web_crypto_rsa_export_der(key.handle().as_ptr(), is_public, state, receive)+ });if !success {return vm.throw_completion(ErrorKind::InternalError, ErrorType::OutOfMemory, &[])@@ -6348,16 +6263,10 @@ 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> {- 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,- )- };+ let (success, bytes) = receive_native_bytes(|state, receive| unsafe {+ web_crypto_rsa_export_jwk_integer(key.handle().as_ptr(), component, state, receive)+ });if !success {return Err(out_of_memory(vm));}@@ -6441,19 +6350,18 @@ impl AlgorithmMethods for RsaOaep {};// 5. Let ciphertext be the value C that results from performing the operation.- let mut ciphertext: Option<Bytes> = None;// SAFETY: The input and output slots live for the call.- let maybe_ciphertext = unsafe {+ let (maybe_ciphertext, ciphertext) = receive_native_bytes(|state, receive| unsafe {web_crypto_rsa_oaep_cipher(true,hash_kind,key.handle().as_ptr(),Span::new(label.as_slice()),Span::new(plaintext.as_slice()),- core::ptr::from_mut(&mut ciphertext).cast(),- receive_bytes,+ state,+ receive,)- };+ });if !maybe_ciphertext {return Err(dom_error("OperationError", b"Failed to encrypt"));}@@ -6506,19 +6414,18 @@ impl AlgorithmMethods for RsaOaep {};// 5. Let plaintext the value M that results from performing the operation.- let mut plaintext: Option<Bytes> = None;// SAFETY: The input and output slots live for the call.- let maybe_plaintext = unsafe {+ let (maybe_plaintext, plaintext) = receive_native_bytes(|state, receive| unsafe {web_crypto_rsa_oaep_cipher(false,hash_kind,key.handle().as_ptr(),Span::new(label.as_slice()),Span::new(ciphertext.as_slice()),- core::ptr::from_mut(&mut plaintext).cast(),- receive_bytes,+ state,+ receive,)- };+ });if !maybe_plaintext {return Err(dom_error("OperationError", b"Failed to encrypt"));}@@ -7283,18 +7190,17 @@ impl AlgorithmMethods for RsaPss {};// 4. Let signature be the signature, S, that results from performing the operation.- let mut signature: Option<Bytes> = None;// SAFETY: The input and output slots live for the call.- let maybe_signature = unsafe {+ let (maybe_signature, signature) = receive_native_bytes(|state, receive| unsafe {web_crypto_rsa_pss_sign(hash_kind,key.handle().as_ptr(),pss_params.salt_length,Span::new(message.as_slice()),- core::ptr::from_mut(&mut signature).cast(),- receive_bytes,+ state,+ receive,)- };+ });if !maybe_signature {return Err(dom_error("OperationError", b"Failed to sign message"));}@@ -8000,17 +7906,16 @@ impl AlgorithmMethods for RsassaPkcs1 {};// 4. Let signature be the value S that results from performing the operation.- let mut signature: Option<Bytes> = None;// SAFETY: The input and output slots live for the call.- let maybe_signature = unsafe {+ let (maybe_signature, signature) = receive_native_bytes(|state, receive| unsafe {web_crypto_rsa_pkcs1_sign(hash_kind,key.handle().as_ptr(),Span::new(message.as_slice()),- core::ptr::from_mut(&mut signature).cast(),- receive_bytes,+ state,+ receive,)- };+ });if !maybe_signature {return Err(dom_error("OperationError", b"Failed to sign message"));}@@ -8800,32 +8705,22 @@ fn ec_key_is_valid(curve: EcCurve, key: Ref<CryptoKey>) -> Result<bool, ()> {}fn ec_export_der(curve: EcCurve, key: Ref<CryptoKey>, is_public: bool) -> Result<Bytes, ()> {- let mut result: Option<Bytes> = None;// SAFETY: The key handle and the output slot are lent for the call.- if !unsafe {- web_crypto_ec_export_der(- curve,- key.handle().as_ptr(),- is_public,- core::ptr::from_mut(&mut result).cast(),- receive_bytes,- )- } {+ let (success, result) = receive_native_bytes(|state, receive| unsafe {+ web_crypto_ec_export_der(curve, key.handle().as_ptr(), is_public, state, receive)+ });+ if !success {return Err(());}Ok(result.expect("LibCrypto returns the DER bytes"))}fn ec_export_uncompressed(key: Ref<CryptoKey>) -> Result<Bytes, ()> {- let mut result: Option<Bytes> = None;// SAFETY: The key handle and the output slot are lent for the call.- if !unsafe {- web_crypto_ec_export_uncompressed(- key.handle().as_ptr(),- core::ptr::from_mut(&mut result).cast(),- receive_bytes,- )- } {+ let (success, result) = receive_native_bytes(|state, receive| unsafe {+ web_crypto_ec_export_uncompressed(key.handle().as_ptr(), state, receive)+ });+ if !success {return Err(());}Ok(result.expect("LibCrypto returns the encoded bytes"))@@ -8853,15 +8748,11 @@ fn ec_export_public_coordinates(curve: EcCurve, key: Ref<CryptoKey>) -> Result<(}fn ec_export_private_scalar(key: Ref<CryptoKey>) -> Result<Bytes, ()> {- let mut result: Option<Bytes> = None;// SAFETY: The key handle and the output slot are lent for the call.- if !unsafe {- web_crypto_ec_export_private_scalar(- key.handle().as_ptr(),- core::ptr::from_mut(&mut result).cast(),- receive_bytes,- )- } {+ let (success, result) = receive_native_bytes(|state, receive| unsafe {+ web_crypto_ec_export_private_scalar(key.handle().as_ptr(), state, receive)+ });+ if !success {return Err(());}Ok(result.expect("LibCrypto returns the private scalar"))@@ -9032,16 +8923,10 @@ impl AlgorithmMethods for Ecdsa {// 3. Let M be the result of performing the digest operation specified by hashAlgorithm using message.let hash_kind =sha_hash_kind(hash_algorithm).map_err(|message| Exception::Dom("NotSupportedError", message))?;- let mut digest: Option<Bytes> = None;// SAFETY: The input and output slot live for the call.- let success = unsafe {- web_crypto_sha_digest(- hash_kind,- Span::new(message.as_slice()),- core::ptr::from_mut(&mut digest).cast(),- receive_bytes,- )- };+ let (success, digest) = receive_native_bytes(|state, receive| unsafe {+ web_crypto_sha_digest(hash_kind, Span::new(message.as_slice()), state, receive)+ });if !success {return cx.vm()@@ -9167,16 +9052,10 @@ impl AlgorithmMethods for Ecdsa {// 3. Let M be the result of performing the digest operation specified by hashAlgorithm using message.let hash_kind =sha_hash_kind(hash_algorithm).map_err(|message| Exception::Dom("NotSupportedError", message))?;- let mut digest: Option<Bytes> = None;// SAFETY: The input and output slot live for the call.- let success = unsafe {- web_crypto_sha_digest(- hash_kind,- Span::new(message.as_slice()),- core::ptr::from_mut(&mut digest).cast(),- receive_bytes,- )- };+ let (success, digest) = receive_native_bytes(|state, receive| unsafe {+ web_crypto_sha_digest(hash_kind, Span::new(message.as_slice()), state, receive)+ });if !success {return cx.vm()@@ -10222,18 +10101,17 @@ impl AlgorithmMethods for Ecdh {// conversion defined in Section 6.2 of [RFC6090] to the output of the ECDH primitive.// NOTE: Remove the prefix from the uncompressed pointlet mut error = 0;- let mut secret_data: Option<Bytes> = None;// SAFETY: The key handles and output slots live for the call.- let status = unsafe {+ let (status, secret_data) = receive_native_bytes(|state, receive| unsafe {web_crypto_ec_compute_coordinate(curve,key.handle().as_ptr(),public_key.handle().as_ptr(),&mut error,- core::ptr::from_mut(&mut secret_data).cast(),- receive_bytes,+ state,+ receive,)- };+ });if status == 1 {// SAFETY: LibCrypto transfers ownership of the error message.let detail = unsafe { Utf16String::from_raw_owned(error) };@@ -11103,42 +10981,32 @@ fn parse_octet_string(vm: &Vm, bytes: &[u8]) -> WebIdlResult<Vec<u8>> {}fn okp_generate_private_key(curve: OkpCurve) -> Result<Bytes, ()> {- let mut key: Option<Bytes> = None;// SAFETY: The output slot is lent for the call.- if !unsafe { web_crypto_okp_generate_private_key(curve, core::ptr::from_mut(&mut key).cast(), receive_bytes) } {+ let (success, key) =+ receive_native_bytes(|state, receive| unsafe { web_crypto_okp_generate_private_key(curve, state, receive) });+ if !success {return Err(());}Ok(key.expect("LibCrypto returns the private key"))}fn okp_generate_public_key(curve: OkpCurve, private_key: &[u8]) -> Result<Bytes, ()> {- let mut key: Option<Bytes> = None;// SAFETY: The private key and output slot are lent for the call.- if !unsafe {- web_crypto_okp_generate_public_key(- curve,- Span::new(private_key),- core::ptr::from_mut(&mut key).cast(),- receive_bytes,- )- } {+ let (success, key) = receive_native_bytes(|state, receive| unsafe {+ web_crypto_okp_generate_public_key(curve, Span::new(private_key), state, receive)+ });+ if !success {return Err(());}Ok(key.expect("LibCrypto returns the public key"))}fn okp_export_der(vm: &Vm, curve: OkpCurve, is_public: bool, key: &[u8]) -> WebIdlResult<Bytes> {- let mut result: Option<Bytes> = None;// SAFETY: The key and the output slot are lent for the call.- if !unsafe {- web_crypto_okp_export_der(- curve,- is_public,- Span::new(key),- core::ptr::from_mut(&mut result).cast(),- receive_bytes,- )- } {+ let (success, result) = receive_native_bytes(|state, receive| unsafe {+ web_crypto_okp_export_der(curve, is_public, Span::new(key), state, receive)+ });+ if !success {return vm.throw_completion(ErrorKind::InternalError, ErrorType::OutOfMemory, &[]).map_err(Into::into);@@ -11696,18 +11564,17 @@ impl AlgorithmMethods for Ed25519 {return Err(dom_error("OperationError", b"Failed to generate public key"));}- let mut signature: Option<Bytes> = None;// SAFETY: The input bytes and output slot are lent for the call.- let maybe_signature = unsafe {+ let (maybe_signature, signature) = receive_native_bytes(|state, receive| unsafe {web_crypto_okp_sign(OkpCurve::Ed25519,Span::new(key.okp_handle_bytes()),Span::new(message.as_slice()),Span::new(&[]),- core::ptr::from_mut(&mut signature).cast(),- receive_bytes,+ state,+ receive,)- };+ });if !maybe_signature {return Err(dom_error("OperationError", b"Failed to sign message"));}@@ -12318,18 +12185,17 @@ impl AlgorithmMethods for Ed448 {// 4. Perform the Ed448 signing process, as specified in [RFC8032], Section 5.2.6,// with message as M and context as C, using the Ed448 private key associated with key.- let mut signature: Option<Bytes> = None;// SAFETY: The input bytes and output slot are lent for the call.- let maybe_signature = unsafe {+ let (maybe_signature, signature) = receive_native_bytes(|state, receive| unsafe {web_crypto_okp_sign(OkpCurve::Ed448,Span::new(key.okp_handle_bytes()),Span::new(message.as_slice()),Span::new(context),- core::ptr::from_mut(&mut signature).cast(),- receive_bytes,+ state,+ receive,)- };+ });if !maybe_signature {return Err(dom_error("OperationError", b"Failed to sign message"));}@@ -12485,17 +12351,16 @@ impl AlgorithmMethods for X25519 {let private_key = key.okp_handle_bytes();let public_key_data = public_key.okp_handle_bytes();- let mut secret: Option<Bytes> = None;// SAFETY: The input bytes and output slot are lent for the call.- let maybe_secret = unsafe {+ let (maybe_secret, secret) = receive_native_bytes(|state, receive| unsafe {web_crypto_okp_compute_coordinate(OkpCurve::X25519,Span::new(private_key),Span::new(public_key_data),- core::ptr::from_mut(&mut secret).cast(),- receive_bytes,+ state,+ receive,)- };+ });if !maybe_secret {return Err(dom_error("OperationError", b"Failed to compute secret"));}@@ -13094,17 +12959,16 @@ impl AlgorithmMethods for X448 {let private_key = key.okp_handle_bytes();let public_key_data = public_key.okp_handle_bytes();- let mut secret: Option<Bytes> = None;// SAFETY: The input bytes and output slot are lent for the call.- let maybe_secret = unsafe {+ let (maybe_secret, secret) = receive_native_bytes(|state, receive| unsafe {web_crypto_okp_compute_coordinate(OkpCurve::X448,Span::new(private_key),Span::new(public_key_data),- core::ptr::from_mut(&mut secret).cast(),- receive_bytes,+ state,+ receive,)- };+ });if !maybe_secret {return Err(dom_error("OperationError", b"Failed to compute secret"));}@@ -13744,17 +13608,11 @@ fn generate_mldsa_key_pair_from_seed(name: &Utf16String, seed: &Bytes) -> Result}fn mldsa_export_der(vm: &Vm, key: Ref<CryptoKey>, is_public: bool, oid: &[u32]) -> WebIdlResult<Bytes> {- let mut result: Option<Bytes> = None;// SAFETY: The key handle, OID and output slot are lent for the call.- if !unsafe {- web_crypto_mldsa_export_der(- key.handle().as_ptr(),- is_public,- Span::new(oid),- core::ptr::from_mut(&mut result).cast(),- receive_bytes,- )- } {+ let (success, result) = receive_native_bytes(|state, receive| unsafe {+ web_crypto_mldsa_export_der(key.handle().as_ptr(), is_public, Span::new(oid), state, receive)+ });+ if !success {return Err(out_of_memory(vm));}Ok(result.expect("LibCrypto returns the DER bytes"))@@ -13829,18 +13687,17 @@ impl AlgorithmMethods for MlDsa {} else {unreachable!("the name identifies an ML-DSA parameter set")};- let mut signature: Option<Bytes> = None;// SAFETY: The key, input bytes and output slot are lent for the call.- let maybe_result = unsafe {+ let (maybe_result, signature) = receive_native_bytes(|state, receive| unsafe {web_crypto_mldsa_sign(size,key.handle().as_ptr(),Span::new(message.as_slice()),Span::new(context),- core::ptr::from_mut(&mut signature).cast(),- receive_bytes,+ state,+ receive,)- };+ });// 5. If the ML-DSA.Sign algorithm returned an error, throw an OperationError.if !maybe_result {@@ -14637,17 +14494,11 @@ fn mlkem_generate_key_pair(size: MlKemSize, seed: &[u8]) -> Result<NativeKeyPair}fn mlkem_export_der(vm: &Vm, key: Ref<CryptoKey>, is_public: bool, oid: &[u32]) -> WebIdlResult<Bytes> {- let mut result: Option<Bytes> = None;// SAFETY: The key handle, OID and output slot are lent for the call.- if !unsafe {- web_crypto_mlkem_export_der(- key.handle().as_ptr(),- is_public,- Span::new(oid),- core::ptr::from_mut(&mut result).cast(),- receive_bytes,- )- } {+ let (success, result) = receive_native_bytes(|state, receive| unsafe {+ web_crypto_mlkem_export_der(key.handle().as_ptr(), is_public, Span::new(oid), state, receive)+ });+ if !success {return Err(out_of_memory(vm));}Ok(result.expect("LibCrypto returns the DER bytes"))@@ -15163,11 +15014,10 @@ impl AlgorithmMethods for MlKem {}// 2. Let data be a byte sequence containing the raw octets of the key represented by the [[handle]] internal slot of key.- let mut data: Option<Bytes> = None;// SAFETY: The handle and output slot are lent for the call.- unsafe {- web_crypto_mlkem_public_bytes(handle.as_ptr(), core::ptr::from_mut(&mut data).cast(), receive_bytes);- };+ let ((), data) = receive_native_bytes(|state, receive| unsafe {+ web_crypto_mlkem_public_bytes(handle.as_ptr(), state, receive);+ });let data = data.expect("LibCrypto returns the public key bytes");// 3. Let result be data.@@ -15318,17 +15168,16 @@ impl AlgorithmMethods for MlKem {} else {unreachable!("the name identifies an ML-KEM parameter set")};- let mut shared_key: Option<Bytes> = None;// SAFETY: The handle, ciphertext and output slot are lent for the call.- let maybe_shared_key = unsafe {+ let (maybe_shared_key, shared_key) = receive_native_bytes(|state, receive| unsafe {web_crypto_mlkem_decapsulate(size,key.handle().as_ptr(),Span::new(ciphertext.as_slice()),- core::ptr::from_mut(&mut shared_key).cast(),- receive_bytes,+ state,+ receive,)- };+ });if maybe_shared_key != 0 {// SAFETY: LibCrypto transfers ownership of the error message.diff --git a/Libraries/LibWeb/Bindings/Rust/src/crypto/subtle_crypto.rs b/Libraries/LibWeb/Bindings/Rust/src/crypto/subtle_crypto.rsindex 6ec5781be91..f177e272838 100644--- a/Libraries/LibWeb/Bindings/Rust/src/crypto/subtle_crypto.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/crypto/subtle_crypto.rs@@ -277,6 +277,21 @@ fn create_rejected_promise_from_exception(vm: &Vm, realm: Gc<Realm>, exception:})}+fn queue_crypto_rejection(vm: &Vm, realm: Gc<Realm>, promise: WebIdlPromise, exception: Exception) {+ let value = exception.throw(&CallContext::new(vm, realm)).value();+ queue_a_global_task(+ vm,+ realm.global_object(),+ TaskSource::Crypto,+ (realm, promise, value),+ |vm, (realm, promise, value)| {+ with_temporary_execution_context_and_callbacks(realm, || {+ reject_promise(vm, promise, value);+ });+ },+ );+}+fn reject_promise_with_exception(vm: &Vm, promise: WebIdlPromise, exception: Exception) {let realm = promise_realm(promise);with_temporary_execution_context(realm, || {@@ -524,30 +539,25 @@ impl SubtleCrypto {// 8. If the following steps or referenced procedures say to throw an error, queue a global task on// the crypto task source, given realm's global object, to reject promise with the returned// error; and then terminate the algorithm.- let throw_in_this_context = |exception: Exception| {- let value = exception.throw(&CallContext::new(vm, realm)).value();- queue_a_global_task(- vm,- realm.global_object(),- TaskSource::Crypto,- (realm, promise, value),- |vm, (realm, promise, value)| {- with_temporary_execution_context_and_callbacks(realm, || {- reject_promise(vm, promise, value);- });- },- );- };-// 9. If the name member of normalizedAlgorithm is not equal to the name attribute of the [[algorithm]] internal slot of key then throw an InvalidAccessError.if normalized_algorithm.parameter.name != key.algorithm_name() {- throw_in_this_context(dom_error("InvalidAccessError", b"Algorithm mismatch"));+ queue_crypto_rejection(+ vm,+ realm,+ promise,+ dom_error("InvalidAccessError", b"Algorithm mismatch"),+ );return;}// 10. If the [[usages]] internal slot of key does not contain an entry that is "encrypt", then throw an InvalidAccessError.if !key.internal_usages().contains(&KeyUsage::Encrypt) {- throw_in_this_context(dom_error("InvalidAccessError", b"Key does not support encryption"));+ queue_crypto_rejection(+ vm,+ realm,+ promise,+ dom_error("InvalidAccessError", b"Key does not support encryption"),+ );return;}@@ -556,7 +566,7 @@ impl SubtleCrypto {.methods.encrypt(&CallContext::new(vm, realm), key, &data);if let Err(error) = cipher_text {- throw_in_this_context(error);+ queue_crypto_rejection(vm, realm, promise, error);return;}@@ -622,30 +632,25 @@ impl SubtleCrypto {// 8. If the following steps or referenced procedures say to throw an error, queue a global task on// the crypto task source, given realm's global object, to reject promise with the returned// error; and then terminate the algorithm.- let throw_in_this_context = |exception: Exception| {- let value = exception.throw(&CallContext::new(vm, realm)).value();- queue_a_global_task(- vm,- realm.global_object(),- TaskSource::Crypto,- (realm, promise, value),- |vm, (realm, promise, value)| {- with_temporary_execution_context_and_callbacks(realm, || {- reject_promise(vm, promise, value);- });- },- );- };-// 9. If the name member of normalizedAlgorithm is not equal to the name attribute of the [[algorithm]] internal slot of key then throw an InvalidAccessError.if normalized_algorithm.parameter.name != key.algorithm_name() {- throw_in_this_context(dom_error("InvalidAccessError", b"Algorithm mismatch"));+ queue_crypto_rejection(+ vm,+ realm,+ promise,+ dom_error("InvalidAccessError", b"Algorithm mismatch"),+ );return;}// 10. If the [[usages]] internal slot of key does not contain an entry that is "decrypt", then throw an InvalidAccessError.if !key.internal_usages().contains(&KeyUsage::Decrypt) {- throw_in_this_context(dom_error("InvalidAccessError", b"Key does not support decryption"));+ queue_crypto_rejection(+ vm,+ realm,+ promise,+ dom_error("InvalidAccessError", b"Key does not support decryption"),+ );return;}@@ -654,7 +659,7 @@ impl SubtleCrypto {.methods.decrypt(&CallContext::new(vm, realm), key, &data);if let Err(error) = plain_text {- throw_in_this_context(error);+ queue_crypto_rejection(vm, realm, promise, error);return;}@@ -720,28 +725,13 @@ impl SubtleCrypto {// 8. If the following steps or referenced procedures say to throw an error, queue a global task on// the crypto task source, given realm's global object, to reject promise with the returned// error; and then terminate the algorithm.- let throw_in_this_context = |exception: Exception| {- let value = exception.throw(&CallContext::new(vm, realm)).value();- queue_a_global_task(- vm,- realm.global_object(),- TaskSource::Crypto,- (realm, promise, value),- |vm, (realm, promise, value)| {- with_temporary_execution_context_and_callbacks(realm, || {- reject_promise(vm, promise, value);- });- },- );- };-// 9. Let digest be the result of performing the digest operation specified by normalizedAlgorithm using algorithm, with data as message.let digest = algorithm_object.methods.digest(realm, &algorithm_object.parameter, &data_buffer);if let Err(error) = digest {- throw_in_this_context(error);+ queue_crypto_rejection(vm, realm, promise, error);return;}@@ -1149,31 +1139,26 @@ impl SubtleCrypto {// 8. If the following steps or referenced procedures say to throw an error, queue a global task on the// crypto task source, given realm's global object, to reject promise with the returned error; and then// terminate the algorithm.- let throw_in_this_context = |exception: Exception| {- let value = exception.throw(&CallContext::new(vm, realm)).value();- queue_a_global_task(- vm,- realm.global_object(),- TaskSource::Crypto,- (realm, promise, value),- |vm, (realm, promise, value)| {- with_temporary_execution_context_and_callbacks(realm, || {- reject_promise(vm, promise, value);- });- },- );- };-// 9. If the name member of normalizedAlgorithm is not equal to the name attribute of the [[algorithm]]// internal slot of key then throw an InvalidAccessError.if normalized_algorithm.parameter.name != key.algorithm_name() {- throw_in_this_context(dom_error("InvalidAccessError", b"Algorithm mismatch"));+ queue_crypto_rejection(+ vm,+ realm,+ promise,+ dom_error("InvalidAccessError", b"Algorithm mismatch"),+ );return;}// 10. If the [[usages]] internal slot of key does not contain an entry that is "sign", then throw an InvalidAccessError.if !key.internal_usages().contains(&KeyUsage::Sign) {- throw_in_this_context(dom_error("InvalidAccessError", b"Key does not support signing"));+ queue_crypto_rejection(+ vm,+ realm,+ promise,+ dom_error("InvalidAccessError", b"Key does not support signing"),+ );return;}@@ -1186,7 +1171,7 @@ impl SubtleCrypto {&data,);if let Err(error) = signature {- throw_in_this_context(error);+ queue_crypto_rejection(vm, realm, promise, error);return;}@@ -1260,31 +1245,26 @@ impl SubtleCrypto {// 9. If the following steps or referenced procedures say to throw an error, queue a global task on the// crypto task source, given realm's global object, to reject promise with the returned error; and then// terminate the algorithm.- let throw_in_this_context = |exception: Exception| {- let value = exception.throw(&CallContext::new(vm, realm)).value();- queue_a_global_task(- vm,- realm.global_object(),- TaskSource::Crypto,- (realm, promise, value),- |vm, (realm, promise, value)| {- with_temporary_execution_context_and_callbacks(realm, || {- reject_promise(vm, promise, value);- });- },- );- };-// 10. If the name member of normalizedAlgorithm is not equal to the name attribute of the [[algorithm]]// internal slot of key then throw an InvalidAccessError.if normalized_algorithm.parameter.name != key.algorithm_name() {- throw_in_this_context(dom_error("InvalidAccessError", b"Algorithm mismatch"));+ queue_crypto_rejection(+ vm,+ realm,+ promise,+ dom_error("InvalidAccessError", b"Algorithm mismatch"),+ );return;}// 11. If the [[usages]] internal slot of key does not contain an entry that is "verify", then throw an InvalidAccessError.if !key.internal_usages().contains(&KeyUsage::Verify) {- throw_in_this_context(dom_error("InvalidAccessError", b"Key does not support verification"));+ queue_crypto_rejection(+ vm,+ realm,+ promise,+ dom_error("InvalidAccessError", b"Key does not support verification"),+ );return;}@@ -1298,7 +1278,7 @@ impl SubtleCrypto {&data,);if let Err(error) = result {- throw_in_this_context(error);+ queue_crypto_rejection(vm, realm, promise, error);return;}@@ -2057,32 +2037,27 @@ impl SubtleCrypto {with_temporary_execution_context_and_callbacks(realm, || {// 9. If the following steps or referenced procedures say to throw an error, queue a global task on the crypto task// source, given realm's global object, to reject promise with the returned error; and then terminate the algorithm.- let throw_in_this_context = |exception: Exception| {- let value = exception.throw(&CallContext::new(vm, realm)).value();- queue_a_global_task(- vm,- realm.global_object(),- TaskSource::Crypto,- (realm, promise, value),- |vm, (realm, promise, value)| {- with_temporary_execution_context_and_callbacks(realm, || {- reject_promise(vm, promise, value);- });- },- );- };-// 10. If the name member of normalizedEncapsulationAlgorithm is not equal to the name attribute of the [[algorithm]]// internal slot of encapsulationKey then throw an InvalidAccessError.if normalized_encapsulation_algorithm.parameter.name != encapsulation_key.algorithm_name() {- throw_in_this_context(dom_error("InvalidAccessError", b"Invalid encapsulation key algorithm"));+ queue_crypto_rejection(+ vm,+ realm,+ promise,+ dom_error("InvalidAccessError", b"Invalid encapsulation key algorithm"),+ );return;}// 11. If the [[usages]] internal slot of encapsulationKey does not contain an entry that is "encapsulateKey", then// throw an InvalidAccessError.if !encapsulation_key.internal_usages().contains(&KeyUsage::EncapsulateKey) {- throw_in_this_context(dom_error("InvalidAccessError", b"Invalid encapsulation key usage"));+ queue_crypto_rejection(+ vm,+ realm,+ promise,+ dom_error("InvalidAccessError", b"Invalid encapsulation key usage"),+ );return;}@@ -2094,7 +2069,7 @@ impl SubtleCrypto {encapsulation_key,);if let Err(error) = maybe_encapsulated_bits {- throw_in_this_context(error);+ queue_crypto_rejection(vm, realm, promise, error);return;}let encapsulated_bits = maybe_encapsulated_bits.must();@@ -2115,7 +2090,7 @@ impl SubtleCrypto {&usages,);if let Err(error) = maybe_shared_key {- throw_in_this_context(error);+ queue_crypto_rejection(vm, realm, promise, error);return;}// FIXME: 14. If usages is empty, then throw a SyntaxError.@@ -2200,32 +2175,27 @@ impl SubtleCrypto {with_temporary_execution_context_and_callbacks(realm, || {// 7. If the following steps or referenced procedures say to throw an error, queue a global task on the crypto task// source, given realm's global object, to reject promise with the returned error; and then terminate the algorithm.- let throw_in_this_context = |exception: Exception| {- let value = exception.throw(&CallContext::new(vm, realm)).value();- queue_a_global_task(- vm,- realm.global_object(),- TaskSource::Crypto,- (realm, promise, value),- |vm, (realm, promise, value)| {- with_temporary_execution_context_and_callbacks(realm, || {- reject_promise(vm, promise, value);- });- },- );- };-// 8. If the name member of normalizedEncapsulationAlgorithm is not equal to the name attribute of the [[algorithm]]// internal slot of encapsulationKey then throw an InvalidAccessError.if normalized_encapsulation_algorithm.parameter.name != encapsulation_key.algorithm_name() {- throw_in_this_context(dom_error("InvalidAccessError", b"Invalid encapsulation key algorithm"));+ queue_crypto_rejection(+ vm,+ realm,+ promise,+ dom_error("InvalidAccessError", b"Invalid encapsulation key algorithm"),+ );return;}// 9. If the [[usages]] internal slot of encapsulationKey does not contain an entry that is "encapsulateBits", then// throw an InvalidAccessError.if !encapsulation_key.internal_usages().contains(&KeyUsage::EncapsulateBits) {- throw_in_this_context(dom_error("InvalidAccessError", b"Invalid encapsulation key usages"));+ queue_crypto_rejection(+ vm,+ realm,+ promise,+ dom_error("InvalidAccessError", b"Invalid encapsulation key usages"),+ );return;}@@ -2237,7 +2207,7 @@ impl SubtleCrypto {encapsulation_key,);if let Err(error) = maybe_encapsulated_bits {- throw_in_this_context(error);+ queue_crypto_rejection(vm, realm, promise, error);return;}let encapsulated_bits = maybe_encapsulated_bits.must();@@ -2346,32 +2316,27 @@ impl SubtleCrypto {with_temporary_execution_context_and_callbacks(realm, || {// 10. If the following steps or referenced procedures say to throw an error, queue a global task on the crypto task// source, given realm's global object, to reject promise with the returned error; and then terminate the algorithm.- let throw_in_this_context = |exception: Exception| {- let value = exception.throw(&CallContext::new(vm, realm)).value();- queue_a_global_task(- vm,- realm.global_object(),- TaskSource::Crypto,- (realm, promise, value),- |vm, (realm, promise, value)| {- with_temporary_execution_context_and_callbacks(realm, || {- reject_promise(vm, promise, value);- });- },- );- };-// 11. If the name member of normalizedDecapsulationAlgorithm is not equal to the name attribute of the [[algorithm]]// internal slot of decapsulationKey then throw an InvalidAccessError.if normalized_decapsulation_algorithm.parameter.name != decapsulation_key.algorithm_name() {- throw_in_this_context(dom_error("InvalidAccessError", b"Invalid algorithm name"));+ queue_crypto_rejection(+ vm,+ realm,+ promise,+ dom_error("InvalidAccessError", b"Invalid algorithm name"),+ );return;}// 12. If the [[usages]] internal slot of decapsulationKey does not contain an entry that is "decapsulateKey", then// throw an InvalidAccessError.if !decapsulation_key.internal_usages().contains(&KeyUsage::DecapsulateKey) {- throw_in_this_context(dom_error("InvalidAccessError", b"Invalid key usages"));+ queue_crypto_rejection(+ vm,+ realm,+ promise,+ dom_error("InvalidAccessError", b"Invalid key usages"),+ );return;}// 13. Let decapsulatedBits be the result of performing the decapsulate operation specified by the [[algorithm]]@@ -2383,7 +2348,7 @@ impl SubtleCrypto {&cipher_text,);if let Err(error) = maybe_decapsulated_bits {- throw_in_this_context(error);+ queue_crypto_rejection(vm, realm, promise, error);return;}let decapsulated_bits = maybe_decapsulated_bits.must();@@ -2400,7 +2365,7 @@ impl SubtleCrypto {&usages,);if let Err(error) = maybe_shared_key {- throw_in_this_context(error);+ queue_crypto_rejection(vm, realm, promise, error);return;}// FIXME: 15. If usages is empty, then throw a SyntaxError.@@ -2485,32 +2450,27 @@ impl SubtleCrypto {with_temporary_execution_context_and_callbacks(realm, || {// 8. If the following steps or referenced procedures say to throw an error, queue a global task on the crypto task// source, given realm's global object, to reject promise with the returned error; and then terminate the algorithm.- let throw_in_this_context = |exception: Exception| {- let value = exception.throw(&CallContext::new(vm, realm)).value();- queue_a_global_task(- vm,- realm.global_object(),- TaskSource::Crypto,- (realm, promise, value),- |vm, (realm, promise, value)| {- with_temporary_execution_context_and_callbacks(realm, || {- reject_promise(vm, promise, value);- });- },- );- };-// 9. If the name member of normalizedDecapsulationAlgorithm is not equal to the name attribute of the [[algorithm]]// internal slot of decapsulationKey then throw an InvalidAccessError.if normalized_decapsulation_algorithm.parameter.name != decapsulation_key.algorithm_name() {- throw_in_this_context(dom_error("InvalidAccessError", b"Invalid algorithm name"));+ queue_crypto_rejection(+ vm,+ realm,+ promise,+ dom_error("InvalidAccessError", b"Invalid algorithm name"),+ );return;}// 10. If the [[usages]] internal slot of decapsulationKey does not contain an entry that is "decapsulateBits", then// throw an InvalidAccessError.if !decapsulation_key.internal_usages().contains(&KeyUsage::DecapsulateBits) {- throw_in_this_context(dom_error("InvalidAccessError", b"Invalid key usages"));+ queue_crypto_rejection(+ vm,+ realm,+ promise,+ dom_error("InvalidAccessError", b"Invalid key usages"),+ );return;}@@ -2523,7 +2483,7 @@ impl SubtleCrypto {&cipher_text,);if let Err(error) = maybe_decapsulated_bits {- throw_in_this_context(error);+ queue_crypto_rejection(vm, realm, promise, error);return;}let decapsulated_bits = maybe_decapsulated_bits.must();@@ -2607,24 +2567,14 @@ impl SubtleCrypto {// 7. If the following steps or referenced procedures say to throw an error, queue a global task on the crypto// task source, given realm's global object, to reject promise with the returned error; and then terminate// the algorithm.- let throw_in_this_context = |exception: Exception| {- let value = exception.throw(&CallContext::new(vm, realm)).value();- queue_a_global_task(- vm,- realm.global_object(),- TaskSource::Crypto,- (realm, promise, value),- |vm, (realm, promise, value)| {- with_temporary_execution_context_and_callbacks(realm, || {- reject_promise(vm, promise, value);- });- },- );- };-// 8. If the [[type]] internal slot of key is not "private", then throw an InvalidAccessError.if key.key_type() != KeyType::Private {- throw_in_this_context(dom_error("InvalidAccessError", b"Key is not a private key"));+ queue_crypto_rejection(+ vm,+ realm,+ promise,+ dom_error("InvalidAccessError", b"Key is not a private key"),+ );return;}@@ -2632,7 +2582,12 @@ impl SubtleCrypto {// algorithm, then throw a SyntaxError.for usage in &key_usages {if !public_key_usages.contains(usage) {- throw_in_this_context(dom_error("SyntaxError", b"Invalid key usage for a public key"));+ queue_crypto_rejection(+ vm,+ realm,+ promise,+ dom_error("SyntaxError", b"Invalid key usage for a public key"),+ );return;}}@@ -2643,7 +2598,12 @@ impl SubtleCrypto {// 11. If an error occurred, then throw a OperationError.if public_key_data.is_none() {- throw_in_this_context(dom_error("OperationError", b"Failed to derive the public key"));+ queue_crypto_rejection(+ vm,+ realm,+ promise,+ dom_error("OperationError", b"Failed to derive the public key"),+ );return;}let public_key = public_key_data.expect("the public key was derived");@@ -3028,333 +2988,138 @@ fn supported_algorithms() -> &'static SupportedAlgorithmsMap {// https://w3c.github.io/webcrypto/#algorithm-conventions// https://w3c.github.io/webcrypto/#rsassa-pkcs1-registration- define_an_algorithm(- &mut internal_object,- "sign",- "RSASSA-PKCS1-v1_5",- RegisteredAlgorithm::RsassaPkcs1(RsaParameterType::Base),- );- define_an_algorithm(- &mut internal_object,- "verify",- "RSASSA-PKCS1-v1_5",- RegisteredAlgorithm::RsassaPkcs1(RsaParameterType::Base),- );- define_an_algorithm(- &mut internal_object,- "generateKey",- "RSASSA-PKCS1-v1_5",- RegisteredAlgorithm::RsassaPkcs1(RsaParameterType::KeyGen),- );- define_an_algorithm(- &mut internal_object,- "importKey",- "RSASSA-PKCS1-v1_5",- RegisteredAlgorithm::RsassaPkcs1(RsaParameterType::Import),- );- define_an_algorithm(- &mut internal_object,- "exportKey",- "RSASSA-PKCS1-v1_5",- RegisteredAlgorithm::RsassaPkcs1(RsaParameterType::Base),- );+ for (operation, registered_algorithm) in [+ ("sign", RegisteredAlgorithm::RsassaPkcs1(RsaParameterType::Base)),+ ("verify", RegisteredAlgorithm::RsassaPkcs1(RsaParameterType::Base)),+ (+ "generateKey",+ RegisteredAlgorithm::RsassaPkcs1(RsaParameterType::KeyGen),+ ),+ ("importKey", RegisteredAlgorithm::RsassaPkcs1(RsaParameterType::Import)),+ ("exportKey", RegisteredAlgorithm::RsassaPkcs1(RsaParameterType::Base)),+ ] {+ define_an_algorithm(+ &mut internal_object,+ operation,+ "RSASSA-PKCS1-v1_5",+ registered_algorithm,+ );+ }// https://w3c.github.io/webcrypto/#rsa-pss-registration- define_an_algorithm(- &mut internal_object,- "sign",- "RSA-PSS",- RegisteredAlgorithm::RsaPss(RsaParameterType::Pss),- );- define_an_algorithm(- &mut internal_object,- "verify",- "RSA-PSS",- RegisteredAlgorithm::RsaPss(RsaParameterType::Pss),- );- define_an_algorithm(- &mut internal_object,- "generateKey",- "RSA-PSS",- RegisteredAlgorithm::RsaPss(RsaParameterType::KeyGen),- );- define_an_algorithm(- &mut internal_object,- "importKey",- "RSA-PSS",- RegisteredAlgorithm::RsaPss(RsaParameterType::Import),- );- define_an_algorithm(- &mut internal_object,- "exportKey",- "RSA-PSS",- RegisteredAlgorithm::RsaPss(RsaParameterType::Base),- );+ for (operation, registered_algorithm) in [+ ("sign", RegisteredAlgorithm::RsaPss(RsaParameterType::Pss)),+ ("verify", RegisteredAlgorithm::RsaPss(RsaParameterType::Pss)),+ ("generateKey", RegisteredAlgorithm::RsaPss(RsaParameterType::KeyGen)),+ ("importKey", RegisteredAlgorithm::RsaPss(RsaParameterType::Import)),+ ("exportKey", RegisteredAlgorithm::RsaPss(RsaParameterType::Base)),+ ] {+ define_an_algorithm(&mut internal_object, operation, "RSA-PSS", registered_algorithm);+ }// https://w3c.github.io/webcrypto/#rsa-oaep-registration- define_an_algorithm(- &mut internal_object,- "encrypt",- "RSA-OAEP",- RegisteredAlgorithm::RsaOaep(RsaParameterType::Oaep),- );- define_an_algorithm(- &mut internal_object,- "decrypt",- "RSA-OAEP",- RegisteredAlgorithm::RsaOaep(RsaParameterType::Oaep),- );- define_an_algorithm(- &mut internal_object,- "generateKey",- "RSA-OAEP",- RegisteredAlgorithm::RsaOaep(RsaParameterType::KeyGen),- );- define_an_algorithm(- &mut internal_object,- "importKey",- "RSA-OAEP",- RegisteredAlgorithm::RsaOaep(RsaParameterType::Import),- );- define_an_algorithm(- &mut internal_object,- "exportKey",- "RSA-OAEP",- RegisteredAlgorithm::RsaOaep(RsaParameterType::Base),- );+ for (operation, registered_algorithm) in [+ ("encrypt", RegisteredAlgorithm::RsaOaep(RsaParameterType::Oaep)),+ ("decrypt", RegisteredAlgorithm::RsaOaep(RsaParameterType::Oaep)),+ ("generateKey", RegisteredAlgorithm::RsaOaep(RsaParameterType::KeyGen)),+ ("importKey", RegisteredAlgorithm::RsaOaep(RsaParameterType::Import)),+ ("exportKey", RegisteredAlgorithm::RsaOaep(RsaParameterType::Base)),+ ] {+ define_an_algorithm(&mut internal_object, operation, "RSA-OAEP", registered_algorithm);+ }// https://w3c.github.io/webcrypto/#ecdsa-registration- define_an_algorithm(- &mut internal_object,- "sign",- "ECDSA",- RegisteredAlgorithm::Ecdsa(EcParameterType::SignOrVerify),- );- define_an_algorithm(- &mut internal_object,- "verify",- "ECDSA",- RegisteredAlgorithm::Ecdsa(EcParameterType::SignOrVerify),- );- define_an_algorithm(- &mut internal_object,- "generateKey",- "ECDSA",- RegisteredAlgorithm::Ecdsa(EcParameterType::KeyGen),- );- define_an_algorithm(- &mut internal_object,- "importKey",- "ECDSA",- RegisteredAlgorithm::Ecdsa(EcParameterType::Import),- );- define_an_algorithm(- &mut internal_object,- "exportKey",- "ECDSA",- RegisteredAlgorithm::Ecdsa(EcParameterType::Base),- );+ for (operation, registered_algorithm) in [+ ("sign", RegisteredAlgorithm::Ecdsa(EcParameterType::SignOrVerify)),+ ("verify", RegisteredAlgorithm::Ecdsa(EcParameterType::SignOrVerify)),+ ("generateKey", RegisteredAlgorithm::Ecdsa(EcParameterType::KeyGen)),+ ("importKey", RegisteredAlgorithm::Ecdsa(EcParameterType::Import)),+ ("exportKey", RegisteredAlgorithm::Ecdsa(EcParameterType::Base)),+ ] {+ define_an_algorithm(&mut internal_object, operation, "ECDSA", registered_algorithm);+ }// https://w3c.github.io/webcrypto/#ecdh-registration- define_an_algorithm(- &mut internal_object,- "importKey",- "ECDH",- RegisteredAlgorithm::Ecdh(EcParameterType::Import),- );- define_an_algorithm(- &mut internal_object,- "exportKey",- "ECDH",- RegisteredAlgorithm::Ecdh(EcParameterType::Base),- );- define_an_algorithm(- &mut internal_object,- "deriveBits",- "ECDH",- RegisteredAlgorithm::Ecdh(EcParameterType::Derive),- );- define_an_algorithm(- &mut internal_object,- "generateKey",- "ECDH",- RegisteredAlgorithm::Ecdh(EcParameterType::KeyGen),- );+ for (operation, registered_algorithm) in [+ ("importKey", RegisteredAlgorithm::Ecdh(EcParameterType::Import)),+ ("exportKey", RegisteredAlgorithm::Ecdh(EcParameterType::Base)),+ ("deriveBits", RegisteredAlgorithm::Ecdh(EcParameterType::Derive)),+ ("generateKey", RegisteredAlgorithm::Ecdh(EcParameterType::KeyGen)),+ ] {+ define_an_algorithm(&mut internal_object, operation, "ECDH", registered_algorithm);+ }// https://w3c.github.io/webcrypto/#aes-ctr-registration- define_an_algorithm(- &mut internal_object,- "encrypt",- "AES-CTR",- RegisteredAlgorithm::AesCtr(AesParameterType::Ctr),- );- define_an_algorithm(- &mut internal_object,- "decrypt",- "AES-CTR",- RegisteredAlgorithm::AesCtr(AesParameterType::Ctr),- );- define_an_algorithm(- &mut internal_object,- "generateKey",- "AES-CTR",- RegisteredAlgorithm::AesCtr(AesParameterType::KeyGen),- );- define_an_algorithm(- &mut internal_object,- "importKey",- "AES-CTR",- RegisteredAlgorithm::AesCtr(AesParameterType::Base),- );- define_an_algorithm(- &mut internal_object,- "exportKey",- "AES-CTR",- RegisteredAlgorithm::AesCtr(AesParameterType::Base),- );- define_an_algorithm(- &mut internal_object,- "get key length",- "AES-CTR",- RegisteredAlgorithm::AesCtr(AesParameterType::DerivedKey),- );+ for (operation, registered_algorithm) in [+ ("encrypt", RegisteredAlgorithm::AesCtr(AesParameterType::Ctr)),+ ("decrypt", RegisteredAlgorithm::AesCtr(AesParameterType::Ctr)),+ ("generateKey", RegisteredAlgorithm::AesCtr(AesParameterType::KeyGen)),+ ("importKey", RegisteredAlgorithm::AesCtr(AesParameterType::Base)),+ ("exportKey", RegisteredAlgorithm::AesCtr(AesParameterType::Base)),+ (+ "get key length",+ RegisteredAlgorithm::AesCtr(AesParameterType::DerivedKey),+ ),+ ] {+ define_an_algorithm(&mut internal_object, operation, "AES-CTR", registered_algorithm);+ }// https://w3c.github.io/webcrypto/#aes-cbc-registration- define_an_algorithm(- &mut internal_object,- "encrypt",- "AES-CBC",- RegisteredAlgorithm::AesCbc(AesParameterType::Cbc),- );- define_an_algorithm(- &mut internal_object,- "decrypt",- "AES-CBC",- RegisteredAlgorithm::AesCbc(AesParameterType::Cbc),- );- define_an_algorithm(- &mut internal_object,- "generateKey",- "AES-CBC",- RegisteredAlgorithm::AesCbc(AesParameterType::KeyGen),- );- define_an_algorithm(- &mut internal_object,- "importKey",- "AES-CBC",- RegisteredAlgorithm::AesCbc(AesParameterType::Base),- );- define_an_algorithm(- &mut internal_object,- "exportKey",- "AES-CBC",- RegisteredAlgorithm::AesCbc(AesParameterType::Base),- );- define_an_algorithm(- &mut internal_object,- "get key length",- "AES-CBC",- RegisteredAlgorithm::AesCbc(AesParameterType::DerivedKey),- );+ for (operation, registered_algorithm) in [+ ("encrypt", RegisteredAlgorithm::AesCbc(AesParameterType::Cbc)),+ ("decrypt", RegisteredAlgorithm::AesCbc(AesParameterType::Cbc)),+ ("generateKey", RegisteredAlgorithm::AesCbc(AesParameterType::KeyGen)),+ ("importKey", RegisteredAlgorithm::AesCbc(AesParameterType::Base)),+ ("exportKey", RegisteredAlgorithm::AesCbc(AesParameterType::Base)),+ (+ "get key length",+ RegisteredAlgorithm::AesCbc(AesParameterType::DerivedKey),+ ),+ ] {+ define_an_algorithm(&mut internal_object, operation, "AES-CBC", registered_algorithm);+ }// https://w3c.github.io/webcrypto/#aes-gcm-registration- define_an_algorithm(- &mut internal_object,- "encrypt",- "AES-GCM",- RegisteredAlgorithm::AesGcm(AesParameterType::Gcm),- );- define_an_algorithm(- &mut internal_object,- "decrypt",- "AES-GCM",- RegisteredAlgorithm::AesGcm(AesParameterType::Gcm),- );- define_an_algorithm(- &mut internal_object,- "generateKey",- "AES-GCM",- RegisteredAlgorithm::AesGcm(AesParameterType::KeyGen),- );- define_an_algorithm(- &mut internal_object,- "importKey",- "AES-GCM",- RegisteredAlgorithm::AesGcm(AesParameterType::Base),- );- define_an_algorithm(- &mut internal_object,- "exportKey",- "AES-GCM",- RegisteredAlgorithm::AesGcm(AesParameterType::Base),- );- define_an_algorithm(- &mut internal_object,- "get key length",- "AES-GCM",- RegisteredAlgorithm::AesGcm(AesParameterType::DerivedKey),- );+ for (operation, registered_algorithm) in [+ ("encrypt", RegisteredAlgorithm::AesGcm(AesParameterType::Gcm)),+ ("decrypt", RegisteredAlgorithm::AesGcm(AesParameterType::Gcm)),+ ("generateKey", RegisteredAlgorithm::AesGcm(AesParameterType::KeyGen)),+ ("importKey", RegisteredAlgorithm::AesGcm(AesParameterType::Base)),+ ("exportKey", RegisteredAlgorithm::AesGcm(AesParameterType::Base)),+ (+ "get key length",+ RegisteredAlgorithm::AesGcm(AesParameterType::DerivedKey),+ ),+ ] {+ define_an_algorithm(&mut internal_object, operation, "AES-GCM", registered_algorithm);+ }// https://w3c.github.io/webcrypto/#aes-kw-registration- define_an_algorithm(- &mut internal_object,- "wrapKey",- "AES-KW",- RegisteredAlgorithm::AesKw(AesParameterType::Base),- );- define_an_algorithm(- &mut internal_object,- "unwrapKey",- "AES-KW",- RegisteredAlgorithm::AesKw(AesParameterType::Base),- );- define_an_algorithm(- &mut internal_object,- "generateKey",- "AES-KW",- RegisteredAlgorithm::AesKw(AesParameterType::KeyGen),- );- define_an_algorithm(- &mut internal_object,- "importKey",- "AES-KW",- RegisteredAlgorithm::AesKw(AesParameterType::Base),- );- define_an_algorithm(- &mut internal_object,- "exportKey",- "AES-KW",- RegisteredAlgorithm::AesKw(AesParameterType::Base),- );- define_an_algorithm(- &mut internal_object,- "get key length",- "AES-KW",- RegisteredAlgorithm::AesKw(AesParameterType::DerivedKey),- );+ for (operation, registered_algorithm) in [+ ("wrapKey", RegisteredAlgorithm::AesKw(AesParameterType::Base)),+ ("unwrapKey", RegisteredAlgorithm::AesKw(AesParameterType::Base)),+ ("generateKey", RegisteredAlgorithm::AesKw(AesParameterType::KeyGen)),+ ("importKey", RegisteredAlgorithm::AesKw(AesParameterType::Base)),+ ("exportKey", RegisteredAlgorithm::AesKw(AesParameterType::Base)),+ (+ "get key length",+ RegisteredAlgorithm::AesKw(AesParameterType::DerivedKey),+ ),+ ] {+ define_an_algorithm(&mut internal_object, operation, "AES-KW", registered_algorithm);+ }// https://w3c.github.io/webcrypto/#hmac-registration- define_an_algorithm(&mut internal_object, "sign", "HMAC", RegisteredAlgorithm::Hmac);- define_an_algorithm(&mut internal_object, "verify", "HMAC", RegisteredAlgorithm::Hmac);- define_an_algorithm(- &mut internal_object,- "generateKey",- "HMAC",- RegisteredAlgorithm::HmacKeyGen,- );- define_an_algorithm(- &mut internal_object,- "importKey",- "HMAC",- RegisteredAlgorithm::HmacImport,- );- define_an_algorithm(&mut internal_object, "exportKey", "HMAC", RegisteredAlgorithm::Hmac);- define_an_algorithm(- &mut internal_object,- "get key length",- "HMAC",- RegisteredAlgorithm::HmacImport,- );+ for (operation, registered_algorithm) in [+ ("sign", RegisteredAlgorithm::Hmac),+ ("verify", RegisteredAlgorithm::Hmac),+ ("generateKey", RegisteredAlgorithm::HmacKeyGen),+ ("importKey", RegisteredAlgorithm::HmacImport),+ ("exportKey", RegisteredAlgorithm::Hmac),+ ("get key length", RegisteredAlgorithm::HmacImport),+ ] {+ define_an_algorithm(&mut internal_object, operation, "HMAC", registered_algorithm);+ }// https://w3c.github.io/webcrypto/#sha-registrationdefine_an_algorithm(&mut internal_object, "digest", "SHA-1", RegisteredAlgorithm::Sha);@@ -3372,306 +3137,147 @@ fn supported_algorithms() -> &'static SupportedAlgorithmsMap {define_an_algorithm(&mut internal_object, "digest", "cSHAKE256", RegisteredAlgorithm::CShake);// https://w3c.github.io/webcrypto/#hkdf-registration- define_an_algorithm(- &mut internal_object,- "deriveBits",- "HKDF",- RegisteredAlgorithm::HkdfParams,- );- define_an_algorithm(&mut internal_object, "importKey", "HKDF", RegisteredAlgorithm::Hkdf);- define_an_algorithm(- &mut internal_object,- "get key length",- "HKDF",- RegisteredAlgorithm::Hkdf,- );+ for (operation, registered_algorithm) in [+ ("deriveBits", RegisteredAlgorithm::HkdfParams),+ ("importKey", RegisteredAlgorithm::Hkdf),+ ("get key length", RegisteredAlgorithm::Hkdf),+ ] {+ define_an_algorithm(&mut internal_object, operation, "HKDF", registered_algorithm);+ }// https://w3c.github.io/webcrypto/#pbkdf2-registration- define_an_algorithm(- &mut internal_object,- "deriveBits",- "PBKDF2",- RegisteredAlgorithm::Pbkdf2Params,- );- define_an_algorithm(&mut internal_object, "importKey", "PBKDF2", RegisteredAlgorithm::Pbkdf2);- define_an_algorithm(- &mut internal_object,- "get key length",- "PBKDF2",- RegisteredAlgorithm::Pbkdf2,- );+ for (operation, registered_algorithm) in [+ ("deriveBits", RegisteredAlgorithm::Pbkdf2Params),+ ("importKey", RegisteredAlgorithm::Pbkdf2),+ ("get key length", RegisteredAlgorithm::Pbkdf2),+ ] {+ define_an_algorithm(&mut internal_object, operation, "PBKDF2", registered_algorithm);+ }// https://wicg.github.io/webcrypto-secure-curves/#x25519-registration- define_an_algorithm(- &mut internal_object,- "deriveBits",- "X25519",- RegisteredAlgorithm::X25519(true),- );- define_an_algorithm(- &mut internal_object,- "generateKey",- "X25519",- RegisteredAlgorithm::X25519(false),- );- define_an_algorithm(- &mut internal_object,- "importKey",- "X25519",- RegisteredAlgorithm::X25519(false),- );- define_an_algorithm(- &mut internal_object,- "exportKey",- "X25519",- RegisteredAlgorithm::X25519(false),- );+ for (operation, registered_algorithm) in [+ ("deriveBits", RegisteredAlgorithm::X25519(true)),+ ("generateKey", RegisteredAlgorithm::X25519(false)),+ ("importKey", RegisteredAlgorithm::X25519(false)),+ ("exportKey", RegisteredAlgorithm::X25519(false)),+ ] {+ define_an_algorithm(&mut internal_object, operation, "X25519", registered_algorithm);+ }// https://wicg.github.io/webcrypto-secure-curves/#x448-registration- define_an_algorithm(- &mut internal_object,- "deriveBits",- "X448",- RegisteredAlgorithm::X448(true),- );- define_an_algorithm(- &mut internal_object,- "generateKey",- "X448",- RegisteredAlgorithm::X448(false),- );- define_an_algorithm(- &mut internal_object,- "importKey",- "X448",- RegisteredAlgorithm::X448(false),- );- define_an_algorithm(- &mut internal_object,- "exportKey",- "X448",- RegisteredAlgorithm::X448(false),- );+ for (operation, registered_algorithm) in [+ ("deriveBits", RegisteredAlgorithm::X448(true)),+ ("generateKey", RegisteredAlgorithm::X448(false)),+ ("importKey", RegisteredAlgorithm::X448(false)),+ ("exportKey", RegisteredAlgorithm::X448(false)),+ ] {+ define_an_algorithm(&mut internal_object, operation, "X448", registered_algorithm);+ }// https://wicg.github.io/webcrypto-secure-curves/#ed25519-registration- define_an_algorithm(&mut internal_object, "sign", "Ed25519", RegisteredAlgorithm::Ed25519);- define_an_algorithm(&mut internal_object, "verify", "Ed25519", RegisteredAlgorithm::Ed25519);- define_an_algorithm(- &mut internal_object,- "generateKey",- "Ed25519",- RegisteredAlgorithm::Ed25519,- );- define_an_algorithm(- &mut internal_object,- "importKey",- "Ed25519",- RegisteredAlgorithm::Ed25519,- );- define_an_algorithm(- &mut internal_object,- "exportKey",- "Ed25519",- RegisteredAlgorithm::Ed25519,- );+ for (operation, registered_algorithm) in [+ ("sign", RegisteredAlgorithm::Ed25519),+ ("verify", RegisteredAlgorithm::Ed25519),+ ("generateKey", RegisteredAlgorithm::Ed25519),+ ("importKey", RegisteredAlgorithm::Ed25519),+ ("exportKey", RegisteredAlgorithm::Ed25519),+ ] {+ define_an_algorithm(&mut internal_object, operation, "Ed25519", registered_algorithm);+ }// https://wicg.github.io/webcrypto-secure-curves/#ed448-registration- define_an_algorithm(&mut internal_object, "sign", "Ed448", RegisteredAlgorithm::Ed448(true));- define_an_algorithm(- &mut internal_object,- "verify",- "Ed448",- RegisteredAlgorithm::Ed448(true),- );- define_an_algorithm(- &mut internal_object,- "generateKey",- "Ed448",- RegisteredAlgorithm::Ed448(false),- );- define_an_algorithm(- &mut internal_object,- "importKey",- "Ed448",- RegisteredAlgorithm::Ed448(false),- );- define_an_algorithm(- &mut internal_object,- "exportKey",- "Ed448",- RegisteredAlgorithm::Ed448(false),- );+ for (operation, registered_algorithm) in [+ ("sign", RegisteredAlgorithm::Ed448(true)),+ ("verify", RegisteredAlgorithm::Ed448(true)),+ ("generateKey", RegisteredAlgorithm::Ed448(false)),+ ("importKey", RegisteredAlgorithm::Ed448(false)),+ ("exportKey", RegisteredAlgorithm::Ed448(false)),+ ] {+ define_an_algorithm(&mut internal_object, operation, "Ed448", registered_algorithm);+ }// https://wicg.github.io/webcrypto-modern-algos/#ml-dsa-registrationfor name in ["ML-DSA-44", "ML-DSA-65", "ML-DSA-87"] {- define_an_algorithm(&mut internal_object, "sign", name, RegisteredAlgorithm::MlDsa(true));- define_an_algorithm(&mut internal_object, "verify", name, RegisteredAlgorithm::MlDsa(true));- define_an_algorithm(- &mut internal_object,- "generateKey",- name,- RegisteredAlgorithm::MlDsa(false),- );- define_an_algorithm(- &mut internal_object,- "importKey",- name,- RegisteredAlgorithm::MlDsa(false),- );- define_an_algorithm(- &mut internal_object,- "exportKey",- name,- RegisteredAlgorithm::MlDsa(false),- );+ for (operation, registered_algorithm) in [+ ("sign", RegisteredAlgorithm::MlDsa(true)),+ ("verify", RegisteredAlgorithm::MlDsa(true)),+ ("generateKey", RegisteredAlgorithm::MlDsa(false)),+ ("importKey", RegisteredAlgorithm::MlDsa(false)),+ ("exportKey", RegisteredAlgorithm::MlDsa(false)),+ ] {+ define_an_algorithm(&mut internal_object, operation, name, registered_algorithm);+ }}// https://wicg.github.io/webcrypto-modern-algos/#ml-kem-registrationfor name in ["ML-KEM-512", "ML-KEM-768", "ML-KEM-1024"] {- define_an_algorithm(&mut internal_object, "generateKey", name, RegisteredAlgorithm::MlKem);- define_an_algorithm(&mut internal_object, "importKey", name, RegisteredAlgorithm::MlKem);- define_an_algorithm(&mut internal_object, "exportKey", name, RegisteredAlgorithm::MlKem);- define_an_algorithm(&mut internal_object, "encapsulate", name, RegisteredAlgorithm::MlKem);- define_an_algorithm(&mut internal_object, "decapsulate", name, RegisteredAlgorithm::MlKem);- define_an_algorithm(- &mut internal_object,- "get shared key length",- name,- RegisteredAlgorithm::MlKem,- );+ for (operation, registered_algorithm) in [+ ("generateKey", RegisteredAlgorithm::MlKem),+ ("importKey", RegisteredAlgorithm::MlKem),+ ("exportKey", RegisteredAlgorithm::MlKem),+ ("encapsulate", RegisteredAlgorithm::MlKem),+ ("decapsulate", RegisteredAlgorithm::MlKem),+ ("get shared key length", RegisteredAlgorithm::MlKem),+ ] {+ define_an_algorithm(&mut internal_object, operation, name, registered_algorithm);+ }}// https://wicg.github.io/webcrypto-modern-algos/#argon2-registrationfor algorithm in ["Argon2d", "Argon2i", "Argon2id"] {+ for (operation, registered_algorithm) in [+ ("importKey", RegisteredAlgorithm::Argon2),+ ("deriveBits", RegisteredAlgorithm::Argon2Params),+ ("get key length", RegisteredAlgorithm::Argon2),+ ] {+ define_an_algorithm(&mut internal_object, operation, algorithm, registered_algorithm);+ }+ }++ // https://wicg.github.io/webcrypto-modern-algos/#chacha20-poly1305-registration+ for (operation, registered_algorithm) in [+ ("encrypt", RegisteredAlgorithm::ChaCha20Poly1305Aead),+ ("decrypt", RegisteredAlgorithm::ChaCha20Poly1305Aead),+ ("generateKey", RegisteredAlgorithm::ChaCha20Poly1305),+ ("importKey", RegisteredAlgorithm::ChaCha20Poly1305),+ ("exportKey", RegisteredAlgorithm::ChaCha20Poly1305),+ ("get key length", RegisteredAlgorithm::ChaCha20Poly1305),+ ] {define_an_algorithm(&mut internal_object,- "importKey",- algorithm,- RegisteredAlgorithm::Argon2,- );- define_an_algorithm(- &mut internal_object,- "deriveBits",- algorithm,- RegisteredAlgorithm::Argon2Params,- );- define_an_algorithm(- &mut internal_object,- "get key length",- algorithm,- RegisteredAlgorithm::Argon2,+ operation,+ "ChaCha20-Poly1305",+ registered_algorithm,);}- // https://wicg.github.io/webcrypto-modern-algos/#chacha20-poly1305-registration- define_an_algorithm(- &mut internal_object,- "encrypt",- "ChaCha20-Poly1305",- RegisteredAlgorithm::ChaCha20Poly1305Aead,- );- define_an_algorithm(- &mut internal_object,- "decrypt",- "ChaCha20-Poly1305",- RegisteredAlgorithm::ChaCha20Poly1305Aead,- );- define_an_algorithm(- &mut internal_object,- "generateKey",- "ChaCha20-Poly1305",- RegisteredAlgorithm::ChaCha20Poly1305,- );- define_an_algorithm(- &mut internal_object,- "importKey",- "ChaCha20-Poly1305",- RegisteredAlgorithm::ChaCha20Poly1305,- );- define_an_algorithm(- &mut internal_object,- "exportKey",- "ChaCha20-Poly1305",- RegisteredAlgorithm::ChaCha20Poly1305,- );- define_an_algorithm(- &mut internal_object,- "get key length",- "ChaCha20-Poly1305",- RegisteredAlgorithm::ChaCha20Poly1305,- );-// https://wicg.github.io/webcrypto-modern-algos/#aes-ocb-registration- define_an_algorithm(- &mut internal_object,- "encrypt",- "AES-OCB",- RegisteredAlgorithm::AesOcb(AesParameterType::Aead),- );- define_an_algorithm(- &mut internal_object,- "decrypt",- "AES-OCB",- RegisteredAlgorithm::AesOcb(AesParameterType::Aead),- );- define_an_algorithm(- &mut internal_object,- "generateKey",- "AES-OCB",- RegisteredAlgorithm::AesOcb(AesParameterType::KeyGen),- );- define_an_algorithm(- &mut internal_object,- "importKey",- "AES-OCB",- RegisteredAlgorithm::AesOcb(AesParameterType::Base),- );- define_an_algorithm(- &mut internal_object,- "exportKey",- "AES-OCB",- RegisteredAlgorithm::AesOcb(AesParameterType::Base),- );- define_an_algorithm(- &mut internal_object,- "get key length",- "AES-OCB",- RegisteredAlgorithm::AesOcb(AesParameterType::DerivedKey),- );+ for (operation, registered_algorithm) in [+ ("encrypt", RegisteredAlgorithm::AesOcb(AesParameterType::Aead)),+ ("decrypt", RegisteredAlgorithm::AesOcb(AesParameterType::Aead)),+ ("generateKey", RegisteredAlgorithm::AesOcb(AesParameterType::KeyGen)),+ ("importKey", RegisteredAlgorithm::AesOcb(AesParameterType::Base)),+ ("exportKey", RegisteredAlgorithm::AesOcb(AesParameterType::Base)),+ (+ "get key length",+ RegisteredAlgorithm::AesOcb(AesParameterType::DerivedKey),+ ),+ ] {+ define_an_algorithm(&mut internal_object, operation, "AES-OCB", registered_algorithm);+ }// https://wicg.github.io/webcrypto-modern-algos/#kmac-registrationfor algorithm in ["KMAC128", "KMAC256"] {- define_an_algorithm(- &mut internal_object,- "sign",- algorithm,- RegisteredAlgorithm::KmacSignOrVerify,- );- define_an_algorithm(- &mut internal_object,- "verify",- algorithm,- RegisteredAlgorithm::KmacSignOrVerify,- );- define_an_algorithm(- &mut internal_object,- "generateKey",- algorithm,- RegisteredAlgorithm::KmacKeyGen,- );- define_an_algorithm(- &mut internal_object,- "importKey",- algorithm,- RegisteredAlgorithm::KmacImport,- );- define_an_algorithm(&mut internal_object, "exportKey", algorithm, RegisteredAlgorithm::Kmac);- define_an_algorithm(- &mut internal_object,- "get key length",- algorithm,- RegisteredAlgorithm::KmacImport,- );+ for (operation, registered_algorithm) in [+ ("sign", RegisteredAlgorithm::KmacSignOrVerify),+ ("verify", RegisteredAlgorithm::KmacSignOrVerify),+ ("generateKey", RegisteredAlgorithm::KmacKeyGen),+ ("importKey", RegisteredAlgorithm::KmacImport),+ ("exportKey", RegisteredAlgorithm::Kmac),+ ("get key length", RegisteredAlgorithm::KmacImport),+ ] {+ define_an_algorithm(&mut internal_object, operation, algorithm, registered_algorithm);+ }}internal_objectdiff --git a/Libraries/LibWeb/Crypto/CryptoAlgorithms.cpp b/Libraries/LibWeb/Crypto/CryptoAlgorithms.cppindex d546ec3dbea..83346ef8e67 100644--- a/Libraries/LibWeb/Crypto/CryptoAlgorithms.cpp+++ b/Libraries/LibWeb/Crypto/CryptoAlgorithms.cpp@@ -59,6 +59,14 @@ enum class Asn1Structure : u8 {FlatPtr web_crypto_decode_asn1_structure(ReadonlyBytes, Asn1Structure, void*, bool*);}+static bool receive_byte_result(ErrorOr<ByteBuffer> const& result, void* state, ReceiveEncodedBytes receive)+{+ if (result.is_error())+ return false;+ receive(state, result.value());+ return true;+}+int web_crypto_encode_base64url(ReadonlyBytes bytes, ReceiveEncodedBytes receive, void* state){auto encoded = encode_base64url(bytes, AK::OmitPadding::Yes);@@ -223,10 +231,7 @@ static ErrorOr<ByteBuffer> export_rsa_exponent(::Crypto::UnsignedBigInteger consbool web_crypto_rsa_export_public_exponent(ReadonlyBytes public_exponent, void* state, ReceiveEncodedBytes receive){auto bytes = export_rsa_exponent(::Crypto::UnsignedBigInteger::import_data(public_exponent));- if (bytes.is_error())- return false;- receive(state, bytes.value());- return true;+ return receive_byte_result(bytes, state, receive);}bool web_crypto_rsa_read_key_metadata(CryptoKey::InternalKeyData const* key, u32* modulus_length, void* state, ReceiveEncodedBytes receive)@@ -241,10 +246,7 @@ bool web_crypto_rsa_read_key_metadata(CryptoKey::InternalKeyData const* key, u32return export_rsa_exponent(private_key.public_exponent());},[](auto const&) -> ErrorOr<ByteBuffer> { VERIFY_NOT_REACHED(); });- if (result.is_error())- return false;- receive(state, result.value());- return true;+ return receive_byte_result(result, state, receive);}CryptoKey::InternalKeyData* web_crypto_rsa_key_from_jwk_components(bool is_private, ReadonlySpan<ReadonlyBytes> components)@@ -271,10 +273,7 @@ bool web_crypto_rsa_export_der(CryptoKey::InternalKeyData const* key, bool is_puauto result = is_public? ::Crypto::PK::wrap_in_subject_public_key_info(key->get<::Crypto::PK::RSAPublicKey>(), ::Crypto::ASN1::rsa_encryption_oid, nullptr): ::Crypto::PK::wrap_in_private_key_info(key->get<::Crypto::PK::RSAPrivateKey>(), ::Crypto::ASN1::rsa_encryption_oid, nullptr);- if (result.is_error())- return false;- receive(state, result.value());- return true;+ return receive_byte_result(result, state, receive);}bool web_crypto_rsa_export_jwk_integer(CryptoKey::InternalKeyData const* key, u8 component, void* state, ReceiveEncodedBytes receive)@@ -325,10 +324,7 @@ bool web_crypto_rsa_oaep_cipher(bool encrypt, ::Crypto::Hash::HashKind hash_kindrsa.set_label(label);return rsa.decrypt(input);}();- if (result.is_error())- return false;- receive(state, result.value());- return true;+ return receive_byte_result(result, state, receive);}bool web_crypto_rsa_pss_sign(::Crypto::Hash::HashKind hash_kind, CryptoKey::InternalKeyData const* key, u32 salt_length, ReadonlyBytes message, void* state, ReceiveEncodedBytes receive)@@ -336,10 +332,7 @@ bool web_crypto_rsa_pss_sign(::Crypto::Hash::HashKind hash_kind, CryptoKey::Inte::Crypto::PK::RSA_PSS_EMSA rsa { hash_kind, key->get<::Crypto::PK::RSAPrivateKey>() };rsa.set_salt_length(salt_length);auto result = rsa.sign(message);- if (result.is_error())- return false;- receive(state, result.value());- return true;+ return receive_byte_result(result, state, receive);}bool web_crypto_rsa_pss_verify(::Crypto::Hash::HashKind hash_kind, CryptoKey::InternalKeyData const* key, u32 salt_length, ReadonlyBytes message, ReadonlyBytes signature, bool* verified)@@ -357,10 +350,7 @@ bool web_crypto_rsa_pkcs1_sign(::Crypto::Hash::HashKind hash_kind, CryptoKey::In{::Crypto::PK::RSA_PKCS1_EMSA rsa { hash_kind, key->get<::Crypto::PK::RSAPrivateKey>() };auto result = rsa.sign(message);- if (result.is_error())- return false;- receive(state, result.value());- return true;+ return receive_byte_result(result, state, receive);}bool web_crypto_rsa_pkcs1_verify(::Crypto::Hash::HashKind hash_kind, CryptoKey::InternalKeyData const* key, ReadonlyBytes message, ReadonlyBytes signature, bool* verified)@@ -386,30 +376,21 @@ bool web_crypto_aes_cbc_cipher(bool encrypt, ReadonlyBytes key, ReadonlyBytes in{::Crypto::Cipher::AESCBCCipher cipher(key);auto result = encrypt ? cipher.encrypt(input, iv) : cipher.decrypt(input, iv);- if (result.is_error())- return false;- receive(state, result.value());- return true;+ return receive_byte_result(result, state, receive);}bool web_crypto_aes_ctr_cipher(bool encrypt, ReadonlyBytes key, ReadonlyBytes input, ReadonlyBytes counter, void* state, ReceiveEncodedBytes receive){::Crypto::Cipher::AESCTRCipher cipher(key);auto result = encrypt ? cipher.encrypt(input, counter) : cipher.decrypt(input, counter);- if (result.is_error())- return false;- receive(state, result.value());- return true;+ return receive_byte_result(result, state, receive);}bool web_crypto_aes_kw_cipher(bool wrap, ReadonlyBytes key, ReadonlyBytes input, void* state, ReceiveEncodedBytes receive){::Crypto::Cipher::AESKWCipher cipher(key);auto result = wrap ? cipher.wrap(input) : cipher.unwrap(input);- if (result.is_error())- return false;- receive(state, result.value());- return true;+ return receive_byte_result(result, state, receive);}bool web_crypto_aes_gcm_encrypt(ReadonlyBytes key, ReadonlyBytes plaintext, ReadonlyBytes iv, ReadonlyBytes additional_data, size_t tag_length, void* ciphertext, void* tag, ReceiveEncodedBytes receive)@@ -462,11 +443,7 @@ bool web_crypto_sha_digest(::Crypto::Hash::HashKind hash_kind, ReadonlyBytes datauto digest = hash.digest();auto result_buffer = ByteBuffer::copy(digest.immutable_data(), hash.digest_size());- if (result_buffer.is_error())- return false;-- receive(state, result_buffer.value());- return true;+ return receive_byte_result(result_buffer, state, receive);}struct OptionalBytes {@@ -678,19 +655,13 @@ bool web_crypto_ec_export_der(EcCurve curve, CryptoKey::InternalKeyData const* k}return ::Crypto::PK::wrap_in_private_key_info(key->get<::Crypto::PK::ECPrivateKey>(), ::Crypto::ASN1::ec_public_key_encryption_oid, ec_params);}();- if (result.is_error())- return false;- receive(state, result.value());- return true;+ return receive_byte_result(result, state, receive);}bool web_crypto_ec_export_uncompressed(CryptoKey::InternalKeyData const* key, void* state, ReceiveEncodedBytes receive){auto result = key->get<::Crypto::PK::ECPublicKey>().to_uncompressed();- if (result.is_error())- return false;- receive(state, result.value());- return true;+ return receive_byte_result(result, state, receive);}bool web_crypto_ec_export_public_coordinates(EcCurve curve_id, CryptoKey::InternalKeyData const* key, void* x, void* y, ReceiveEncodedBytes receive)@@ -718,10 +689,7 @@ bool web_crypto_ec_export_public_coordinates(EcCurve curve_id, CryptoKey::Internbool web_crypto_ec_export_private_scalar(CryptoKey::InternalKeyData const* key, void* state, ReceiveEncodedBytes receive){auto result = key->get<::Crypto::PK::ECPrivateKey>().d_bytes();- if (result.is_error())- return false;- receive(state, result.value());- return true;+ return receive_byte_result(result, state, receive);}enum class OkpCurve : u8 {@@ -776,19 +744,13 @@ bool web_crypto_okp_export_der(OkpCurve, bool, ReadonlyBytes, void*, ReceiveEncobool web_crypto_okp_generate_private_key(OkpCurve curve, void* state, ReceiveEncodedBytes receive){auto result = okp_curve(curve).generate_private_key();- if (result.is_error())- return false;- receive(state, result.value());- return true;+ return receive_byte_result(result, state, receive);}bool web_crypto_okp_generate_public_key(OkpCurve curve, ReadonlyBytes private_key, void* state, ReceiveEncodedBytes receive){auto result = okp_curve(curve).generate_public_key(private_key);- if (result.is_error())- return false;- receive(state, result.value());- return true;+ return receive_byte_result(result, state, receive);}bool web_crypto_okp_compute_coordinate(OkpCurve curve, ReadonlyBytes private_key, ReadonlyBytes public_key, void* state, ReceiveEncodedBytes receive)@@ -797,10 +759,7 @@ bool web_crypto_okp_compute_coordinate(OkpCurve curve, ReadonlyBytes private_keyauto result = curve == OkpCurve::X25519? ::Crypto::Curves::X25519 {}.compute_coordinate(private_key, public_key): ::Crypto::Curves::X448 {}.compute_coordinate(private_key, public_key);- if (result.is_error())- return false;- receive(state, result.value());- return true;+ return receive_byte_result(result, state, receive);}bool web_crypto_okp_sign(OkpCurve curve, ReadonlyBytes private_key, ReadonlyBytes message, ReadonlyBytes context, void* state, ReceiveEncodedBytes receive)@@ -809,10 +768,7 @@ bool web_crypto_okp_sign(OkpCurve curve, ReadonlyBytes private_key, ReadonlyByteauto result = curve == OkpCurve::Ed25519? ::Crypto::Curves::Ed25519 {}.sign(private_key, message): ::Crypto::Curves::Ed448 {}.sign(private_key, message, context);- if (result.is_error())- return false;- receive(state, result.value());- return true;+ return receive_byte_result(result, state, receive);}FlatPtr web_crypto_okp_verify(OkpCurve curve, ReadonlyBytes public_key, ReadonlyBytes signature, ReadonlyBytes message, ReadonlyBytes context, bool* verified)@@ -857,10 +813,7 @@ bool web_crypto_okp_export_der(OkpCurve curve, bool is_public, ReadonlyBytes keyTRY(encoder.write(key));return ::Crypto::PK::wrap_in_private_key_info(encoder.finish(), oid);}();- if (result.is_error())- return false;- receive(state, result.value());- return true;+ return receive_byte_result(result, state, receive);}extern "C" {@@ -906,10 +859,7 @@ bool web_crypto_mldsa_sign(::Crypto::PK::MLDSASize size, CryptoKey::InternalKeyD{::Crypto::PK::MLDSA lattice(size, key->get<::Crypto::PK::MLDSAPrivateKey>(), MUST(ByteBuffer::copy(context)));auto result = lattice.sign(message);- if (result.is_error())- return false;- receive(state, result.value());- return true;+ return receive_byte_result(result, state, receive);}bool web_crypto_mldsa_verify(::Crypto::PK::MLDSASize size, CryptoKey::InternalKeyData const* key, ReadonlyBytes message, ReadonlyBytes signature, ReadonlyBytes context, bool* verified)@@ -965,10 +915,7 @@ bool web_crypto_mldsa_export_der(CryptoKey::InternalKeyData const* key, bool is_auto result = is_public? ::Crypto::PK::wrap_in_subject_public_key_info(key->get<::Crypto::PK::MLDSAPublicKey>().public_key(), oid): ::Crypto::PK::wrap_in_private_key_info(key->get<::Crypto::PK::MLDSAPrivateKey>(), oid);- if (result.is_error())- return false;- receive(state, result.value());- return true;+ return receive_byte_result(result, state, receive);}extern "C" {@@ -1022,10 +969,7 @@ bool web_crypto_mlkem_export_der(CryptoKey::InternalKeyData const* key, bool is_auto result = is_public? ::Crypto::PK::wrap_in_subject_public_key_info(key->get<::Crypto::PK::MLKEMPublicKey>().public_key(), oid): ::Crypto::PK::wrap_in_private_key_info(key->get<::Crypto::PK::MLKEMPrivateKey>(), oid);- if (result.is_error())- return false;- receive(state, result.value());- return true;+ return receive_byte_result(result, state, receive);}FlatPtr web_crypto_mlkem_encapsulate(::Crypto::PK::MLKEMSize size, CryptoKey::InternalKeyData const* key, void* shared_key, void* ciphertext, ReceiveEncodedBytes receive)@@ -1076,20 +1020,14 @@ bool web_crypto_hkdf_derive_key(::Crypto::Hash::HashKind kind, ReadonlyBytes sal{::Crypto::Hash::HKDF hkdf(kind);auto result = hkdf.derive_key(salt, key_derivation_key, info, length);- if (result.is_error())- return false;- receive(state, result.value());- return true;+ return receive_byte_result(result, state, receive);}bool web_crypto_pbkdf2_derive_key(::Crypto::Hash::HashKind kind, ReadonlyBytes password, ReadonlyBytes salt, u32 iterations, u32 length, void* state, ReceiveEncodedBytes receive){::Crypto::Hash::PBKDF2 pbkdf2(kind);auto result = pbkdf2.derive_key(password, salt, iterations, length);- if (result.is_error())- return false;- receive(state, result.value());- return true;+ return receive_byte_result(result, state, receive);}static_assert(to_underlying(::Crypto::Hash::Argon2Type::Argon2d) == 0);@@ -1175,10 +1113,7 @@ bool web_crypto_kmac_sign(::Crypto::Authentication::KMACKind kind, ReadonlyBytes{::Crypto::Authentication::KMAC kmac(kind);auto result = kmac.sign(key, message, output_length, customization.to_optional());- if (result.is_error())- return false;- receive(state, result.value());- return true;+ return receive_byte_result(result, state, receive);}extern "C" CryptoKey::InternalKeyData* web_crypto_public_key_for_private_key(CryptoKey::InternalKeyData const*, FlatPtr name, FlatPtr named_curve);