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,13 +381,45 @@ 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 = {
kind: 4,
@ -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()

View file

@ -6,16 +6,26 @@
* Convert hex string to Uint8Array
*/
export function hexToBytes(hex: string): Uint8Array {
if (typeof hex !== 'string') {
throw new TypeError('hexToBytes: expected string, got ' + typeof hex)
}
if (hex.length % 2 !== 0) {
throw new Error('Hex string must have even length')
throw new Error('hexToBytes: received invalid unpadded hex')
}
const bytes = hex.match(/.{2}/g)?.map(byte => parseInt(byte, 16))
if (!bytes) {
throw new Error('Invalid hex string')
const array = new Uint8Array(hex.length / 2)
for (let i = 0; i < array.length; i++) {
const j = i * 2
const hexByte = hex.slice(j, j + 2)
const byte = Number.parseInt(hexByte, 16)
if (Number.isNaN(byte) || byte < 0) {
throw new Error('Invalid byte sequence')
}
array[i] = byte
}
return new Uint8Array(bytes)
return array
}
/**