From 8eddf49e61576cd81a8e49e09281abd996165664 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Tue, 4 Nov 2025 23:46:16 -0600 Subject: [PATCH] Implement NIP-65 relay management - Replace single relayUrl with NIP-65 compatible relayMetadata structure - Add RelayListManager component for managing multiple relays with read/write permissions - Add NostrSync component to automatically sync user's NIP-65 relay list on login - Update NostrProvider to use relay list instead of single relay - Remove RelaySelector component and update empty states - Update AGENTS.md documentation to reflect relay management changes - Automatically publish relay list changes as NIP-65 events when user is logged in --- AGENTS.md | 44 +++- src/App.tsx | 22 +- src/components/AppProvider.tsx | 22 +- src/components/DMProvider.tsx | 84 ++++---- src/components/NostrProvider.tsx | 42 ++-- src/components/NostrSync.tsx | 62 ++++++ src/components/RelayListManager.tsx | 272 ++++++++++++++++++++++++ src/components/RelaySelector.tsx | 174 --------------- src/components/auth/AccountSwitcher.tsx | 4 - src/contexts/AppContext.ts | 13 +- src/hooks/useZaps.ts | 2 +- src/pages/Messages.tsx | 2 - src/test/TestApp.tsx | 7 +- 13 files changed, 478 insertions(+), 272 deletions(-) create mode 100644 src/components/NostrSync.tsx create mode 100644 src/components/RelayListManager.tsx delete mode 100644 src/components/RelaySelector.tsx diff --git a/AGENTS.md b/AGENTS.md index 2adc65f..9d5be10 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -756,7 +756,7 @@ The project includes a complete direct messaging system with real-time updates, For complete implementation guide including: - Setup and configuration -- Sending messages and file attachments +- Sending messages and file attachments - Using the `DMMessagingInterface` component - Building custom messaging UIs - Protocol comparison (NIP-04 vs NIP-17) @@ -832,16 +832,46 @@ export function Post(/* ...props */) { ## App Configuration -The project includes an `AppProvider` that manages global application state including theme and relay configuration. The default configuration includes: +The project includes an `AppProvider` that manages global application state including theme and NIP-65 relay configuration. The default configuration includes: ```typescript const defaultConfig: AppConfig = { theme: "light", - relayUrl: "wss://relay.nostr.band", + relayMetadata: { + relays: [ + { url: 'wss://relay.ditto.pub', read: true, write: true }, + { url: 'wss://relay.nostr.band', read: true, write: true }, + { url: 'wss://relay.damus.io', read: true, write: true }, + ], + updatedAt: 0, + }, }; ``` -Preset relays are available including Ditto, Nostr.Band, Damus, and Primal. The app uses local storage to persist user preferences. +The app uses NIP-65 compatible relay management with automatic sync when users log in. Local storage persists user preferences and relay configurations. + +### Relay Management + +The project includes a complete NIP-65 relay management system: + +- **RelayListManager**: Component for managing multiple relays with read/write permissions +- **NostrSync**: Automatically syncs user's NIP-65 relay list when they log in +- **Automatic Publishing**: Changes to relay configuration are automatically published as NIP-65 events when the user is logged in + +Use the `RelayListManager` component to provide relay management interfaces: + +```tsx +import { RelayListManager } from '@/components/RelayListManager'; + +function SettingsPage() { + return ( +
+

Relay Settings

+ +
+ ); +} +``` ## Routing @@ -895,10 +925,9 @@ The router includes automatic scroll-to-top functionality and a 404 NotFound pag ### Empty States and No Content Found -When no content is found (empty search results, no data available, etc.), display a minimalist empty state with the `RelaySelector` component. This allows users to easily switch relays to discover content from different sources. +When no content is found (empty search results, no data available, etc.), display a minimalist empty state with helpful messaging. The application uses NIP-65 relay management, so users can manage their relays through the settings or relay management interface. ```tsx -import { RelaySelector } from '@/components/RelaySelector'; import { Card, CardContent } from '@/components/ui/card'; // Empty state example @@ -907,9 +936,8 @@ import { Card, CardContent } from '@/components/ui/card';

- No results found. Try another relay? + No results found. Try checking your relay connections or wait a moment for content to load.

-
diff --git a/src/App.tsx b/src/App.tsx index aa3be8d..8861bf2 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -6,6 +6,7 @@ import { createHead, UnheadProvider } from '@unhead/react/client'; import { InferSeoMetaPlugin } from '@unhead/addons'; import { Suspense } from 'react'; import NostrProvider from '@/components/NostrProvider'; +import { NostrSync } from '@/components/NostrSync'; import { Toaster } from "@/components/ui/toaster"; import { TooltipProvider } from "@/components/ui/tooltip"; import { NostrLoginProvider } from '@nostrify/react/login'; @@ -34,20 +35,20 @@ const queryClient = new QueryClient({ const defaultConfig: AppConfig = { theme: "light", - relayUrl: "wss://relay.ditto.pub", + relayMetadata: { + relays: [ + { url: 'wss://relay.ditto.pub', read: true, write: true }, + { url: 'wss://relay.nostr.band', read: true, write: true }, + { url: 'wss://relay.damus.io', read: true, write: true }, + ], + updatedAt: 0, + }, }; -const presetRelays = [ - { url: 'wss://relay.ditto.pub', name: 'Ditto' }, - { url: 'wss://relay.nostr.band', name: 'Nostr.Band' }, - { url: 'wss://relay.damus.io', name: 'Damus' }, - { url: 'wss://relay.primal.net', name: 'Primal' }, -]; - const dmConfig: DMConfig = { // Enable or disable DMs entirely enabled: true, // Set to false to completely disable messaging functionality - + // Choose one protocol mode: // PROTOCOL_MODE.NIP04_ONLY - Force NIP-04 (legacy) only // PROTOCOL_MODE.NIP17_ONLY - Force NIP-17 (private) only @@ -58,10 +59,11 @@ const dmConfig: DMConfig = { export function App() { return ( - + + diff --git a/src/components/AppProvider.tsx b/src/components/AppProvider.tsx index 5d927b6..8b72567 100644 --- a/src/components/AppProvider.tsx +++ b/src/components/AppProvider.tsx @@ -1,7 +1,7 @@ import { ReactNode, useEffect } from 'react'; import { z } from 'zod'; import { useLocalStorage } from '@/hooks/useLocalStorage'; -import { AppContext, type AppConfig, type AppContextType, type Theme } from '@/contexts/AppContext'; +import { AppContext, type AppConfig, type AppContextType, type Theme, type RelayMetadata } from '@/contexts/AppContext'; interface AppProviderProps { children: ReactNode; @@ -9,14 +9,22 @@ interface AppProviderProps { storageKey: string; /** Default app configuration */ defaultConfig: AppConfig; - /** Optional list of preset relays to display in the RelaySelector */ - presetRelays?: { name: string; url: string }[]; } +// Zod schema for RelayMetadata validation +const RelayMetadataSchema = z.object({ + relays: z.array(z.object({ + url: z.string().url(), + read: z.boolean(), + write: z.boolean(), + })), + updatedAt: z.number(), +}) satisfies z.ZodType; + // Zod schema for AppConfig validation const AppConfigSchema = z.object({ theme: z.enum(['dark', 'light', 'system']), - relayUrl: z.string().url(), + relayMetadata: RelayMetadataSchema, }) satisfies z.ZodType; export function AppProvider(props: AppProviderProps) { @@ -24,7 +32,6 @@ export function AppProvider(props: AppProviderProps) { children, storageKey, defaultConfig, - presetRelays, } = props; // App configuration state with localStorage persistence @@ -50,7 +57,6 @@ export function AppProvider(props: AppProviderProps) { const appContextValue: AppContextType = { config, updateConfig, - presetRelays, }; // Apply theme effects to document @@ -90,11 +96,11 @@ function useApplyTheme(theme: Theme) { if (theme !== 'system') return; const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)'); - + const handleChange = () => { const root = window.document.documentElement; root.classList.remove('light', 'dark'); - + const systemTheme = mediaQuery.matches ? 'dark' : 'light'; root.classList.add(systemTheme); }; diff --git a/src/components/DMProvider.tsx b/src/components/DMProvider.tsx index a312486..43710cb 100644 --- a/src/components/DMProvider.tsx +++ b/src/components/DMProvider.tsx @@ -137,7 +137,7 @@ interface DMProviderProps { */ 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; } @@ -176,10 +176,10 @@ export function DMProvider({ children, config }: DMProviderProps) { const { config: appConfig } = useAppContext(); const userPubkey = useMemo(() => user?.pubkey, [user?.pubkey]); - - // Track relay URL to detect changes - const previousRelayUrl = useRef(appConfig.relayUrl); - + + // Track relay metadata to detect changes + const previousRelayMetadata = useRef(appConfig.relayMetadata); + // Determine if NIP-17 is enabled based on protocol mode const enableNIP17 = protocolMode !== PROTOCOL_MODE.NIP04_ONLY; @@ -210,8 +210,8 @@ export function DMProvider({ children, config }: DMProviderProps) { // ============================================================================ // Send NIP-04 Message (internal) - const sendNIP4Message = useMutation({ @@ -254,8 +254,8 @@ export function DMProvider({ children, config }: DMProviderProps) { }); // Send NIP-17 Message (internal) - const sendNIP17Message = useMutation({ @@ -270,7 +270,7 @@ export function DMProvider({ children, config }: DMProviderProps) { // Step 1: Create the inner Kind 14 Private Direct Message const now = Math.floor(Date.now() / 1000); - + // Generate randomized timestamps for gift wraps (NIP-59 metadata privacy) // Randomize within ±2 days in the PAST only (relays reject future timestamps > +30min) const randomizeTimestamp = (baseTime: number) => { @@ -320,11 +320,11 @@ export function DMProvider({ children, config }: DMProviderProps) { // Step 3: Create TWO Kind 1059 Gift Wrap events // Per NIP-17/NIP-59: Gift wraps MUST be signed with random, ephemeral keys // to hide the sender's identity and provide - some - metadata privacy - + // Generate random secret keys for each gift wrap const recipientRandomKey = generateSecretKey(); const senderRandomKey = generateSecretKey(); - + // Create signers with the random keys const recipientRandomSigner = new NSecSigner(recipientRandomKey); const senderRandomSigner = new NSecSigner(senderRandomKey); @@ -357,15 +357,15 @@ export function DMProvider({ children, config }: DMProviderProps) { nostr.event(recipientGiftWrap), nostr.event(senderGiftWrap), ]); - + // Check for failures and log detailed errors const recipientResult = results[0]; const senderResult = results[1]; - + if (recipientResult.status === 'rejected') { console.error('[DM] Failed to publish recipient gift wrap'); console.error('[DM] Recipient gift wrap event:', recipientGiftWrap); - + // Try to extract detailed errors from AggregateError const error = recipientResult.reason; if (error && typeof error === 'object' && 'errors' in error) { @@ -374,11 +374,11 @@ export function DMProvider({ children, config }: DMProviderProps) { console.error('[DM] Recipient error:', error); } } - + if (senderResult.status === 'rejected') { console.error('[DM] Failed to publish sender gift wrap'); console.error('[DM] Sender gift wrap event:', senderGiftWrap); - + // Try to extract detailed errors from AggregateError const error = senderResult.reason; if (error && typeof error === 'object' && 'errors' in error) { @@ -387,7 +387,7 @@ export function DMProvider({ children, config }: DMProviderProps) { console.error('[DM] Sender error:', error); } } - + // If both failed, throw error if (recipientResult.status === 'rejected' && senderResult.status === 'rejected') { throw new Error(`Both gift wraps rejected. Recipient: ${recipientResult.reason}, Sender: ${senderResult.reason}`); @@ -478,7 +478,7 @@ export function DMProvider({ children, config }: DMProviderProps) { let allNIP17Events: NostrEvent[] = []; let processedMessages = 0; - + // Adjust since timestamp to account for NIP-17 timestamp fuzzing (±2 days) // We need to query from (lastSync - 2 days) to catch messages with randomized past timestamps // This may fetch duplicates, but they're filtered by message ID in addMessageToState @@ -713,7 +713,7 @@ export function DMProvider({ children, config }: DMProviderProps) { const existingMessageIds = new Set( existing.messages.map(msg => msg.originalGiftWrapId || msg.id) ); - const newMessages = value.messages.filter(msg => + const newMessages = value.messages.filter(msg => !existingMessageIds.has(msg.originalGiftWrapId || msg.id) ); @@ -1052,7 +1052,7 @@ export function DMProvider({ children, config }: DMProviderProps) { if (!sinceTimestamp && lastSync.nip17) { subscriptionSince = lastSync.nip17 - DM_CONSTANTS.SUBSCRIPTION_OVERLAP_SECONDS; } - + // Adjust for NIP-17 timestamp fuzzing (±2 days) // Subscribe from (lastSync - 2 days) to catch messages with randomized past timestamps const TWO_DAYS_IN_SECONDS = 2 * 24 * 60 * 60; @@ -1101,7 +1101,7 @@ export function DMProvider({ children, config }: DMProviderProps) { try { const { readMessagesFromDB } = await import('@/lib/dmMessageStore'); - + const cachedStore = await readMessagesFromDB(userPubkey); if (!cachedStore || Object.keys(cachedStore.participants).length === 0) { @@ -1122,13 +1122,13 @@ export function DMProvider({ children, config }: DMProviderProps) { // 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 + 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); @@ -1142,7 +1142,7 @@ export function DMProvider({ children, config }: DMProviderProps) { 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, @@ -1154,7 +1154,7 @@ export function DMProvider({ children, config }: DMProviderProps) { } } } - + return { ...msg, id: msg.id || `missing-${msg.kind}-${msg.created_at}-${msg.pubkey.substring(0, 8)}-${msg.content?.substring(0, 16) || 'nocontent'}`, @@ -1197,17 +1197,17 @@ export function DMProvider({ children, config }: DMProviderProps) { try { // ===== PHASE 1: Load cache and show immediately ===== const { nip4Since, nip17Since } = await loadAllCachedMessages(); - + // Mark as completed BEFORE releasing isLoading to prevent re-trigger setHasInitialLoadCompleted(true); - + // Show cached messages immediately! Don't wait for relays setLoadingPhase(LOADING_PHASES.READY); setIsLoading(false); // ===== PHASE 2: Query relays in background (non-blocking, parallel) ===== setLoadingPhase(LOADING_PHASES.RELAYS); - + // Run NIP-04 and NIP-17 queries IN PARALLEL const [nip4Result, nip17Result] = await Promise.all([ queryRelaysForMessagesSince(MESSAGE_PROTOCOL.NIP04, nip4Since), @@ -1261,7 +1261,7 @@ export function DMProvider({ children, config }: DMProviderProps) { setSubscriptions({ isNIP4Connected: false, isNIP17Connected: false }); setScanProgress({ nip4: null, nip17: null }); setLoadingPhase(LOADING_PHASES.IDLE); - + // Trigger reload by setting hasInitialLoadCompleted to false setHasInitialLoadCompleted(false); } catch (error) { @@ -1279,7 +1279,7 @@ export function DMProvider({ children, config }: DMProviderProps) { // Cleanup effect useEffect(() => { if (!enabled) return; - + return () => { if (nip4SubscriptionRef.current) { nip4SubscriptionRef.current.close(); @@ -1295,7 +1295,7 @@ export function DMProvider({ children, config }: DMProviderProps) { // Cleanup subscriptions useEffect(() => { if (!enabled) return; - + return () => { if (nip4SubscriptionRef.current) { nip4SubscriptionRef.current.close(); @@ -1312,14 +1312,14 @@ export function DMProvider({ children, config }: DMProviderProps) { // Detect relay changes and reload messages useEffect(() => { - const relayChanged = previousRelayUrl.current !== appConfig.relayUrl; - - previousRelayUrl.current = appConfig.relayUrl; - + const relayChanged = JSON.stringify(previousRelayMetadata.current) !== JSON.stringify(appConfig.relayMetadata); + + previousRelayMetadata.current = appConfig.relayMetadata; + if (relayChanged && enabled && userPubkey && hasInitialLoadCompleted) { clearCacheAndRefetch(); } - }, [enabled, userPubkey, appConfig.relayUrl, hasInitialLoadCompleted, clearCacheAndRefetch]); + }, [enabled, userPubkey, appConfig.relayMetadata, hasInitialLoadCompleted, clearCacheAndRefetch]); // Detect hard refresh shortcut (Ctrl+Shift+R / Cmd+Shift+R) to clear cache useEffect(() => { @@ -1461,14 +1461,14 @@ export function DMProvider({ children, config }: DMProviderProps) { }, [enabled, messages, shouldSaveImmediately, writeAllMessagesToStore, triggerDebouncedWrite]); // Send message - const sendMessage = useCallback(async (params: { - recipientPubkey: string; - content: string; + const sendMessage = useCallback(async (params: { + recipientPubkey: string; + content: string; protocol?: MessageProtocol; attachments?: FileAttachment[]; }) => { if (!enabled) return; - + const { recipientPubkey, content, protocol = MESSAGE_PROTOCOL.NIP04, attachments } = params; if (!userPubkey) return; diff --git a/src/components/NostrProvider.tsx b/src/components/NostrProvider.tsx index 5f94ef9..2b8a7ef 100644 --- a/src/components/NostrProvider.tsx +++ b/src/components/NostrProvider.tsx @@ -1,5 +1,5 @@ import React, { useEffect, useRef } from 'react'; -import { NostrEvent, NPool, NRelay1 } from '@nostrify/nostrify'; +import { NostrEvent, NostrFilter, NPool, NRelay1 } from '@nostrify/nostrify'; import { NostrContext } from '@nostrify/react'; import { useQueryClient } from '@tanstack/react-query'; import { useAppContext } from '@/hooks/useAppContext'; @@ -10,7 +10,7 @@ interface NostrProviderProps { const NostrProvider: React.FC = (props) => { const { children } = props; - const { config, presetRelays } = useAppContext(); + const { config } = useAppContext(); const queryClient = useQueryClient(); @@ -18,13 +18,13 @@ const NostrProvider: React.FC = (props) => { const pool = useRef(undefined); // Use refs so the pool always has the latest data - const relayUrl = useRef(config.relayUrl); + const relayMetadata = useRef(config.relayMetadata); - // Invalidate Nostr queries when relayUrl changes + // Invalidate Nostr queries when relay metadata changes useEffect(() => { - relayUrl.current = config.relayUrl; + relayMetadata.current = config.relayMetadata; queryClient.invalidateQueries({ queryKey: ['nostr'] }); - }, [config.relayUrl, queryClient]); + }, [config.relayMetadata, queryClient]); // Initialize NPool only once if (!pool.current) { @@ -32,21 +32,27 @@ const NostrProvider: React.FC = (props) => { open(url: string) { return new NRelay1(url); }, - reqRouter(filters) { - return new Map([[relayUrl.current, filters]]); + reqRouter(filters: NostrFilter[]) { + const routes = new Map(); + + // Route to all read relays + const readRelays = relayMetadata.current.relays + .filter(r => r.read) + .map(r => r.url); + + for (const url of readRelays) { + routes.set(url, filters); + } + + return routes; }, eventRouter(_event: NostrEvent) { - // Publish to the selected relay - const allRelays = new Set([relayUrl.current]); + // Get write relays from metadata + const writeRelays = relayMetadata.current.relays + .filter(r => r.write) + .map(r => r.url); - // Also publish to the preset relays, capped to 5 - for (const { url } of (presetRelays ?? [])) { - allRelays.add(url); - - if (allRelays.size >= 5) { - break; - } - } + const allRelays = new Set(writeRelays); return [...allRelays]; }, diff --git a/src/components/NostrSync.tsx b/src/components/NostrSync.tsx new file mode 100644 index 0000000..2ebf856 --- /dev/null +++ b/src/components/NostrSync.tsx @@ -0,0 +1,62 @@ +import { useEffect } from 'react'; +import { useNostr } from '@nostrify/react'; +import { useCurrentUser } from '@/hooks/useCurrentUser'; +import { useAppContext } from '@/hooks/useAppContext'; + +/** + * NostrSync - Syncs user's Nostr data + * + * This component runs globally to sync various Nostr data when the user logs in. + * Currently syncs: + * - NIP-65 relay list (kind 10002) + */ +export function NostrSync() { + const { nostr } = useNostr(); + const { user } = useCurrentUser(); + const { config, updateConfig } = useAppContext(); + + useEffect(() => { + if (!user) return; + + const syncRelaysFromNostr = async () => { + try { + const events = await nostr.query( + [{ kinds: [10002], authors: [user.pubkey], limit: 1 }], + { signal: AbortSignal.timeout(5000) } + ); + + if (events.length > 0) { + const event = events[0]; + + // Only update if the event is newer than our stored data + if (event.created_at > config.relayMetadata.updatedAt) { + const fetchedRelays = event.tags + .filter(([name]) => name === 'r') + .map(([_, url, marker]) => ({ + url, + read: !marker || marker === 'read', + write: !marker || marker === 'write', + })); + + if (fetchedRelays.length > 0) { + console.log('Syncing relay list from Nostr:', fetchedRelays); + updateConfig((current) => ({ + ...current, + relayMetadata: { + relays: fetchedRelays, + updatedAt: event.created_at, + }, + })); + } + } + } + } catch (error) { + console.error('Failed to sync relays from Nostr:', error); + } + }; + + syncRelaysFromNostr(); + }, [user, config.relayMetadata.updatedAt, nostr, updateConfig]); + + return null; +} \ No newline at end of file diff --git a/src/components/RelayListManager.tsx b/src/components/RelayListManager.tsx new file mode 100644 index 0000000..c6fbe0e --- /dev/null +++ b/src/components/RelayListManager.tsx @@ -0,0 +1,272 @@ +import { useState, useEffect } from 'react'; +import { Plus, X, Wifi } from 'lucide-react'; +import { Button } from '@/components/ui/button'; +import { Label } from '@/components/ui/label'; +import { Input } from '@/components/ui/input'; +import { Switch } from '@/components/ui/switch'; +import { useAppContext } from '@/hooks/useAppContext'; +import { useCurrentUser } from '@/hooks/useCurrentUser'; +import { useNostrPublish } from '@/hooks/useNostrPublish'; +import { useToast } from '@/hooks/useToast'; + +interface Relay { + url: string; + read: boolean; + write: boolean; +} + +export function RelayListManager() { + const { config, updateConfig } = useAppContext(); + const { user } = useCurrentUser(); + const { mutate: publishEvent } = useNostrPublish(); + const { toast } = useToast(); + + const [relays, setRelays] = useState(config.relayMetadata.relays); + const [newRelayUrl, setNewRelayUrl] = useState(''); + + // Sync local state with config when it changes (e.g., from NostrProvider sync) + useEffect(() => { + setRelays(config.relayMetadata.relays); + }, [config.relayMetadata.relays]); + + const normalizeRelayUrl = (url: string): string => { + url = url.trim(); + try { + return new URL(url).toString(); + } catch { + try { + return new URL(`wss://${url}`).toString(); + } catch { + return url; + } + } + }; + + const isValidRelayUrl = (url: string): boolean => { + const trimmed = url.trim(); + if (!trimmed) return false; + + const normalized = normalizeRelayUrl(trimmed); + try { + new URL(normalized); + return true; + } catch { + return false; + } + }; + + const handleAddRelay = () => { + if (!isValidRelayUrl(newRelayUrl)) { + toast({ + title: 'Invalid relay URL', + description: 'Please enter a valid relay URL (e.g., wss://relay.example.com)', + variant: 'destructive', + }); + return; + } + + const normalized = normalizeRelayUrl(newRelayUrl); + + if (relays.some(r => r.url === normalized)) { + toast({ + title: 'Relay already exists', + description: 'This relay is already in your list.', + variant: 'destructive', + }); + return; + } + + const newRelays = [...relays, { url: normalized, read: true, write: true }]; + setRelays(newRelays); + setNewRelayUrl(''); + + saveRelays(newRelays); + }; + + const handleRemoveRelay = (url: string) => { + const newRelays = relays.filter(r => r.url !== url); + setRelays(newRelays); + saveRelays(newRelays); + }; + + const handleToggleRead = (url: string) => { + const newRelays = relays.map(r => + r.url === url ? { ...r, read: !r.read } : r + ); + setRelays(newRelays); + saveRelays(newRelays); + }; + + const handleToggleWrite = (url: string) => { + const newRelays = relays.map(r => + r.url === url ? { ...r, write: !r.write } : r + ); + setRelays(newRelays); + saveRelays(newRelays); + }; + + const saveRelays = (newRelays: Relay[]) => { + const now = Math.floor(Date.now() / 1000); + + // Update local config + updateConfig((current) => ({ + ...current, + relayMetadata: { + relays: newRelays, + updatedAt: now, + }, + })); + + // Publish to Nostr if user is logged in + if (user) { + publishNIP65RelayList(newRelays); + } + }; + + const publishNIP65RelayList = (relayList: Relay[]) => { + const tags = relayList.map(relay => { + if (relay.read && relay.write) { + return ['r', relay.url]; + } else if (relay.read) { + return ['r', relay.url, 'read']; + } else if (relay.write) { + return ['r', relay.url, 'write']; + } + // If neither read nor write, don't include (shouldn't happen) + return null; + }).filter((tag): tag is string[] => tag !== null); + + publishEvent( + { + kind: 10002, + content: '', + tags, + }, + { + onSuccess: () => { + toast({ + title: 'Relay list published', + description: 'Your relay list has been published to Nostr.', + }); + }, + onError: (error) => { + console.error('Failed to publish relay list:', error); + toast({ + title: 'Failed to publish relay list', + description: 'There was an error publishing your relay list to Nostr.', + variant: 'destructive', + }); + }, + } + ); + }; + + const renderRelayUrl = (url: string): string => { + try { + const parsed = new URL(url); + if (parsed.protocol === 'wss:') { + if (parsed.pathname === '/') { + return parsed.host; + } else { + return parsed.host + parsed.pathname; + } + } else { + return parsed.href; + } + } catch { + return url; + } + } + + return ( +
+ {/* Relay List */} +
+ {relays.map((relay) => ( +
+ + + {renderRelayUrl(relay.url)} + + + {/* Read Switch */} +
+ + handleToggleRead(relay.url)} + className="data-[state=checked]:bg-green-500" + /> +
+ + {/* Write Switch */} +
+ + handleToggleWrite(relay.url)} + className="data-[state=checked]:bg-blue-500" + /> +
+ + {/* Remove Button */} + +
+ ))} +
+ + {/* Add Relay Form */} +
+
+ + setNewRelayUrl(e.target.value)} + onKeyDown={(e) => { + if (e.key === 'Enter') { + handleAddRelay(); + } + }} + /> +
+ +
+ + {!user && ( +

+ Log in to sync your relay list with Nostr +

+ )} +
+ ); +} \ No newline at end of file diff --git a/src/components/RelaySelector.tsx b/src/components/RelaySelector.tsx deleted file mode 100644 index afdd658..0000000 --- a/src/components/RelaySelector.tsx +++ /dev/null @@ -1,174 +0,0 @@ -import { Check, ChevronsUpDown, Wifi, Plus } from "lucide-react"; -import { cn } from "@/lib/utils"; -import { Button } from "@/components/ui/button"; -import { - Command, - CommandEmpty, - CommandGroup, - CommandInput, - CommandItem, - CommandList, -} from "@/components/ui/command"; -import { - Popover, - PopoverContent, - PopoverTrigger, -} from "@/components/ui/popover"; -import { useState } from "react"; -import { useAppContext } from "@/hooks/useAppContext"; - -interface RelaySelectorProps { - className?: string; -} - -export function RelaySelector(props: RelaySelectorProps) { - const { className } = props; - const { config, updateConfig, presetRelays = [] } = useAppContext(); - - const selectedRelay = config.relayUrl; - const setSelectedRelay = (relay: string) => { - updateConfig((current) => ({ ...current, relayUrl: relay })); - }; - - const [open, setOpen] = useState(false); - const [inputValue, setInputValue] = useState(""); - - const selectedOption = presetRelays.find((option) => option.url === selectedRelay); - - // Function to normalize relay URL by adding wss:// if no protocol is present - const normalizeRelayUrl = (url: string): string => { - const trimmed = url.trim(); - if (!trimmed) return trimmed; - - // Check if it already has a protocol - if (trimmed.includes('://')) { - return trimmed; - } - - // Add wss:// prefix - return `wss://${trimmed}`; - }; - - // Handle adding a custom relay - const handleAddCustomRelay = (url: string) => { - setSelectedRelay?.(normalizeRelayUrl(url)); - setOpen(false); - setInputValue(""); - }; - - // Check if input value looks like a valid relay URL - const isValidRelayInput = (value: string): boolean => { - const trimmed = value.trim(); - if (!trimmed) return false; - - // Basic validation - should contain at least a domain-like structure - const normalized = normalizeRelayUrl(trimmed); - try { - new URL(normalized); - return true; - } catch { - return false; - } - }; - - return ( - - - - - - - - - - {inputValue && isValidRelayInput(inputValue) ? ( - handleAddCustomRelay(inputValue)} - className="cursor-pointer" - > - -
- Add custom relay - - {normalizeRelayUrl(inputValue)} - -
-
- ) : ( -
- {inputValue ? "Invalid relay URL" : "No relay found."} -
- )} -
- - {presetRelays - .filter((option) => - !inputValue || - option.name.toLowerCase().includes(inputValue.toLowerCase()) || - option.url.toLowerCase().includes(inputValue.toLowerCase()) - ) - .map((option) => ( - { - setSelectedRelay(normalizeRelayUrl(currentValue)); - setOpen(false); - setInputValue(""); - }} - > - -
- {option.name} - {option.url} -
-
- ))} - {inputValue && isValidRelayInput(inputValue) && ( - handleAddCustomRelay(inputValue)} - className="cursor-pointer border-t" - > - -
- Add custom relay - - {normalizeRelayUrl(inputValue)} - -
-
- )} -
-
-
-
-
- ); -} \ No newline at end of file diff --git a/src/components/auth/AccountSwitcher.tsx b/src/components/auth/AccountSwitcher.tsx index 9b4783b..afc655d 100644 --- a/src/components/auth/AccountSwitcher.tsx +++ b/src/components/auth/AccountSwitcher.tsx @@ -10,7 +10,6 @@ import { DropdownMenuTrigger, } from '@/components/ui/dropdown-menu.tsx'; import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar.tsx'; -import { RelaySelector } from '@/components/RelaySelector'; import { WalletModal } from '@/components/WalletModal'; import { useLoggedInAccounts, type Account } from '@/hooks/useLoggedInAccounts'; import { genUserName } from '@/lib/genUserName'; @@ -43,9 +42,6 @@ export function AccountSwitcher({ onAddAccountClick }: AccountSwitcherProps) { -
Switch Relay
- -
Switch Account
{otherUsers.map((user) => ( ) => Partial) => void; - /** Optional list of preset relays to display in the RelaySelector */ - presetRelays?: { name: string; url: string }[]; } export const AppContext = createContext(undefined); diff --git a/src/hooks/useZaps.ts b/src/hooks/useZaps.ts index 1bfeb2b..ec16d45 100644 --- a/src/hooks/useZaps.ts +++ b/src/hooks/useZaps.ts @@ -205,7 +205,7 @@ export function useZaps( profile: actualTarget.pubkey, event: event, amount: zapAmount, - relays: [config.relayUrl], + relays: config.relayMetadata.relays.map(r => r.url), comment }); diff --git a/src/pages/Messages.tsx b/src/pages/Messages.tsx index 2ea2090..121cd08 100644 --- a/src/pages/Messages.tsx +++ b/src/pages/Messages.tsx @@ -1,6 +1,5 @@ import { useSeoMeta } from '@unhead/react'; import { DMMessagingInterface } from '@/components/dm/DMMessagingInterface'; -import { RelaySelector } from '@/components/RelaySelector'; const Messages = () => { useSeoMeta({ @@ -14,7 +13,6 @@ const Messages = () => { {/* Header */}

Messages

-
diff --git a/src/test/TestApp.tsx b/src/test/TestApp.tsx index d4edfdd..3b2d4b9 100644 --- a/src/test/TestApp.tsx +++ b/src/test/TestApp.tsx @@ -23,7 +23,12 @@ export function TestApp({ children }: TestAppProps) { const defaultConfig: AppConfig = { theme: 'light', - relayUrl: 'wss://relay.nostr.band', + relayMetadata: { + relays: [ + { url: 'wss://relay.nostr.band', read: true, write: true }, + ], + updatedAt: 0, + }, }; return (