From e82e44cc2ded4ad379d4818eb81260238ea6f832 Mon Sep 17 00:00:00 2001 From: nazeh Date: Thu, 8 Aug 2024 14:25:36 +0300 Subject: [PATCH] fix(js): return better error for Keypair.fromSecretKey() with invalid input --- pubky/pkg/test/keys.js | 8 ++++++++ pubky/src/wasm/keys.rs | 19 ++++++++++++++----- 2 files changed, 22 insertions(+), 5 deletions(-) diff --git a/pubky/pkg/test/keys.js b/pubky/pkg/test/keys.js index e184b3b..d036862 100644 --- a/pubky/pkg/test/keys.js +++ b/pubky/pkg/test/keys.js @@ -11,3 +11,11 @@ test('generate keys from a seed', async (t) => { t.is(publicKey.z32(), 'gcumbhd7sqit6nn457jxmrwqx9pyymqwamnarekgo3xppqo6a19o') }) + +test('fromSecretKey error', async (t) => { + const secretkey = Buffer.from('5aa93b299a343aa2691739771f2b5b', 'hex') + + + t.throws(() => Keypair.fromSecretKey(null), /Expected secret_key to be an instance of Uint8Array/) + t.throws(() => Keypair.fromSecretKey(secretkey), /Expected secret_key to be 32 bytes, got 15/) +}) diff --git a/pubky/src/wasm/keys.rs b/pubky/src/wasm/keys.rs index 345e721..12ecdd7 100644 --- a/pubky/src/wasm/keys.rs +++ b/pubky/src/wasm/keys.rs @@ -15,11 +15,20 @@ impl Keypair { /// Generate a [Keypair] from a secret key. #[wasm_bindgen(js_name = "fromSecretKey")] - pub fn from_secret_key(secret_key: js_sys::Uint8Array) -> Self { + pub fn from_secret_key(secret_key: js_sys::Uint8Array) -> Result { + if !js_sys::Uint8Array::instanceof(&secret_key) { + return Err("Expected secret_key to be an instance of Uint8Array".into()); + } + + let len = secret_key.byte_length(); + if (len != 32) { + return Err(format!("Expected secret_key to be 32 bytes, got {len}"))?; + } + let mut bytes = [0; 32]; secret_key.copy_to(&mut bytes); - Self(pkarr::Keypair::from_secret_key(&bytes)) + Ok(Self(pkarr::Keypair::from_secret_key(&bytes))) } /// Returns the secret key of this keypair. @@ -67,9 +76,9 @@ impl PublicKey { #[wasm_bindgen(js_name = "from")] /// @throws pub fn try_from(value: JsValue) -> Result { - let string = value.as_string().ok_or(Error::Generic( - "Couldn't create a PublicKey from this type of value".to_string(), - ))?; + let string = value + .as_string() + .ok_or("Couldn't create a PublicKey from this type of value")?; Ok(PublicKey( pkarr::PublicKey::try_from(string).map_err(Error::Pkarr)?,