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.
This commit is contained in:
padreug 2025-08-08 19:17:12 +02:00
parent dc053ad1be
commit aa3509d807

View file

@ -403,22 +403,28 @@ export function useNostrChat() {
throw new Error(`Invalid public key length: ${publicKey.length} (expected 64)`) throw new Error(`Invalid public key length: ${publicKey.length} (expected 64)`)
} }
console.log('Encrypting message with keys:', { // Validate hex format
privateKeyLength: privateKey.length, const hexRegex = /^[0-9a-fA-F]+$/
publicKeyLength: publicKey.length, if (!hexRegex.test(privateKey)) {
privateKeyPrefix: privateKey.slice(0, 8) + '...', throw new Error(`Invalid private key format: contains non-hex characters`)
publicKeyPrefix: publicKey.slice(0, 8) + '...', }
contentLength: content.length
}) if (!hexRegex.test(publicKey)) {
throw new Error(`Invalid public key format: contains non-hex characters`)
}
// Encrypt the message // Encrypt the message
const encryptedContent = await nip04.encrypt( let encryptedContent: string
privateKey, try {
publicKey, encryptedContent = await nip04.encrypt(
content privateKey,
) publicKey,
content
console.log('Message encrypted successfully, length:', encryptedContent.length) )
} catch (encryptError) {
console.error('Encryption failed:', encryptError)
throw new Error(`Encryption failed: ${encryptError instanceof Error ? encryptError.message : String(encryptError)}`)
}
// Create the event template // Create the event template
const eventTemplate: EventTemplate = { const eventTemplate: EventTemplate = {