From aa3509d8073bd9719c36682a37099f1adc3d2354 Mon Sep 17 00:00:00 2001 From: padreug Date: Fri, 8 Aug 2025 19:17:12 +0200 Subject: [PATCH] feat: Improve Nostr chat encryption with enhanced key validation and error handling - Add validation for the hex format of private and public keys before encryption, ensuring they contain only valid characters. - Implement error handling during the encryption process to log failures and provide clearer error messages. - Refactor the encryption logic to improve reliability and security in the message encryption workflow. --- src/composables/useNostrChat.ts | 34 +++++++++++++++++++-------------- 1 file changed, 20 insertions(+), 14 deletions(-) diff --git a/src/composables/useNostrChat.ts b/src/composables/useNostrChat.ts index 852d219..57239d1 100644 --- a/src/composables/useNostrChat.ts +++ b/src/composables/useNostrChat.ts @@ -403,22 +403,28 @@ export function useNostrChat() { throw new Error(`Invalid public key length: ${publicKey.length} (expected 64)`) } - console.log('Encrypting message with keys:', { - privateKeyLength: privateKey.length, - publicKeyLength: publicKey.length, - privateKeyPrefix: privateKey.slice(0, 8) + '...', - publicKeyPrefix: publicKey.slice(0, 8) + '...', - contentLength: content.length - }) + // Validate hex format + const hexRegex = /^[0-9a-fA-F]+$/ + if (!hexRegex.test(privateKey)) { + throw new Error(`Invalid private key format: contains non-hex characters`) + } + + if (!hexRegex.test(publicKey)) { + throw new Error(`Invalid public key format: contains non-hex characters`) + } // Encrypt the message - const encryptedContent = await nip04.encrypt( - privateKey, - publicKey, - content - ) - - console.log('Message encrypted successfully, length:', encryptedContent.length) + let encryptedContent: string + try { + encryptedContent = await nip04.encrypt( + privateKey, + publicKey, + content + ) + } catch (encryptError) { + console.error('Encryption failed:', encryptError) + throw new Error(`Encryption failed: ${encryptError instanceof Error ? encryptError.message : String(encryptError)}`) + } // Create the event template const eventTemplate: EventTemplate = {