From 4c21a4147c016652b9c2185393d397d29e16f6f7 Mon Sep 17 00:00:00 2001 From: lemonknowsall Date: Mon, 22 Sep 2025 21:01:06 -0700 Subject: [PATCH] added push notification hook --- AGENTS.md | 43 +++ src/hooks/usePush.ts | 615 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 658 insertions(+) create mode 100644 src/hooks/usePush.ts diff --git a/AGENTS.md b/AGENTS.md index f6e89c6..c615884 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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 ( + + ); +} +``` + +#### 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: diff --git a/src/hooks/usePush.ts b/src/hooks/usePush.ts new file mode 100644 index 0000000..111b2d0 --- /dev/null +++ b/src/hooks/usePush.ts @@ -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; +} + +/** + * 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; + 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(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 + ): Promise => { + 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 => { + 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 & { is_active: boolean }> + ): Promise => { + 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 => { + 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 => { + 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 => { + 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 => { + 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 => { + 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 + ): Promise => { + 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 + ): Promise => { + 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 + ): Promise => { + 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 ( + * + * ); + * } + * ``` + */