mirror of
https://gitlab.com/soapbox-pub/mkstack.git
synced 2026-12-03 08:07:21 +00:00
feat: port over nip-17 dms
This commit is contained in:
1 parent
57c646f919
commit
0870e227d9
7 files changed
+544
No files matched your search
Generated
+7
@@ -48,6 +48,7 @@
|
||||
"cmdk": "^1.0.0",
|
||||
"date-fns": "^3.6.0",
|
||||
"embla-carousel-react": "^8.3.0",
|
||||
"idb": "^8.0.3",
|
||||
"input-otp": "^1.2.4",
|
||||
"lucide-react": "^0.462.0",
|
||||
"nostr-tools": "^2.13.0",
|
||||
@@ -5486,6 +5487,12 @@
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/idb": {
|
||||
"version": "8.0.3",
|
||||
"resolved": "https://registry.npmjs.org/idb/-/idb-8.0.3.tgz",
|
||||
"integrity": "sha512-LtwtVyVYO5BqRvcsKuB2iUMnHwPVByPCXFXOpuU96IZPPoPN6xjOGxZQ74pgSVVLQWtUOYgyeL4GE98BY5D3wg==",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/ignore": {
|
||||
"version": "5.3.2",
|
||||
"resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz",
|
||||
|
||||
@@ -50,6 +50,7 @@
|
||||
"cmdk": "^1.0.0",
|
||||
"date-fns": "^3.6.0",
|
||||
"embla-carousel-react": "^8.3.0",
|
||||
"idb": "^8.0.3",
|
||||
"input-otp": "^1.2.4",
|
||||
"lucide-react": "^0.462.0",
|
||||
"nostr-tools": "^2.13.0",
|
||||
|
||||
@@ -0,0 +1,193 @@
|
||||
import { useMutation } from '@tanstack/react-query';
|
||||
import { useNostrPublish } from '@/hooks/useNostrPublish';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
|
||||
interface BaseSendDMParams {
|
||||
recipientPubkey: string;
|
||||
content: string;
|
||||
attachments?: Array<{
|
||||
url: string;
|
||||
mimeType: string;
|
||||
size: number;
|
||||
name: string;
|
||||
tags: string[][];
|
||||
}>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook for sending direct messages using NIP-04 and NIP-17 protocols
|
||||
*
|
||||
* @example
|
||||
* ```tsx
|
||||
* const { sendNIP4Message, sendNIP17Message } = useSendDM();
|
||||
*
|
||||
* // Send NIP-04 message
|
||||
* await sendNIP4Message.mutateAsync({
|
||||
* recipientPubkey: 'hex-pubkey',
|
||||
* content: 'Hello!'
|
||||
* });
|
||||
*
|
||||
* // Send NIP-17 message (more secure, uses NIP-44 + gift wrapping)
|
||||
* await sendNIP17Message.mutateAsync({
|
||||
* recipientPubkey: 'hex-pubkey',
|
||||
* content: 'Hello securely!'
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
export function useSendDM() {
|
||||
const { mutateAsync: createEvent } = useNostrPublish();
|
||||
const { user } = useCurrentUser();
|
||||
const { toast } = useToast();
|
||||
|
||||
// Helper function to prepare content with attachments
|
||||
const prepareMessageContent = (content: string, attachments: BaseSendDMParams['attachments'] = []) => {
|
||||
if (attachments.length === 0) return content;
|
||||
|
||||
const fileUrls = attachments.map(file => file.url).join('\n');
|
||||
return content ? `${content}\n\n${fileUrls}` : fileUrls;
|
||||
};
|
||||
|
||||
// Helper function to create imeta tags for attachments (NIP-92)
|
||||
const createImetaTags = (attachments: BaseSendDMParams['attachments'] = []) => {
|
||||
return attachments.map(file => {
|
||||
const imetaTag = ["imeta"];
|
||||
imetaTag.push(`url ${file.url}`);
|
||||
if (file.mimeType) imetaTag.push(`m ${file.mimeType}`);
|
||||
if (file.size) imetaTag.push(`size ${file.size}`);
|
||||
if (file.name) imetaTag.push(`alt ${file.name}`);
|
||||
|
||||
file.tags.forEach(tag => {
|
||||
if (tag[0] === 'x') imetaTag.push(`x ${tag[1]}`);
|
||||
if (tag[0] === 'ox') imetaTag.push(`ox ${tag[1]}`);
|
||||
});
|
||||
|
||||
return imetaTag;
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Send a NIP-04 encrypted direct message
|
||||
* Uses legacy NIP-04 encryption (nip04.encrypt)
|
||||
*/
|
||||
const sendNIP4Message = useMutation({
|
||||
mutationFn: async ({ recipientPubkey, content, attachments = [] }: BaseSendDMParams) => {
|
||||
if (!user?.signer?.nip04) {
|
||||
console.error('[SendDM] NIP-04 encryption not available');
|
||||
throw new Error('NIP-04 encryption not available');
|
||||
}
|
||||
|
||||
console.log('[SendDM] Sending NIP-04 message');
|
||||
|
||||
const messageContent = prepareMessageContent(content, attachments);
|
||||
const encryptedContent = await user.signer.nip04.encrypt(recipientPubkey, messageContent);
|
||||
|
||||
const tags = [
|
||||
["p", recipientPubkey],
|
||||
...createImetaTags(attachments)
|
||||
];
|
||||
|
||||
const event = await createEvent({
|
||||
kind: 4, // NIP-04 encrypted DM
|
||||
content: encryptedContent,
|
||||
tags,
|
||||
});
|
||||
|
||||
console.log('[SendDM] Created NIP-04 message:', event);
|
||||
return event;
|
||||
},
|
||||
onError: (error) => {
|
||||
console.error('Failed to send NIP-04 DM:', error);
|
||||
toast({
|
||||
title: "Error",
|
||||
description: "Failed to send NIP-04 message. Please try again.",
|
||||
variant: "destructive",
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* Send a NIP-17 encrypted direct message (Gift Wrapped)
|
||||
* Uses NIP-44 encryption with gift wrapping (NIP-59) for enhanced privacy
|
||||
*
|
||||
* Creates:
|
||||
* 1. Kind 14 Private DM event (signed by sender)
|
||||
* 2. Kind 13 Seal events (encrypted to recipient and sender)
|
||||
* 3. Kind 1059 Gift Wrap events (for recipient and sender to find messages)
|
||||
*/
|
||||
const sendNIP17Message = useMutation({
|
||||
mutationFn: async ({ recipientPubkey, content, attachments = [] }: BaseSendDMParams) => {
|
||||
if (!user?.signer?.nip44) {
|
||||
console.error('[SendDM] NIP-44 encryption not available for NIP-17');
|
||||
throw new Error('NIP-44 encryption not available for NIP-17');
|
||||
}
|
||||
|
||||
console.log('[SendDM] Sending NIP-17 Gift Wrap message');
|
||||
|
||||
const messageContent = prepareMessageContent(content, attachments);
|
||||
|
||||
// Step 1: Create and sign the Kind 14 Private DM event
|
||||
const privateDMTags = [
|
||||
["p", recipientPubkey],
|
||||
...createImetaTags(attachments)
|
||||
];
|
||||
|
||||
const privateDM = await user.signer.signEvent({
|
||||
kind: 14,
|
||||
content: messageContent,
|
||||
tags: privateDMTags,
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
});
|
||||
|
||||
// Step 2: Create TWO Kind 13 Seal events - one for recipient, one for sender
|
||||
|
||||
// Seal for recipient (encrypted to them)
|
||||
const recipientSeal = await user.signer.signEvent({
|
||||
kind: 13,
|
||||
content: await user.signer.nip44.encrypt(recipientPubkey, JSON.stringify(privateDM)),
|
||||
tags: [], // Seal events typically have no tags
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
});
|
||||
|
||||
// Seal for sender (encrypted to us)
|
||||
const senderSeal = await user.signer.signEvent({
|
||||
kind: 13,
|
||||
content: await user.signer.nip44.encrypt(user.pubkey, JSON.stringify(privateDM)),
|
||||
tags: [], // Seal events typically have no tags
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
});
|
||||
|
||||
// Step 3: Create TWO Kind 1059 Gift Wrap events
|
||||
// One for the recipient, one for myself (so I can see sent messages)
|
||||
|
||||
// Gift Wrap for recipient - they should be able to find it via their pubkey in p tag
|
||||
const recipientGiftWrap = await createEvent({
|
||||
kind: 1059, // Gift Wrap
|
||||
content: await user.signer.nip44.encrypt(recipientPubkey, JSON.stringify(recipientSeal)),
|
||||
tags: [["p", recipientPubkey]], // Recipient can find this via their pubkey
|
||||
});
|
||||
|
||||
// Gift Wrap for myself - I should be able to find it via my pubkey in p tag
|
||||
const myGiftWrap = await createEvent({
|
||||
kind: 1059, // Gift Wrap
|
||||
content: await user.signer.nip44.encrypt(user.pubkey, JSON.stringify(senderSeal)),
|
||||
tags: [["p", user.pubkey]], // I can find this via my pubkey
|
||||
});
|
||||
|
||||
return { recipientGiftWrap, myGiftWrap };
|
||||
},
|
||||
onError: (error) => {
|
||||
console.error('Failed to send NIP-17 DM:', error);
|
||||
toast({
|
||||
title: "Error",
|
||||
description: "Failed to send NIP-17 message. Please try again.",
|
||||
variant: "destructive",
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
sendNIP4Message,
|
||||
sendNIP17Message,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { MESSAGE_PROTOCOL, type MessageProtocol } from '@/types/dm';
|
||||
|
||||
/**
|
||||
* Helper function to determine message protocol from event kind
|
||||
*/
|
||||
export function getMessageProtocol(kind: number): MessageProtocol {
|
||||
switch (kind) {
|
||||
case 4: return MESSAGE_PROTOCOL.NIP04;
|
||||
case 1059: return MESSAGE_PROTOCOL.NIP17; // Gift Wrap
|
||||
case 14: return MESSAGE_PROTOCOL.NIP17; // Private DM (decrypted NIP-17)
|
||||
default: return MESSAGE_PROTOCOL.UNKNOWN;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Protocol indicator configuration for UI display
|
||||
*/
|
||||
export const PROTOCOL_CONFIG = {
|
||||
[MESSAGE_PROTOCOL.NIP04]: {
|
||||
color: 'bg-orange-500',
|
||||
textColor: 'text-orange-600 dark:text-orange-400',
|
||||
label: 'NIP-04',
|
||||
title: 'NIP-04 encrypted message'
|
||||
},
|
||||
[MESSAGE_PROTOCOL.NIP17]: {
|
||||
color: 'bg-purple-500',
|
||||
textColor: 'text-purple-600 dark:text-purple-400',
|
||||
label: 'NIP-17',
|
||||
title: 'NIP-44/NIP-17 encrypted message'
|
||||
},
|
||||
[MESSAGE_PROTOCOL.UNKNOWN]: {
|
||||
color: 'bg-gray-400',
|
||||
textColor: 'text-gray-600 dark:text-gray-400',
|
||||
label: 'Unknown',
|
||||
title: 'Unknown message type'
|
||||
}
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* Constants for consistent naming across the app
|
||||
*/
|
||||
export const PROTOCOL_CONSTANTS = {
|
||||
// localStorage keys
|
||||
NIP17_ENABLED_KEY: 'enableNIP17',
|
||||
|
||||
// Logger prefixes
|
||||
NIP4_LOG_PREFIX: 'DMS: [NIP4]',
|
||||
NIP17_LOG_PREFIX: 'DMS: [NIP17]',
|
||||
DMCHAT_LOG_PREFIX: 'DMS: [DMCHAT]',
|
||||
DIRECT_MESSAGES_LOG_PREFIX: 'DMS: [DirectMessages]',
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* Message pagination constants
|
||||
*/
|
||||
export const MESSAGES_PER_PAGE = 25;
|
||||
@@ -0,0 +1,61 @@
|
||||
import type { NostrEvent } from '@nostrify/nostrify';
|
||||
import type { DecryptedMessage, DMConversation } from '@/types/dm';
|
||||
|
||||
/**
|
||||
* Shared validation function for DM events
|
||||
* Validates both NIP-04 (kind 4) and NIP-17 (kind 1059) encrypted DMs
|
||||
*/
|
||||
export function validateDMEvent(event: NostrEvent): boolean {
|
||||
// Accept both NIP-04 (kind 4) and NIP-17 (kind 1059) encrypted DMs
|
||||
if (![4, 1059].includes(event.kind)) return false;
|
||||
|
||||
// Must have a 'p' tag for the recipient
|
||||
const hasP = event.tags.some(([name]) => name === 'p');
|
||||
if (!hasP) return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract the recipient pubkey from a DM event
|
||||
*/
|
||||
export function getRecipientPubkey(event: NostrEvent): string | null {
|
||||
const pTag = event.tags.find(([name]) => name === 'p');
|
||||
return pTag ? pTag[1] : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if a message is from the current user
|
||||
*/
|
||||
export function isMessageFromUser(message: DecryptedMessage, userPubkey: string): boolean {
|
||||
return message.pubkey === userPubkey;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sort conversations by last activity (most recent first)
|
||||
*/
|
||||
export function sortConversationsByActivity(conversations: DMConversation[]): DMConversation[] {
|
||||
return [...conversations].sort((a, b) => b.lastMessageTime - a.lastMessageTime);
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter conversations by search query
|
||||
* Searches in decrypted message content and participant info
|
||||
*/
|
||||
export function filterConversationsByQuery(
|
||||
conversations: DMConversation[],
|
||||
query: string
|
||||
): DMConversation[] {
|
||||
if (!query.trim()) return conversations;
|
||||
|
||||
const lowerQuery = query.toLowerCase();
|
||||
return conversations.filter(conv => {
|
||||
// Search in pubkey
|
||||
if (conv.pubkey.toLowerCase().includes(lowerQuery)) return true;
|
||||
|
||||
// Search in last message content
|
||||
if (conv.lastMessage?.decryptedContent?.toLowerCase().includes(lowerQuery)) return true;
|
||||
|
||||
return false;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
import { openDB, IDBPDatabase } from 'idb';
|
||||
import type { NostrEvent } from '@nostrify/nostrify';
|
||||
|
||||
// Match the in-memory structure exactly
|
||||
interface StoredParticipant {
|
||||
messages: NostrEvent[]; // Store only basic NostrEvent in IndexedDB
|
||||
lastActivity: number;
|
||||
hasNIP4: boolean;
|
||||
hasNIP17: boolean;
|
||||
}
|
||||
|
||||
// Store structure: Map<participantPubkey, StoredParticipant>
|
||||
interface MessageStore {
|
||||
participants: Record<string, StoredParticipant>;
|
||||
lastSync: {
|
||||
nip4: number | null;
|
||||
nip17: number | null;
|
||||
};
|
||||
}
|
||||
|
||||
// IndexedDB configuration
|
||||
const DB_NAME = 'nostr-messages';
|
||||
const DB_VERSION = 1;
|
||||
|
||||
/**
|
||||
* Initialize IndexedDB for a specific user
|
||||
* Creates a user-specific store if it doesn't exist
|
||||
*/
|
||||
async function initDB(userNpub: string): Promise<IDBPDatabase> {
|
||||
const storeName = `messages-${userNpub}`;
|
||||
|
||||
return openDB(DB_NAME, DB_VERSION, {
|
||||
upgrade(db, _oldVersion, _newVersion) {
|
||||
// Create store for this user if it doesn't exist
|
||||
if (!db.objectStoreNames.contains(storeName)) {
|
||||
db.createObjectStore(storeName, { keyPath: 'id' });
|
||||
console.log(`DMS: Created store ${storeName} in IndexedDB`);
|
||||
}
|
||||
},
|
||||
blocked() {
|
||||
console.warn('IndexedDB upgrade blocked - another tab may have the database open');
|
||||
},
|
||||
blocking() {
|
||||
console.warn('IndexedDB upgrade blocking - this tab is preventing another tab from upgrading');
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Read all messages from IndexedDB for a specific user
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const messageStore = await readMessagesFromDB('npub1...');
|
||||
* if (messageStore) {
|
||||
* console.log('Loaded messages:', messageStore.participants);
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
export async function readMessagesFromDB(userNpub: string): Promise<MessageStore | null> {
|
||||
try {
|
||||
const db = await initDB(userNpub);
|
||||
const storeName = `messages-${userNpub}`;
|
||||
|
||||
// Check if the store exists before trying to read from it
|
||||
if (!db.objectStoreNames.contains(storeName)) {
|
||||
console.log(`Store ${storeName} does not exist yet for user ${userNpub.slice(0, 8)}...`);
|
||||
return null;
|
||||
}
|
||||
|
||||
// Read the entire store as one object
|
||||
const storeData = await db.get(storeName, 'messageStore');
|
||||
|
||||
if (storeData) {
|
||||
console.log(`Read message store from IndexedDB for user ${userNpub.slice(0, 8)}...`);
|
||||
return storeData as MessageStore;
|
||||
} else {
|
||||
console.log(`DMS: No message store found in IndexedDB for user ${userNpub.slice(0, 8)}...`);
|
||||
return null;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error reading messages from IndexedDB:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Write messages to IndexedDB for a specific user
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* await writeMessagesToDB('npub1...', {
|
||||
* participants: {
|
||||
* 'hex-pubkey': {
|
||||
* messages: [...],
|
||||
* lastActivity: Date.now(),
|
||||
* hasNIP4: true,
|
||||
* hasNIP17: false
|
||||
* }
|
||||
* },
|
||||
* lastSync: { nip4: Date.now(), nip17: null }
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
export async function writeMessagesToDB(userNpub: string, messageStore: MessageStore): Promise<void> {
|
||||
try {
|
||||
const db = await initDB(userNpub);
|
||||
const storeName = `messages-${userNpub}`;
|
||||
|
||||
// Check if the store exists before trying to write to it
|
||||
if (!db.objectStoreNames.contains(storeName)) {
|
||||
console.log(`Store ${storeName} does not exist yet for user ${userNpub.slice(0, 8)}..., creating it`);
|
||||
// Force a database upgrade to create the store
|
||||
await db.close();
|
||||
const newDb = await openDB(DB_NAME, DB_VERSION + 1, {
|
||||
upgrade(db, _oldVersion, _newVersion) {
|
||||
if (!db.objectStoreNames.contains(storeName)) {
|
||||
db.createObjectStore(storeName, { keyPath: 'id' });
|
||||
console.log(`DMS: Created store ${storeName} in IndexedDB during write`);
|
||||
}
|
||||
},
|
||||
});
|
||||
await newDb.put(storeName, { id: 'messageStore', ...messageStore });
|
||||
await newDb.close();
|
||||
} else {
|
||||
// Store the entire message store as one object
|
||||
await db.put(storeName, { id: 'messageStore', ...messageStore });
|
||||
}
|
||||
|
||||
console.log(`Wrote message store to IndexedDB for user ${userNpub.slice(0, 8)}... (${Object.keys(messageStore.participants).length} participants)`);
|
||||
} catch (error) {
|
||||
console.error('Error writing messages to IndexedDB:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear all messages from IndexedDB for a specific user
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* await clearMessagesFromDB('npub1...');
|
||||
* ```
|
||||
*/
|
||||
export async function clearMessagesFromDB(userNpub: string): Promise<void> {
|
||||
try {
|
||||
const db = await initDB(userNpub);
|
||||
const storeName = `messages-${userNpub}`;
|
||||
|
||||
if (db.objectStoreNames.contains(storeName)) {
|
||||
// Clear the entire store
|
||||
const tx = db.transaction(storeName, 'readwrite');
|
||||
const store = tx.objectStore(storeName);
|
||||
await store.clear();
|
||||
await tx.done;
|
||||
|
||||
console.log(`DMS: Cleared message store from IndexedDB for user ${userNpub.slice(0, 8)}...`);
|
||||
} else {
|
||||
console.log(`DMS: Store ${storeName} does not exist for user ${userNpub.slice(0, 8)}..., nothing to clear`);
|
||||
}
|
||||
|
||||
await db.close();
|
||||
} catch (error) {
|
||||
console.error('DMS: Error clearing messages from IndexedDB:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import type { NostrEvent } from '@nostrify/nostrify';
|
||||
|
||||
/**
|
||||
* DM Tab Types - for organizing conversations
|
||||
*/
|
||||
export type DMTabType = 'known' | 'newRequests';
|
||||
|
||||
/**
|
||||
* Message Protocol Types
|
||||
*/
|
||||
export const MESSAGE_PROTOCOL = {
|
||||
NIP04: 'NIP04',
|
||||
NIP17: 'NIP17',
|
||||
UNKNOWN: 'UNKNOWN'
|
||||
} as const;
|
||||
|
||||
export type MessageProtocol = typeof MESSAGE_PROTOCOL[keyof typeof MESSAGE_PROTOCOL];
|
||||
|
||||
/**
|
||||
* Decrypted message with additional metadata
|
||||
*/
|
||||
export interface DecryptedMessage extends NostrEvent {
|
||||
decryptedContent?: string;
|
||||
error?: string;
|
||||
isSending?: boolean;
|
||||
clientFirstSeen?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* DM Conversation structure
|
||||
*/
|
||||
export interface DMConversation {
|
||||
id: string; // The other person's pubkey
|
||||
pubkey: string;
|
||||
lastMessage?: DecryptedMessage;
|
||||
lastMessageTime: number;
|
||||
unreadCount: number;
|
||||
// Conversation categorization
|
||||
isKnown?: boolean; // User has sent at least one message to this person
|
||||
isRequest?: boolean; // Other person has sent messages, but user hasn't replied
|
||||
// Reply status tracking
|
||||
lastMessageFromUser?: boolean; // True if user sent the last message, false if other person did
|
||||
}
|
||||
|
||||
/**
|
||||
* Message sending parameters
|
||||
*/
|
||||
export interface SendMessageParams {
|
||||
recipientPubkey: string;
|
||||
content: string;
|
||||
protocol?: MessageProtocol; // Optional - defaults to NIP-04
|
||||
attachments?: Array<{
|
||||
url: string;
|
||||
mimeType: string;
|
||||
size: number;
|
||||
name: string;
|
||||
tags: string[][];
|
||||
}>;
|
||||
}
|
||||
Reference in new issue
Block a user