feat: Enhance Nostr chat encryption with key validation and logging

- Implement validation for private and public keys before encryption, ensuring they are present and in the correct hex format.
- Add detailed console logging for key lengths and encryption success, improving debugging and transparency in the message encryption process.
- Refactor the encryption call to use validated keys, enhancing security and reliability.
This commit is contained in:
padreug 2025-08-08 18:47:15 +02:00
parent 7241789c9e
commit dc053ad1be
2 changed files with 50 additions and 8 deletions

View file

@ -381,12 +381,44 @@ export function useNostrChat() {
}
try {
// Validate keys before encryption
if (!currentUser.value.prvkey || !peerPubkey) {
throw new Error('Missing private key or peer public key')
}
// Ensure keys are in correct hex format (64 characters for private key, 64 characters for public key)
const privateKey = currentUser.value.prvkey.startsWith('0x')
? currentUser.value.prvkey.slice(2)
: currentUser.value.prvkey
const publicKey = peerPubkey.startsWith('0x')
? peerPubkey.slice(2)
: peerPubkey
if (privateKey.length !== 64) {
throw new Error(`Invalid private key length: ${privateKey.length} (expected 64)`)
}
if (publicKey.length !== 64) {
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
})
// Encrypt the message
const encryptedContent = await nip04.encrypt(
currentUser.value.prvkey,
peerPubkey,
privateKey,
publicKey,
content
)
console.log('Message encrypted successfully, length:', encryptedContent.length)
// Create the event template
const eventTemplate: EventTemplate = {
@ -397,7 +429,7 @@ export function useNostrChat() {
}
// Finalize the event (sign it)
const event = finalizeEvent(eventTemplate, hexToBytes(currentUser.value.prvkey))
const event = finalizeEvent(eventTemplate, hexToBytes(privateKey))
// Publish to relays
const relayConfigs = getRelays()