Author SHA1 Message Date
lemonknowsall 4c21a4147c added push notification hook 2025-09-22 21:01:06 -07:00
9 changed files with 658 additions and 544 deletions

No files matched your search

+43
View File
@@ -36,6 +36,7 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3.
- `useWallet`: Unified wallet detection (WebLN + NWC)
- `useNWC`: Nostr Wallet Connect connection management
- `useNWCContext`: Access NWC context provider
- `usePush`: Push notifications via Nostr RPC
- `/src/pages/`: Page components used by React Router (Index, NotFound)
- `/src/lib/`: Utility functions and shared logic
- `/src/contexts/`: React context providers (AppContext, NWCContext)
@@ -842,6 +843,48 @@ const encrypted = await user.signer.nip44.encrypt(user.pubkey, "hello world");
const decrypted = await user.signer.nip44.decrypt(user.pubkey, encrypted) // "hello world"
```
### Push Notifications
The project includes `usePush` hook for managing push notifications via Nostr RPC. This enables users to receive browser notifications for Nostr events.
#### Basic Usage
```tsx
import { usePush } from '@/hooks/usePush';
function NotificationButton({ authorPubkey }: { authorPubkey: string }) {
const { subscribeToAuthor, isLoading, error } = usePush();
const handleEnableNotifications = async () => {
try {
await subscribeToAuthor(authorPubkey);
} catch (error) {
console.error('Failed to enable notifications:', error);
}
};
return (
<Button onClick={handleEnableNotifications} disabled={isLoading}>
{isLoading ? 'Enabling...' : 'Enable Notifications'}
</Button>
);
}
```
#### Available Methods
- **`subscribeToAuthor`**: Get notifications for new posts from a specific user
- **`subscribeToMentions`**: Get notifications when mentioned in posts
- **`subscribeToHashtag`**: Get notifications for posts with specific hashtags
- **`registerSubscription`**: Create custom notification subscriptions
- **`deleteSubscription`**: Remove notification subscriptions
#### Requirements
- User must be logged in with NIP-44 encryption support
- Browser must support push notifications
- VAPID public key is included by default
### Rendering Rich Text Content
Nostr text notes (kind 1, 11, and 1111) have a plaintext `content` field that may contain URLs, hashtags, and Nostr URIs. These events should render their content using the `NoteContent` component:
-7
View File
@@ -48,7 +48,6 @@
"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",
@@ -5487,12 +5486,6 @@
"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",
-1
View File
@@ -50,7 +50,6 @@
"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",
+615
View File
@@ -0,0 +1,615 @@
import { useState, useCallback } from 'react';
import { useNostr } from '@nostrify/react';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useToast } from '@/hooks/useToast';
import { nip19 } from 'nostr-tools';
// Your VAPID public key
const VAPID_PUBLIC_KEY = 'BIur4J9v796yU2ZUhaka6exwLAKUhAnDv0zJhrf_T1yuFs4jh4g8IaYygGAJ7u1KxZdu2Dwxh1ae5ob8yClHamc';
/**
* Push subscription configuration for Web Push API
*/
export interface PushSubscription {
endpoint: string;
p256dh_key: string;
auth_key: string;
}
/**
* Nostr event filter for push notifications
*/
export interface NotificationFilter {
kinds?: number[];
authors?: string[];
"#p"?: string[];
"#t"?: string[];
since?: number;
until?: number;
limit?: number;
}
/**
* Notification content configuration
*/
export interface NotificationConfig {
title: string;
body: string;
icon?: string;
badge?: string;
data?: Record<string, unknown>;
}
/**
* Complete subscription object for push notifications
*/
export interface PushNotificationSubscription {
subscription_id: string;
domain: string;
filter: NotificationFilter;
notification: NotificationConfig;
push_subscription: PushSubscription;
}
/**
* RPC request structure for push notification server
*/
interface RPCRequest {
method: 'register_subscription' | 'update_subscription' | 'delete_subscription' | 'list_subscriptions' | 'get_subscription';
params: Record<string, unknown>;
request_id: string;
}
/**
* Hook for managing push notifications via Nostr RPC
* Sends encrypted RPC events to a push notification worker
*/
export function usePush(workerPubkey?: string) {
const { nostr } = useNostr();
const { user } = useCurrentUser();
const { toast } = useToast();
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
// Default worker pubkey - your actual push notification server
const defaultWorkerPubkey = workerPubkey || '7c3be2769c76eecd6c6e27276722dfae0d8ad201825253452153b90093c41654';
const clearError = useCallback(() => {
setError(null);
}, []);
/**
* Send an encrypted RPC request to the push notification worker
*/
const sendRPCRequest = useCallback(async (
method: RPCRequest['method'],
params: Record<string, unknown>
): Promise<void> => {
if (!user?.signer) {
throw new Error('User must be logged in to manage push notifications');
}
if (!user.signer.nip44) {
throw new Error('Signer must support NIP-44 encryption for push notifications');
}
// Decode worker pubkey if it's in npub format
let workerHex = defaultWorkerPubkey;
if (defaultWorkerPubkey.startsWith('npub1')) {
const decoded = nip19.decode(defaultWorkerPubkey);
if (decoded.type !== 'npub') {
throw new Error('Invalid worker pubkey format');
}
workerHex = decoded.data;
}
const requestId = `req_${crypto.randomUUID().replace(/-/g, "").slice(0, 8)}`;
const request: RPCRequest = {
method,
params,
request_id: requestId,
};
try {
// Encrypt the request using NIP-44
const payload = JSON.stringify(request);
console.log('Encrypting RPC request payload:', payload);
const encryptedRequest = await user.signer.nip44.encrypt(workerHex, payload);
console.log('Encrypted request:', encryptedRequest);
// Create unsigned RPC event (kind 25742)
const unsignedEvent = {
kind: 25742,
content: encryptedRequest,
tags: [
['p', workerHex],
['rpc', requestId],
['method', method],
],
created_at: Math.floor(Date.now() / 1000),
};
console.log('Signing RPC event:', unsignedEvent);
console.log('Target worker pubkey:', workerHex);
// Sign the event using the user's signer
const signedEvent = await user.signer.signEvent(unsignedEvent);
console.log('Signed RPC event:', signedEvent);
// Send the signed RPC event
const result = await nostr.event(signedEvent);
console.log('RPC event sent result:', result);
return;
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Unknown error occurred';
console.error('RPC send error:', err);
throw new Error(`Failed to send push notification request: ${errorMessage}`);
}
}, [user, nostr, defaultWorkerPubkey]);
/**
* Register a new push notification subscription
*/
const registerSubscription = useCallback(async (
subscriptionId: string,
domain: string,
filter: NotificationFilter,
notification: NotificationConfig,
pushSubscription: PushSubscription
): Promise<void> => {
setIsLoading(true);
setError(null);
try {
await sendRPCRequest('register_subscription', {
subscription_id: subscriptionId,
domain,
filter,
notification,
push_subscription: pushSubscription,
});
toast({
title: 'Push notifications enabled',
description: 'You will now receive push notifications for this content.',
});
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to register subscription';
setError(errorMessage);
toast({
title: 'Failed to enable notifications',
description: errorMessage,
variant: 'destructive',
});
throw err;
} finally {
setIsLoading(false);
}
}, [sendRPCRequest, toast]);
/**
* Update an existing push notification subscription
*/
const updateSubscription = useCallback(async (
subscriptionId: string,
domain: string,
updates: Partial<Pick<PushNotificationSubscription, 'filter' | 'notification' | 'push_subscription'> & { is_active: boolean }>
): Promise<void> => {
setIsLoading(true);
setError(null);
try {
await sendRPCRequest('update_subscription', {
subscription_id: subscriptionId,
domain,
updates,
});
toast({
title: 'Subscription updated',
description: 'Your push notification settings have been updated.',
});
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to update subscription';
setError(errorMessage);
toast({
title: 'Failed to update notifications',
description: errorMessage,
variant: 'destructive',
});
throw err;
} finally {
setIsLoading(false);
}
}, [sendRPCRequest, toast]);
/**
* Delete a push notification subscription
*/
const deleteSubscription = useCallback(async (
subscriptionId: string,
domain: string
): Promise<void> => {
setIsLoading(true);
setError(null);
try {
await sendRPCRequest('delete_subscription', {
subscription_id: subscriptionId,
domain,
});
toast({
title: 'Push notifications disabled',
description: 'You will no longer receive push notifications for this content.',
});
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to delete subscription';
setError(errorMessage);
toast({
title: 'Failed to disable notifications',
description: errorMessage,
variant: 'destructive',
});
throw err;
} finally {
setIsLoading(false);
}
}, [sendRPCRequest, toast]);
/**
* List all subscriptions for a domain
*/
const listSubscriptions = useCallback(async (domain: string): Promise<void> => {
setIsLoading(true);
setError(null);
try {
await sendRPCRequest('list_subscriptions', { domain });
// Note: This is a fire-and-forget operation - the worker logs the results
// In a full implementation, you might want to listen for response events
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to list subscriptions';
setError(errorMessage);
throw err;
} finally {
setIsLoading(false);
}
}, [sendRPCRequest]);
/**
* Get a specific subscription
*/
const getSubscription = useCallback(async (subscriptionId: string): Promise<void> => {
setIsLoading(true);
setError(null);
try {
await sendRPCRequest('get_subscription', { subscription_id: subscriptionId });
// Note: This is a fire-and-forget operation - the worker logs the results
// In a full implementation, you might want to listen for response events
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to get subscription';
setError(errorMessage);
throw err;
} finally {
setIsLoading(false);
}
}, [sendRPCRequest]);
/**
* Request browser permission for push notifications
*/
const requestNotificationPermission = useCallback(async (): Promise<NotificationPermission> => {
if (!('Notification' in window)) {
throw new Error('This browser does not support push notifications');
}
if (Notification.permission === 'granted') {
return 'granted';
}
if (Notification.permission === 'denied') {
throw new Error('Push notifications are blocked. Please enable them in your browser settings.');
}
const permission = await Notification.requestPermission();
if (permission !== 'granted') {
throw new Error('Push notification permission was denied');
}
return permission;
}, []);
/**
* Convert npub to hex format for use in filters
*/
const convertNpubToHex = useCallback((pubkey: string): string => {
if (pubkey.startsWith('npub1')) {
try {
const decoded = nip19.decode(pubkey);
if (decoded.type !== 'npub') {
throw new Error('Invalid npub format');
}
return decoded.data;
} catch (error) {
throw new Error(`Failed to decode npub: ${error instanceof Error ? error.message : String(error)}`);
}
}
// If it's already hex format, return as-is
return pubkey;
}, []);
/**
* Convert VAPID key from base64url string to Uint8Array (matches working implementation)
*/
const convertVapidKey = useCallback((key: string): Uint8Array => {
try {
// Add padding if needed
const padding = '='.repeat((4 - (key.length % 4)) % 4);
const base64 = (key + padding).replace(/-/g, '+').replace(/_/g, '/');
// Decode base64 to binary string
const rawData = window.atob(base64);
// Convert binary string to Uint8Array
const outputArray = new Uint8Array(rawData.length);
for (let i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i);
}
console.log('VAPID key converted:', {
originalLength: key.length,
base64Length: base64.length,
outputLength: outputArray.length,
firstBytes: Array.from(outputArray.slice(0, 10))
});
return outputArray;
} catch (err) {
throw new Error(`Invalid VAPID key format: ${err instanceof Error ? err.message : String(err)}`);
}
}, []);
/**
* Subscribe to browser push notifications and get subscription details
*/
const subscribeToPush = useCallback(async (vapidPublicKey: string = VAPID_PUBLIC_KEY): Promise<PushSubscription> => {
if (!('serviceWorker' in navigator) || !('PushManager' in window)) {
throw new Error('Push notifications are not supported in this browser');
}
await requestNotificationPermission();
// Register service worker and wait for it to be ready
const registration = await navigator.serviceWorker.ready;
console.log('Service worker ready:', registration);
console.log('Service worker scope:', registration.scope);
console.log('Service worker active:', !!registration.active);
// Check if already subscribed
const existingSubscription = await registration.pushManager.getSubscription();
console.log('Existing subscription:', existingSubscription);
// Convert VAPID key to proper format
console.log('VAPID public key (base64):', vapidPublicKey);
const applicationServerKey = convertVapidKey(vapidPublicKey);
console.log('VAPID key converted to Uint8Array, length:', applicationServerKey.length);
let subscription;
try {
console.log('Attempting to subscribe to push manager...');
// Subscribe to push notifications
subscription = await registration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey,
});
console.log('Push subscription successful:', subscription);
} catch (pushError: any) {
console.error('Push subscription failed with error:', pushError);
console.error('Error name:', pushError.name);
console.error('Error message:', pushError.message);
// Provide specific error messages based on error type
if (pushError.name === 'InvalidStateError') {
throw new Error('Push subscription failed: Invalid state (possibly already subscribed)');
} else if (pushError.name === 'NotAllowedError') {
throw new Error('Push subscription failed: Permission denied by user');
} else if (pushError.name === 'NotSupportedError') {
throw new Error('Push subscription failed: Push not supported by this browser/service');
} else if (pushError.name === 'AbortError') {
throw new Error('Push subscription failed: Request was aborted (VAPID key mismatch?)');
} else {
throw new Error(`Push subscription failed: ${pushError.name} - ${pushError.message}`);
}
}
// Extract keys safely
const subscriptionJson = subscription.toJSON();
const keys = subscriptionJson.keys;
if (!keys?.p256dh || !keys?.auth) {
throw new Error('Invalid subscription keys received');
}
// Convert to our format
return {
endpoint: subscription.endpoint,
p256dh_key: keys.p256dh,
auth_key: keys.auth,
};
}, [requestNotificationPermission, convertVapidKey]);
/**
* Helper function to create a subscription for following an author
*/
const subscribeToAuthor = useCallback(async (
authorPubkey: string,
vapidPublicKey: string = VAPID_PUBLIC_KEY,
domain: string = window.location.hostname,
customNotification?: Partial<NotificationConfig>
): Promise<void> => {
const pushSubscription = await subscribeToPush(vapidPublicKey);
// Convert npub to hex format for the filter
const authorHex = convertNpubToHex(authorPubkey);
const subscriptionId = `follow-${authorHex.slice(0, 16)}-${Date.now()}`;
const filter: NotificationFilter = {
kinds: [1], // Text notes
authors: [authorHex], // Use hex format
limit: 50,
};
const notification: NotificationConfig = {
title: '{{author_name}} posted something!',
body: '{{content}}',
icon: '/icon-192x192.png',
badge: '/badge-72x72.png',
data: {
type: 'new_post',
author: authorHex, // Store hex format in data as well
},
...customNotification,
};
await registerSubscription(subscriptionId, domain, filter, notification, pushSubscription);
}, [subscribeToPush, registerSubscription, convertNpubToHex]);
/**
* Helper function to create a subscription for mentions
*/
const subscribeToMentions = useCallback(async (
userPubkey: string,
vapidPublicKey: string = VAPID_PUBLIC_KEY,
domain: string = window.location.hostname,
customNotification?: Partial<NotificationConfig>
): Promise<void> => {
const pushSubscription = await subscribeToPush(vapidPublicKey);
// Convert npub to hex format for the filter
const userHex = convertNpubToHex(userPubkey);
const subscriptionId = `mentions-${userHex.slice(0, 16)}-${Date.now()}`;
const filter: NotificationFilter = {
kinds: [1], // Text notes
"#p": [userHex], // Mentions of the user (use hex format)
limit: 50,
};
const notification: NotificationConfig = {
title: '{{author_name}} mentioned you!',
body: '{{content}}',
icon: '/icon-192x192.png',
badge: '/badge-72x72.png',
data: {
type: 'mention',
user: userHex, // Store hex format in data as well
},
...customNotification,
};
await registerSubscription(subscriptionId, domain, filter, notification, pushSubscription);
}, [subscribeToPush, registerSubscription, convertNpubToHex]);
/**
* Helper function to create a subscription for hashtags
*/
const subscribeToHashtag = useCallback(async (
hashtag: string,
vapidPublicKey: string = VAPID_PUBLIC_KEY,
domain: string = window.location.hostname,
customNotification?: Partial<NotificationConfig>
): Promise<void> => {
const pushSubscription = await subscribeToPush(vapidPublicKey);
const subscriptionId = `hashtag-${hashtag}-${Date.now()}`;
const filter: NotificationFilter = {
kinds: [1], // Text notes
"#t": [hashtag], // Posts with the hashtag
limit: 50,
};
const notification: NotificationConfig = {
title: `{{author_name}} posted about #${hashtag}`,
body: `{{content}}`,
icon: '/icon-192x192.png',
badge: '/badge-72x72.png',
data: {
type: 'hashtag',
hashtag,
},
...customNotification,
};
await registerSubscription(subscriptionId, domain, filter, notification, pushSubscription);
}, [subscribeToPush, registerSubscription]);
return {
// Core RPC methods
registerSubscription,
updateSubscription,
deleteSubscription,
listSubscriptions,
getSubscription,
// Browser push notification helpers
requestNotificationPermission,
subscribeToPush,
// Convenience methods for common use cases
subscribeToAuthor,
subscribeToMentions,
subscribeToHashtag,
// State
isLoading,
error,
clearError,
// Config
workerPubkey: defaultWorkerPubkey,
};
}
/**
* Example usage:
*
* ```tsx
* import { usePush } from '@/hooks/usePush';
*
* function MyComponent() {
* const {
* subscribeToAuthor,
* subscribeToMentions,
* isLoading,
* error
* } = usePush('npub1yourpushworkerpubkey');
*
* const handleFollowNotifications = async (authorPubkey: string) => {
* try {
* await subscribeToAuthor(authorPubkey, 'myapp.com');
* } catch (error) {
* console.error('Failed to enable notifications:', error);
* }
* };
*
* return (
* <Button
* onClick={() => handleFollowNotifications('npub1author...')}
* disabled={isLoading}
* >
* {isLoading ? 'Enabling...' : 'Enable Notifications'}
* </Button>
* );
* }
* ```
*/
-193
View File
@@ -1,193 +0,0 @@
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,
};
}
-56
View File
@@ -1,56 +0,0 @@
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;
-61
View File
@@ -1,61 +0,0 @@
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;
});
}
-167
View File
@@ -1,167 +0,0 @@
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;
}
}
-59
View File
@@ -1,59 +0,0 @@
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[][];
}>;
}