mirror of
https://gitlab.com/soapbox-pub/mkstack.git
synced 2026-12-05 08:23:35 +00:00
wip initial dump of DM stuff from universes
This commit is contained in:
1 parent
49abb22471
commit
1d42551b36
8 files changed
+5663
-6
No files matched your search
@@ -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",
|
||||
|
||||
+13
-6
@@ -11,6 +11,7 @@ import { TooltipProvider } from "@/components/ui/tooltip";
|
||||
import { NostrLoginProvider } from '@nostrify/react/login';
|
||||
import { AppProvider } from '@/components/AppProvider';
|
||||
import { NWCProvider } from '@/contexts/NWCContext';
|
||||
import { DMProvider } from '@/contexts/DMContext';
|
||||
import { AppConfig } from '@/contexts/AppContext';
|
||||
import AppRouter from './AppRouter';
|
||||
|
||||
@@ -42,6 +43,10 @@ const presetRelays = [
|
||||
{ url: 'wss://relay.primal.net', name: 'Primal' },
|
||||
];
|
||||
|
||||
const dmSettings = {
|
||||
enableNIP17: true,
|
||||
};
|
||||
|
||||
export function App() {
|
||||
return (
|
||||
<UnheadProvider head={head}>
|
||||
@@ -50,12 +55,14 @@ export function App() {
|
||||
<NostrLoginProvider storageKey='nostr:login'>
|
||||
<NostrProvider>
|
||||
<NWCProvider>
|
||||
<TooltipProvider>
|
||||
<Toaster />
|
||||
<Suspense>
|
||||
<AppRouter />
|
||||
</Suspense>
|
||||
</TooltipProvider>
|
||||
<DMProvider enableNIP17={dmSettings.enableNIP17}>
|
||||
<TooltipProvider>
|
||||
<Toaster />
|
||||
<Suspense>
|
||||
<AppRouter />
|
||||
</Suspense>
|
||||
</TooltipProvider>
|
||||
</DMProvider>
|
||||
</NWCProvider>
|
||||
</NostrProvider>
|
||||
</NostrLoginProvider>
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,233 @@
|
||||
import { useMutation, type UseMutationResult } from '@tanstack/react-query';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useNostrPublish } from '@/hooks/useNostrPublish';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import type { NostrEvent } from '@nostrify/nostrify';
|
||||
|
||||
// ============================================================================
|
||||
// Types
|
||||
// ============================================================================
|
||||
|
||||
interface FileAttachment {
|
||||
url: string;
|
||||
mimeType: string;
|
||||
size: number;
|
||||
name: string;
|
||||
tags: string[][];
|
||||
}
|
||||
|
||||
interface SendNIP4MessageParams {
|
||||
recipientPubkey: string;
|
||||
content: string;
|
||||
attachments?: FileAttachment[];
|
||||
}
|
||||
|
||||
interface SendNIP17MessageParams {
|
||||
recipientPubkey: string;
|
||||
content: string;
|
||||
attachments?: FileAttachment[];
|
||||
}
|
||||
|
||||
interface UseSendDMReturn {
|
||||
sendNIP4Message: UseMutationResult<NostrEvent, Error, SendNIP4MessageParams>;
|
||||
sendNIP17Message: UseMutationResult<NostrEvent, Error, SendNIP17MessageParams>;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Helper Functions
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* Prepare message content with file URLs appended
|
||||
*/
|
||||
function prepareMessageContent(content: string, attachments: FileAttachment[] = []): string {
|
||||
if (attachments.length === 0) return content;
|
||||
|
||||
const fileUrls = attachments.map(file => file.url).join('\n');
|
||||
return content ? `${content}\n\n${fileUrls}` : fileUrls;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create imeta tags for file attachments (NIP-92)
|
||||
*/
|
||||
function createImetaTags(attachments: FileAttachment[] = []): string[][] {
|
||||
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}`);
|
||||
|
||||
// Add hash tags from file.tags
|
||||
file.tags.forEach(tag => {
|
||||
if (tag[0] === 'x') imetaTag.push(`x ${tag[1]}`);
|
||||
if (tag[0] === 'ox') imetaTag.push(`ox ${tag[1]}`);
|
||||
});
|
||||
|
||||
return imetaTag;
|
||||
});
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Hook
|
||||
// ============================================================================
|
||||
|
||||
export function useSendDM(): UseSendDMReturn {
|
||||
const { user } = useCurrentUser();
|
||||
const { mutate: createEvent } = useNostrPublish();
|
||||
const { toast } = useToast();
|
||||
|
||||
// Send NIP-04 Message
|
||||
const sendNIP4Message = useMutation<NostrEvent, Error, SendNIP4MessageParams>({
|
||||
mutationFn: async ({ recipientPubkey, content, attachments = [] }) => {
|
||||
if (!user) {
|
||||
throw new Error('User is not logged in');
|
||||
}
|
||||
|
||||
if (!user.signer.nip04) {
|
||||
throw new Error('NIP-04 encryption not available');
|
||||
}
|
||||
|
||||
// Prepare content with file URLs
|
||||
const messageContent = prepareMessageContent(content, attachments);
|
||||
|
||||
// Encrypt the content
|
||||
const encryptedContent = await user.signer.nip04.encrypt(recipientPubkey, messageContent);
|
||||
|
||||
// Build tags with imeta tags for attachments
|
||||
const tags: string[][] = [
|
||||
['p', recipientPubkey],
|
||||
...createImetaTags(attachments)
|
||||
];
|
||||
|
||||
// Create and publish the event
|
||||
return new Promise((resolve, reject) => {
|
||||
createEvent(
|
||||
{
|
||||
kind: 4,
|
||||
content: encryptedContent,
|
||||
tags,
|
||||
},
|
||||
{
|
||||
onSuccess: (event) => resolve(event),
|
||||
onError: (error) => reject(error),
|
||||
}
|
||||
);
|
||||
});
|
||||
},
|
||||
onError: (error) => {
|
||||
console.error('[useSendDM] Failed to send NIP-04 message:', error);
|
||||
toast({
|
||||
title: 'Failed to send message',
|
||||
description: error.message,
|
||||
variant: 'destructive',
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
// Send NIP-17 Message
|
||||
const sendNIP17Message = useMutation<NostrEvent, Error, SendNIP17MessageParams>({
|
||||
mutationFn: async ({ recipientPubkey, content, attachments = [] }) => {
|
||||
if (!user) {
|
||||
throw new Error('User is not logged in');
|
||||
}
|
||||
|
||||
if (!user.signer.nip44) {
|
||||
throw new Error('NIP-44 encryption not available');
|
||||
}
|
||||
|
||||
// Step 1: Create the inner Kind 14 Private Direct Message
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
|
||||
// Prepare content with file URLs
|
||||
const messageContent = prepareMessageContent(content, attachments);
|
||||
|
||||
// Build tags with imeta tags for attachments
|
||||
const tags: string[][] = [
|
||||
['p', recipientPubkey],
|
||||
...createImetaTags(attachments)
|
||||
];
|
||||
|
||||
const privateMessage: Omit<NostrEvent, 'id' | 'sig'> = {
|
||||
kind: 14,
|
||||
pubkey: user.pubkey,
|
||||
created_at: now,
|
||||
tags,
|
||||
content: messageContent,
|
||||
};
|
||||
|
||||
// Step 2: Create TWO Kind 13 Seal events (one for recipient, one for myself)
|
||||
const recipientSeal: Omit<NostrEvent, 'id' | 'sig'> = {
|
||||
kind: 13,
|
||||
pubkey: user.pubkey,
|
||||
created_at: now,
|
||||
tags: [],
|
||||
content: await user.signer.nip44.encrypt(recipientPubkey, JSON.stringify(privateMessage)),
|
||||
};
|
||||
|
||||
const senderSeal: Omit<NostrEvent, 'id' | 'sig'> = {
|
||||
kind: 13,
|
||||
pubkey: user.pubkey,
|
||||
created_at: now,
|
||||
tags: [],
|
||||
content: await user.signer.nip44.encrypt(user.pubkey, JSON.stringify(privateMessage)),
|
||||
};
|
||||
|
||||
// Step 3: Create TWO Kind 1059 Gift Wrap events
|
||||
// NOTE: This implementation uses the user's key for signing.
|
||||
// todo: For maximum privacy, this should use a random key (see NIP-59).
|
||||
// That fix will be implemented separately.
|
||||
|
||||
// Encrypt the seals first
|
||||
const recipientGiftWrapContent = await user.signer.nip44.encrypt(recipientPubkey, JSON.stringify(recipientSeal));
|
||||
const myGiftWrapContent = await user.signer.nip44.encrypt(user.pubkey, JSON.stringify(senderSeal));
|
||||
|
||||
const recipientGiftWrapPromise = new Promise<NostrEvent>((resolve, reject) => {
|
||||
createEvent(
|
||||
{
|
||||
kind: 1059,
|
||||
content: recipientGiftWrapContent,
|
||||
tags: [['p', recipientPubkey]],
|
||||
},
|
||||
{
|
||||
onSuccess: (event) => resolve(event),
|
||||
onError: (error) => reject(error),
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
const myGiftWrapPromise = new Promise<NostrEvent>((resolve, reject) => {
|
||||
createEvent(
|
||||
{
|
||||
kind: 1059,
|
||||
content: myGiftWrapContent,
|
||||
tags: [['p', user.pubkey]],
|
||||
},
|
||||
{
|
||||
onSuccess: (event) => resolve(event),
|
||||
onError: (error) => reject(error),
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
// Wait for both gift wraps to be published
|
||||
const [recipientGiftWrap] = await Promise.all([recipientGiftWrapPromise, myGiftWrapPromise]);
|
||||
|
||||
// Return the recipient's gift wrap as the "result"
|
||||
return recipientGiftWrap;
|
||||
},
|
||||
onError: (error) => {
|
||||
console.error('[useSendDM] Failed to send NIP-17 message:', error);
|
||||
toast({
|
||||
title: 'Failed to send message',
|
||||
description: error.message,
|
||||
variant: 'destructive',
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
sendNIP4Message,
|
||||
sendNIP17Message,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import type { NostrEvent } from '@nostrify/nostrify';
|
||||
|
||||
// ============================================================================
|
||||
// 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];
|
||||
|
||||
// ============================================================================
|
||||
// Loading Phases
|
||||
// ============================================================================
|
||||
|
||||
export const LOADING_PHASES = {
|
||||
IDLE: 'idle',
|
||||
CACHE: 'cache',
|
||||
RELAYS: 'relays',
|
||||
SUBSCRIPTIONS: 'subscriptions',
|
||||
READY: 'ready',
|
||||
} as const;
|
||||
|
||||
export type LoadingPhase = typeof LOADING_PHASES[keyof typeof LOADING_PHASES];
|
||||
|
||||
// ============================================================================
|
||||
// Protocol Configuration
|
||||
// ============================================================================
|
||||
|
||||
export const PROTOCOL_CONFIG = {
|
||||
[MESSAGE_PROTOCOL.NIP04]: {
|
||||
label: 'NIP-04',
|
||||
description: 'Legacy DMs',
|
||||
kind: 4,
|
||||
},
|
||||
[MESSAGE_PROTOCOL.NIP17]: {
|
||||
label: 'NIP-17',
|
||||
description: 'Private DMs',
|
||||
kind: 1059,
|
||||
},
|
||||
[MESSAGE_PROTOCOL.UNKNOWN]: {
|
||||
label: 'Unknown',
|
||||
description: 'Unknown protocol',
|
||||
kind: 0,
|
||||
},
|
||||
} as const;
|
||||
|
||||
// ============================================================================
|
||||
// Helper Functions
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* Get the message protocol from an event kind
|
||||
*/
|
||||
export function getMessageProtocol(event: NostrEvent): MessageProtocol {
|
||||
switch (event.kind) {
|
||||
case 4:
|
||||
return MESSAGE_PROTOCOL.NIP04;
|
||||
case 1059:
|
||||
return MESSAGE_PROTOCOL.NIP17;
|
||||
default:
|
||||
return MESSAGE_PROTOCOL.UNKNOWN;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a protocol is valid for sending messages
|
||||
*/
|
||||
export function isValidSendProtocol(protocol: MessageProtocol): boolean {
|
||||
return protocol === MESSAGE_PROTOCOL.NIP04 || protocol === MESSAGE_PROTOCOL.NIP17;
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
import { openDB, type IDBPDatabase } from 'idb';
|
||||
import type { NostrEvent } from '@nostrify/nostrify';
|
||||
|
||||
// ============================================================================
|
||||
// IndexedDB Schema
|
||||
// ============================================================================
|
||||
|
||||
const DB_NAME = 'nostr-dm-store';
|
||||
const DB_VERSION = 1;
|
||||
const STORE_NAME = 'messages';
|
||||
|
||||
interface StoredParticipant {
|
||||
messages: NostrEvent[];
|
||||
lastActivity: number;
|
||||
hasNIP4: boolean;
|
||||
hasNIP17: boolean;
|
||||
}
|
||||
|
||||
export interface MessageStore {
|
||||
participants: Record<string, StoredParticipant>;
|
||||
lastSync: {
|
||||
nip4: number | null;
|
||||
nip17: number | null;
|
||||
};
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Database Operations
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* Open the IndexedDB database
|
||||
*/
|
||||
async function openDatabase(): Promise<IDBPDatabase> {
|
||||
return openDB(DB_NAME, DB_VERSION, {
|
||||
upgrade(db) {
|
||||
// Create the messages store if it doesn't exist
|
||||
if (!db.objectStoreNames.contains(STORE_NAME)) {
|
||||
db.createObjectStore(STORE_NAME);
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Write messages to IndexedDB for a specific user
|
||||
*/
|
||||
export async function writeMessagesToDB(
|
||||
userPubkey: string,
|
||||
messageStore: MessageStore
|
||||
): Promise<void> {
|
||||
try {
|
||||
const db = await openDatabase();
|
||||
await db.put(STORE_NAME, messageStore, userPubkey);
|
||||
} catch (error) {
|
||||
console.error('[MessageStore] Error writing to IndexedDB:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Read messages from IndexedDB for a specific user
|
||||
*/
|
||||
export async function readMessagesFromDB(
|
||||
userPubkey: string
|
||||
): Promise<MessageStore | undefined> {
|
||||
try {
|
||||
const db = await openDatabase();
|
||||
const data = await db.get(STORE_NAME, userPubkey);
|
||||
return data as MessageStore | undefined;
|
||||
} catch (error) {
|
||||
console.error('[MessageStore] Error reading from IndexedDB:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete messages from IndexedDB for a specific user
|
||||
*/
|
||||
export async function deleteMessagesFromDB(userPubkey: string): Promise<void> {
|
||||
try {
|
||||
const db = await openDatabase();
|
||||
await db.delete(STORE_NAME, userPubkey);
|
||||
} catch (error) {
|
||||
console.error('[MessageStore] Error deleting from IndexedDB:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear all messages from IndexedDB
|
||||
*/
|
||||
export async function clearAllMessages(): Promise<void> {
|
||||
try {
|
||||
const db = await openDatabase();
|
||||
await db.clear(STORE_NAME);
|
||||
} catch (error) {
|
||||
console.error('[MessageStore] Error clearing IndexedDB:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import type { NostrEvent } from '@nostrify/nostrify';
|
||||
|
||||
/**
|
||||
* Validate that an event is a proper DM event
|
||||
*/
|
||||
export function validateDMEvent(event: NostrEvent): boolean {
|
||||
// Must be kind 4 (NIP-04 DM)
|
||||
if (event.kind !== 4) return false;
|
||||
|
||||
// Must have a 'p' tag
|
||||
const hasRecipient = event.tags?.some(([name]) => name === 'p');
|
||||
if (!hasRecipient) return false;
|
||||
|
||||
// Must have content (even if encrypted)
|
||||
if (!event.content) return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the recipient pubkey from a DM event
|
||||
*/
|
||||
export function getRecipientPubkey(event: NostrEvent): string | undefined {
|
||||
return event.tags?.find(([name]) => name === 'p')?.[1];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the conversation partner pubkey from a DM event
|
||||
* (the other person in the conversation, not the current user)
|
||||
*/
|
||||
export function getConversationPartner(event: NostrEvent, userPubkey: string): string | undefined {
|
||||
const isFromUser = event.pubkey === userPubkey;
|
||||
|
||||
if (isFromUser) {
|
||||
// If we sent it, the partner is the recipient
|
||||
return getRecipientPubkey(event);
|
||||
} else {
|
||||
// If they sent it, the partner is the author
|
||||
return event.pubkey;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user