From 79980ded70b5e75f6e919f54f9124003491d689e Mon Sep 17 00:00:00 2001 From: sam Date: Wed, 22 Oct 2025 16:44:27 +0700 Subject: [PATCH] redo encryption to enc individual messages content, not the whole blob, to circumvent nip44 signer limits --- src/contexts/DMContext.tsx | 136 +++++++++++++++++++++++++------------ src/lib/dmMessageStore.ts | 77 +++------------------ 2 files changed, 101 insertions(+), 112 deletions(-) diff --git a/src/contexts/DMContext.tsx b/src/contexts/DMContext.tsx index 1936726..692c46b 100644 --- a/src/contexts/DMContext.tsx +++ b/src/contexts/DMContext.tsx @@ -74,6 +74,7 @@ interface DecryptedMessage extends NostrEvent { isSending?: boolean; clientFirstSeen?: number; sealEvent?: NostrEvent; // Store kind 13 seal for NIP-17 (only needs 1 decrypt instead of 2) + originalGiftWrapId?: string; // Store gift wrap ID for NIP-17 deduplication } interface NIP17ProcessingResult { @@ -766,11 +767,16 @@ export function DMProvider({ children, config }: DMProviderProps) { for (const giftWrap of messages) { const { processedMessage, conversationPartner, sealEvent } = await processNIP17GiftWrap(giftWrap); - // Use the real message (kind 14) timestamp, not the randomized gift wrap timestamp + // Store the seal (kind 13) as-is + add decryptedEvent for inner message access const messageWithAnimation: DecryptedMessage = { - ...processedMessage, - content: giftWrap.content, // Keep original encrypted content for reference - sealEvent, // Store just the seal (kind 13) - only 1 decrypt needed + ...sealEvent, // Seal fields (kind 13, seal pubkey, encrypted content, etc.) + created_at: processedMessage.created_at, // Use real timestamp from inner message + decryptedEvent: { + ...processedMessage, + content: processedMessage.decryptedContent, + } as NostrEvent, + decryptedContent: processedMessage.decryptedContent, + originalGiftWrapId: giftWrap.id, // Store gift wrap ID for deduplication }; // Use real message timestamp for recency check @@ -859,8 +865,14 @@ export function DMProvider({ children, config }: DMProviderProps) { newState.forEach((value, key) => { const existing = finalMap.get(key); if (existing) { - const existingMessageIds = new Set(existing.messages.map(msg => msg.id)); - const newMessages = value.messages.filter(msg => !existingMessageIds.has(msg.id)); + // For NIP-17 messages with originalGiftWrapId, dedupe by gift wrap ID + // For NIP-04 and cached NIP-17 messages, dedupe by message ID + const existingMessageIds = new Set( + existing.messages.map(msg => msg.originalGiftWrapId || msg.id) + ); + const newMessages = value.messages.filter(msg => + !existingMessageIds.has(msg.originalGiftWrapId || msg.id) + ); const mergedMessages = [...existing.messages, ...newMessages]; mergedMessages.sort((a, b) => a.created_at - b.created_at); @@ -893,7 +905,10 @@ export function DMProvider({ children, config }: DMProviderProps) { const existing = newMap.get(conversationPartner); if (existing) { - if (existing.messages.some(msg => msg.id === message.id)) { + // For NIP-17 messages with originalGiftWrapId, dedupe by gift wrap ID + // For NIP-04 and cached NIP-17 messages, dedupe by message ID + const messageId = message.originalGiftWrapId || message.id; + if (existing.messages.some(msg => (msg.originalGiftWrapId || msg.id) === messageId)) { return prev; } @@ -1066,11 +1081,10 @@ export function DMProvider({ children, config }: DMProviderProps) { processedMessage: { ...messageEvent, id: messageEvent.id || `missing-nip17-inner-${messageEvent.created_at}-${messageEvent.pubkey.substring(0, 8)}-${messageEvent.content.substring(0, 16)}`, - content: event.content, - decryptedContent: messageEvent.content, + decryptedContent: messageEvent.content, // Plaintext from inner message }, conversationPartner, - sealEvent, // Return the seal for caching + sealEvent, // Return the seal (kind 13) for storage }; } catch (error) { nip17ErrorLogger(error as Error); @@ -1095,11 +1109,16 @@ export function DMProvider({ children, config }: DMProviderProps) { const { processedMessage, conversationPartner, sealEvent } = await processNIP17GiftWrap(event); - // Use the real message (kind 14) timestamp, not the randomized gift wrap timestamp + // Store the seal (kind 13) as-is + add decryptedEvent for inner message access const messageWithAnimation: DecryptedMessage = { - ...processedMessage, - content: event.content, // Keep original encrypted content for reference - sealEvent, // Store just the seal (kind 13) - only 1 decrypt needed + ...sealEvent, // Seal fields (kind 13, seal pubkey, encrypted content, etc.) + created_at: processedMessage.created_at, // Use real timestamp from inner message + decryptedEvent: { + ...processedMessage, + content: processedMessage.decryptedContent, + } as NostrEvent, + decryptedContent: processedMessage.decryptedContent, + originalGiftWrapId: event.id, // Store gift wrap ID for deduplication }; // Use real message timestamp for recency check @@ -1225,7 +1244,7 @@ export function DMProvider({ children, config }: DMProviderProps) { const { readMessagesFromDB } = await import('@/lib/dmMessageStore'); const dbReadStart = performance.now(); - const cachedStore = await readMessagesFromDB(userPubkey, user?.signer); + const cachedStore = await readMessagesFromDB(userPubkey); console.log(`[DM] ⏱️ IndexedDB read + decrypt took ${(performance.now() - dbReadStart).toFixed(0)}ms`); if (!cachedStore || Object.keys(cachedStore.participants).length === 0) { @@ -1241,18 +1260,55 @@ export function DMProvider({ children, config }: DMProviderProps) { const newState = new Map(); let messageCount = 0; - // Messages are already decrypted in the encrypted blob! - // Just load them directly into state + // Decrypt each message individually (they're stored in original encrypted form) + const decryptStartTime = performance.now(); for (const [participantPubkey, participant] of Object.entries(filteredParticipants)) { - const processedMessages = participant.messages.map(msg => { + const processedMessages = await Promise.all(participant.messages.map(async (msg) => { messageCount++; - // Content is already decrypted, just add the decryptedContent field + + // Decrypt based on message kind + let decryptedContent: string | undefined; + let error: string | undefined; + + if (msg.kind === 4) { + // NIP-04 message + const otherPubkey = msg.pubkey === user?.pubkey + ? msg.tags.find(([name]) => name === 'p')?.[1] + : msg.pubkey; + + if (otherPubkey && user?.signer?.nip04) { + try { + decryptedContent = await user.signer.nip04.decrypt(otherPubkey, msg.content); + } catch { + error = 'Decryption failed'; + } + } + } else if (msg.kind === 13) { + // NIP-17 seal - decrypt to get the inner kind 14/15 event + if (user?.signer?.nip44) { + try { + const sealContent = await user.signer.nip44.decrypt(msg.pubkey, msg.content); + const decryptedEvent = JSON.parse(sealContent) as NostrEvent; + + // Keep seal structure but add decryptedEvent for access to inner fields + return { + ...msg, + decryptedEvent, // Full inner event (kind 14/15) + decryptedContent: decryptedEvent.content, // Plaintext message + } as NostrEvent & { decryptedEvent?: NostrEvent; decryptedContent?: string; error?: string }; + } catch { + error = 'Decryption failed'; + } + } + } + return { ...msg, id: msg.id || `missing-${msg.kind}-${msg.created_at}-${msg.pubkey.substring(0, 8)}-${msg.content?.substring(0, 16) || 'nocontent'}`, - decryptedContent: msg.content, // Content is already plaintext - } as NostrEvent & { decryptedContent?: string }; - }); + decryptedContent, + error, + } as NostrEvent & { decryptedContent?: string; error?: string }; + })); newState.set(participantPubkey, { messages: processedMessages, @@ -1263,7 +1319,7 @@ export function DMProvider({ children, config }: DMProviderProps) { }); } - console.log(`[DM] ⏱️ Loaded ${messageCount} messages from encrypted cache (no re-decryption needed!)`); + console.log(`[DM] ⏱️ Decrypted ${messageCount} messages in ${(performance.now() - decryptStartTime).toFixed(0)}ms`); const setStateStart = performance.now(); setMessages(newState); @@ -1522,12 +1578,6 @@ export function DMProvider({ children, config }: DMProviderProps) { // Write to store const writeAllMessagesToStore = useCallback(async () => { if (!userPubkey) return; - - // Don't try to save if user/signer is not available - if (!user?.signer) { - console.log('[DM] Skipping cache write - no signer available'); - return; - } try { const { writeMessagesToDB } = await import('@/lib/dmMessageStore'); @@ -1547,26 +1597,26 @@ export function DMProvider({ children, config }: DMProviderProps) { messages.forEach((participant, participantPubkey) => { messageStore.participants[participantPubkey] = { - messages: participant.messages.map(msg => { - // Store decrypted messages with plaintext content - // The entire store will be NIP-44 encrypted as one blob - return { - id: msg.id, - pubkey: msg.pubkey, - content: msg.decryptedContent || msg.content, // Store DECRYPTED content - created_at: msg.created_at, - kind: msg.kind, - tags: msg.tags, - sig: msg.sig, - } as NostrEvent; - }), + messages: participant.messages.map(msg => ({ + // Store messages in their ORIGINAL ENCRYPTED form + // Just strip the decrypted fields (decryptedContent, decryptedEvent) + // Keep originalGiftWrapId for NIP-17 deduplication on cache load + id: msg.id, + pubkey: msg.pubkey, + content: msg.content, // Encrypted content (NIP-04 or seal) + created_at: msg.created_at, + kind: msg.kind, // 4 for NIP-04, 13 for NIP-17 + tags: msg.tags, + sig: msg.sig, + ...(msg.originalGiftWrapId && { originalGiftWrapId: msg.originalGiftWrapId }), + } as NostrEvent)), lastActivity: participant.lastActivity, hasNIP4: participant.hasNIP4, hasNIP17: participant.hasNIP17, }; }); - await writeMessagesToDB(userPubkey, messageStore, user?.signer); + await writeMessagesToDB(userPubkey, messageStore); const currentTime = Math.floor(Date.now() / 1000); setLastSync(prev => ({ diff --git a/src/lib/dmMessageStore.ts b/src/lib/dmMessageStore.ts index e22039b..cd80a64 100644 --- a/src/lib/dmMessageStore.ts +++ b/src/lib/dmMessageStore.ts @@ -15,12 +15,6 @@ const DB_NAME = getDBName(); const DB_VERSION = 1; const STORE_NAME = 'messages'; -// Signer interface for NIP-44 encryption/decryption -interface NIP44Signer { - encrypt(pubkey: string, plaintext: string): Promise; - decrypt(pubkey: string, ciphertext: string): Promise; -} - interface StoredParticipant { messages: NostrEvent[]; lastActivity: number; @@ -36,22 +30,6 @@ export interface MessageStore { }; } -// Wrapper for encrypted storage -interface EncryptedStore { - encrypted: true; - data: string; // NIP-44 encrypted MessageStore JSON -} - -// Type guard to check if data is encrypted -function isEncryptedStore(data: unknown): data is EncryptedStore { - return ( - typeof data === 'object' && - data !== null && - 'encrypted' in data && - (data as EncryptedStore).encrypted === true - ); -} - // ============================================================================ // Database Operations // ============================================================================ @@ -72,37 +50,19 @@ async function openDatabase(): Promise { /** * Write messages to IndexedDB for a specific user - * If signer is provided, encrypts the entire store with NIP-44 + * Messages are stored in their original encrypted form (kind 4 or kind 13) */ export async function writeMessagesToDB( userPubkey: string, - messageStore: MessageStore, - signer?: { nip44?: NIP44Signer } + messageStore: MessageStore ): Promise { try { const db = await openDatabase(); - // Always require encryption - if signer is not available, don't store - if (!signer?.nip44) { - console.warn('[MessageStore] ⚠️ Cannot save: NIP-44 signer not available'); - return; - } - - const plaintext = JSON.stringify(messageStore); - const encrypted = await signer.nip44.encrypt(userPubkey, plaintext); - - // Validate that encryption returned a string - if (typeof encrypted !== 'string' || !encrypted) { - throw new Error('NIP-44 encryption failed: expected string result, got ' + typeof encrypted); - } - - const encryptedStore: EncryptedStore = { - encrypted: true, - data: encrypted, - }; - - await db.put(STORE_NAME, encryptedStore, userPubkey); - console.log('[MessageStore] ✅ Encrypted cache saved'); + // Store messages in their original encrypted form (no NIP-44 wrapper needed) + // Each message content is already encrypted by the sender + await db.put(STORE_NAME, messageStore, userPubkey); + console.log('[MessageStore] ✅ Cached', Object.keys(messageStore.participants).length, 'conversations'); } catch (error) { console.error('[MessageStore] ❌ Error writing to IndexedDB:', error); throw error; @@ -111,11 +71,10 @@ export async function writeMessagesToDB( /** * Read messages from IndexedDB for a specific user - * If data is encrypted, decrypts it using the provided signer + * Messages are stored in their original encrypted form (kind 4 or kind 13) */ export async function readMessagesFromDB( - userPubkey: string, - signer?: { nip44?: NIP44Signer } + userPubkey: string ): Promise { try { const db = await openDatabase(); @@ -125,26 +84,6 @@ export async function readMessagesFromDB( return undefined; } - // Check if data is encrypted - if (isEncryptedStore(data)) { - if (!signer?.nip44) { - console.error('[MessageStore] ❌ Encrypted cache found but no signer available'); - return undefined; - } - - try { - const decrypted = await signer.nip44.decrypt(userPubkey, data.data); - const messageStore = JSON.parse(decrypted) as MessageStore; - console.log('[MessageStore] ✅ Decrypted cache loaded'); - return messageStore; - } catch (error) { - console.error('[MessageStore] ❌ Failed to decrypt cache:', error); - return undefined; - } - } - - // Backward compatibility: unencrypted cache - console.log('[MessageStore] ⚠️ Loaded unencrypted cache (old format)'); return data as MessageStore; } catch (error) { console.error('[MessageStore] Error reading from IndexedDB:', error);