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)`)
}
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(
let encryptedContent: string
try {
encryptedContent = await nip04.encrypt(
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
const eventTemplate: EventTemplate = {