redo encryption to enc individual messages content, not the whole blob, to circumvent nip44 signer limits

This commit is contained in:
sam committed 2025-10-22 16:44:27 +07:00
1 parent 9d7f5e48df
commit 79980ded70
2 files changed
+101 -112

No files matched your search

+93 -43
View File
@@ -74,6 +74,7 @@ interface DecryptedMessage extends NostrEvent {
isSending?: boolean; isSending?: boolean;
clientFirstSeen?: number; clientFirstSeen?: number;
sealEvent?: NostrEvent; // Store kind 13 seal for NIP-17 (only needs 1 decrypt instead of 2) 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 { interface NIP17ProcessingResult {
@@ -766,11 +767,16 @@ export function DMProvider({ children, config }: DMProviderProps) {
for (const giftWrap of messages) { for (const giftWrap of messages) {
const { processedMessage, conversationPartner, sealEvent } = await processNIP17GiftWrap(giftWrap); 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 = { const messageWithAnimation: DecryptedMessage = {
...processedMessage, ...sealEvent, // Seal fields (kind 13, seal pubkey, encrypted content, etc.)
content: giftWrap.content, // Keep original encrypted content for reference created_at: processedMessage.created_at, // Use real timestamp from inner message
sealEvent, // Store just the seal (kind 13) - only 1 decrypt needed 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 // Use real message timestamp for recency check
@@ -859,8 +865,14 @@ export function DMProvider({ children, config }: DMProviderProps) {
newState.forEach((value, key) => { newState.forEach((value, key) => {
const existing = finalMap.get(key); const existing = finalMap.get(key);
if (existing) { if (existing) {
const existingMessageIds = new Set(existing.messages.map(msg => msg.id)); // For NIP-17 messages with originalGiftWrapId, dedupe by gift wrap ID
const newMessages = value.messages.filter(msg => !existingMessageIds.has(msg.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]; const mergedMessages = [...existing.messages, ...newMessages];
mergedMessages.sort((a, b) => a.created_at - b.created_at); 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); const existing = newMap.get(conversationPartner);
if (existing) { 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; return prev;
} }
@@ -1066,11 +1081,10 @@ export function DMProvider({ children, config }: DMProviderProps) {
processedMessage: { processedMessage: {
...messageEvent, ...messageEvent,
id: messageEvent.id || `missing-nip17-inner-${messageEvent.created_at}-${messageEvent.pubkey.substring(0, 8)}-${messageEvent.content.substring(0, 16)}`, 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, // Plaintext from inner message
decryptedContent: messageEvent.content,
}, },
conversationPartner, conversationPartner,
sealEvent, // Return the seal for caching sealEvent, // Return the seal (kind 13) for storage
}; };
} catch (error) { } catch (error) {
nip17ErrorLogger(error as Error); nip17ErrorLogger(error as Error);
@@ -1095,11 +1109,16 @@ export function DMProvider({ children, config }: DMProviderProps) {
const { processedMessage, conversationPartner, sealEvent } = await processNIP17GiftWrap(event); 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 = { const messageWithAnimation: DecryptedMessage = {
...processedMessage, ...sealEvent, // Seal fields (kind 13, seal pubkey, encrypted content, etc.)
content: event.content, // Keep original encrypted content for reference created_at: processedMessage.created_at, // Use real timestamp from inner message
sealEvent, // Store just the seal (kind 13) - only 1 decrypt needed 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 // Use real message timestamp for recency check
@@ -1225,7 +1244,7 @@ export function DMProvider({ children, config }: DMProviderProps) {
const { readMessagesFromDB } = await import('@/lib/dmMessageStore'); const { readMessagesFromDB } = await import('@/lib/dmMessageStore');
const dbReadStart = performance.now(); 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`); console.log(`[DM] ⏱️ IndexedDB read + decrypt took ${(performance.now() - dbReadStart).toFixed(0)}ms`);
if (!cachedStore || Object.keys(cachedStore.participants).length === 0) { if (!cachedStore || Object.keys(cachedStore.participants).length === 0) {
@@ -1241,18 +1260,55 @@ export function DMProvider({ children, config }: DMProviderProps) {
const newState = new Map(); const newState = new Map();
let messageCount = 0; let messageCount = 0;
// Messages are already decrypted in the encrypted blob! // Decrypt each message individually (they're stored in original encrypted form)
// Just load them directly into state const decryptStartTime = performance.now();
for (const [participantPubkey, participant] of Object.entries(filteredParticipants)) { 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++; 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 { return {
...msg, ...msg,
id: msg.id || `missing-${msg.kind}-${msg.created_at}-${msg.pubkey.substring(0, 8)}-${msg.content?.substring(0, 16) || 'nocontent'}`, 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 decryptedContent,
} as NostrEvent & { decryptedContent?: string }; error,
}); } as NostrEvent & { decryptedContent?: string; error?: string };
}));
newState.set(participantPubkey, { newState.set(participantPubkey, {
messages: processedMessages, 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(); const setStateStart = performance.now();
setMessages(newState); setMessages(newState);
@@ -1523,12 +1579,6 @@ export function DMProvider({ children, config }: DMProviderProps) {
const writeAllMessagesToStore = useCallback(async () => { const writeAllMessagesToStore = useCallback(async () => {
if (!userPubkey) return; 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 { try {
const { writeMessagesToDB } = await import('@/lib/dmMessageStore'); const { writeMessagesToDB } = await import('@/lib/dmMessageStore');
@@ -1547,26 +1597,26 @@ export function DMProvider({ children, config }: DMProviderProps) {
messages.forEach((participant, participantPubkey) => { messages.forEach((participant, participantPubkey) => {
messageStore.participants[participantPubkey] = { messageStore.participants[participantPubkey] = {
messages: participant.messages.map(msg => { messages: participant.messages.map(msg => ({
// Store decrypted messages with plaintext content // Store messages in their ORIGINAL ENCRYPTED form
// The entire store will be NIP-44 encrypted as one blob // Just strip the decrypted fields (decryptedContent, decryptedEvent)
return { // Keep originalGiftWrapId for NIP-17 deduplication on cache load
id: msg.id, id: msg.id,
pubkey: msg.pubkey, pubkey: msg.pubkey,
content: msg.decryptedContent || msg.content, // Store DECRYPTED content content: msg.content, // Encrypted content (NIP-04 or seal)
created_at: msg.created_at, created_at: msg.created_at,
kind: msg.kind, kind: msg.kind, // 4 for NIP-04, 13 for NIP-17
tags: msg.tags, tags: msg.tags,
sig: msg.sig, sig: msg.sig,
} as NostrEvent; ...(msg.originalGiftWrapId && { originalGiftWrapId: msg.originalGiftWrapId }),
}), } as NostrEvent)),
lastActivity: participant.lastActivity, lastActivity: participant.lastActivity,
hasNIP4: participant.hasNIP4, hasNIP4: participant.hasNIP4,
hasNIP17: participant.hasNIP17, hasNIP17: participant.hasNIP17,
}; };
}); });
await writeMessagesToDB(userPubkey, messageStore, user?.signer); await writeMessagesToDB(userPubkey, messageStore);
const currentTime = Math.floor(Date.now() / 1000); const currentTime = Math.floor(Date.now() / 1000);
setLastSync(prev => ({ setLastSync(prev => ({
+8 -69
View File
@@ -15,12 +15,6 @@ const DB_NAME = getDBName();
const DB_VERSION = 1; const DB_VERSION = 1;
const STORE_NAME = 'messages'; const STORE_NAME = 'messages';
// Signer interface for NIP-44 encryption/decryption
interface NIP44Signer {
encrypt(pubkey: string, plaintext: string): Promise<string>;
decrypt(pubkey: string, ciphertext: string): Promise<string>;
}
interface StoredParticipant { interface StoredParticipant {
messages: NostrEvent[]; messages: NostrEvent[];
lastActivity: number; 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 // Database Operations
// ============================================================================ // ============================================================================
@@ -72,37 +50,19 @@ async function openDatabase(): Promise<IDBPDatabase> {
/** /**
* Write messages to IndexedDB for a specific user * 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( export async function writeMessagesToDB(
userPubkey: string, userPubkey: string,
messageStore: MessageStore, messageStore: MessageStore
signer?: { nip44?: NIP44Signer }
): Promise<void> { ): Promise<void> {
try { try {
const db = await openDatabase(); const db = await openDatabase();
// Always require encryption - if signer is not available, don't store // Store messages in their original encrypted form (no NIP-44 wrapper needed)
if (!signer?.nip44) { // Each message content is already encrypted by the sender
console.warn('[MessageStore] ⚠️ Cannot save: NIP-44 signer not available'); await db.put(STORE_NAME, messageStore, userPubkey);
return; console.log('[MessageStore] ✅ Cached', Object.keys(messageStore.participants).length, 'conversations');
}
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');
} catch (error) { } catch (error) {
console.error('[MessageStore] ❌ Error writing to IndexedDB:', error); console.error('[MessageStore] ❌ Error writing to IndexedDB:', error);
throw error; throw error;
@@ -111,11 +71,10 @@ export async function writeMessagesToDB(
/** /**
* Read messages from IndexedDB for a specific user * 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( export async function readMessagesFromDB(
userPubkey: string, userPubkey: string
signer?: { nip44?: NIP44Signer }
): Promise<MessageStore | undefined> { ): Promise<MessageStore | undefined> {
try { try {
const db = await openDatabase(); const db = await openDatabase();
@@ -125,26 +84,6 @@ export async function readMessagesFromDB(
return undefined; 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; return data as MessageStore;
} catch (error) { } catch (error) {
console.error('[MessageStore] Error reading from IndexedDB:', error); console.error('[MessageStore] Error reading from IndexedDB:', error);