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:
parent
dc053ad1be
commit
aa3509d807
1 changed files with 20 additions and 14 deletions
|
|
@ -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
|
||||||
|
try {
|
||||||
|
encryptedContent = await nip04.encrypt(
|
||||||
privateKey,
|
privateKey,
|
||||||
publicKey,
|
publicKey,
|
||||||
content
|
content
|
||||||
)
|
)
|
||||||
|
} catch (encryptError) {
|
||||||
console.log('Message encrypted successfully, length:', encryptedContent.length)
|
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 = {
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue