mirror of
https://gitlab.com/soapbox-pub/mkstack.git
synced 2026-12-06 00:37:23 +00:00
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
This commit is contained in:
13 files changed
+478
-272
No files matched your search
@@ -756,7 +756,7 @@ The project includes a complete direct messaging system with real-time updates,
|
|||||||
|
|
||||||
For complete implementation guide including:
|
For complete implementation guide including:
|
||||||
- Setup and configuration
|
- Setup and configuration
|
||||||
- Sending messages and file attachments
|
- Sending messages and file attachments
|
||||||
- Using the `DMMessagingInterface` component
|
- Using the `DMMessagingInterface` component
|
||||||
- Building custom messaging UIs
|
- Building custom messaging UIs
|
||||||
- Protocol comparison (NIP-04 vs NIP-17)
|
- Protocol comparison (NIP-04 vs NIP-17)
|
||||||
@@ -832,16 +832,46 @@ export function Post(/* ...props */) {
|
|||||||
|
|
||||||
## App Configuration
|
## 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
|
```typescript
|
||||||
const defaultConfig: AppConfig = {
|
const defaultConfig: AppConfig = {
|
||||||
theme: "light",
|
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 (
|
||||||
|
<div>
|
||||||
|
<h2>Relay Settings</h2>
|
||||||
|
<RelayListManager />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
## Routing
|
## Routing
|
||||||
|
|
||||||
@@ -895,10 +925,9 @@ The router includes automatic scroll-to-top functionality and a 404 NotFound pag
|
|||||||
|
|
||||||
### Empty States and No Content Found
|
### 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
|
```tsx
|
||||||
import { RelaySelector } from '@/components/RelaySelector';
|
|
||||||
import { Card, CardContent } from '@/components/ui/card';
|
import { Card, CardContent } from '@/components/ui/card';
|
||||||
|
|
||||||
// Empty state example
|
// Empty state example
|
||||||
@@ -907,9 +936,8 @@ import { Card, CardContent } from '@/components/ui/card';
|
|||||||
<CardContent className="py-12 px-8 text-center">
|
<CardContent className="py-12 px-8 text-center">
|
||||||
<div className="max-w-sm mx-auto space-y-6">
|
<div className="max-w-sm mx-auto space-y-6">
|
||||||
<p className="text-muted-foreground">
|
<p className="text-muted-foreground">
|
||||||
No results found. Try another relay?
|
No results found. Try checking your relay connections or wait a moment for content to load.
|
||||||
</p>
|
</p>
|
||||||
<RelaySelector className="w-full" />
|
|
||||||
</div>
|
</div>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
|||||||
+12
-10
@@ -6,6 +6,7 @@ import { createHead, UnheadProvider } from '@unhead/react/client';
|
|||||||
import { InferSeoMetaPlugin } from '@unhead/addons';
|
import { InferSeoMetaPlugin } from '@unhead/addons';
|
||||||
import { Suspense } from 'react';
|
import { Suspense } from 'react';
|
||||||
import NostrProvider from '@/components/NostrProvider';
|
import NostrProvider from '@/components/NostrProvider';
|
||||||
|
import { NostrSync } from '@/components/NostrSync';
|
||||||
import { Toaster } from "@/components/ui/toaster";
|
import { Toaster } from "@/components/ui/toaster";
|
||||||
import { TooltipProvider } from "@/components/ui/tooltip";
|
import { TooltipProvider } from "@/components/ui/tooltip";
|
||||||
import { NostrLoginProvider } from '@nostrify/react/login';
|
import { NostrLoginProvider } from '@nostrify/react/login';
|
||||||
@@ -34,20 +35,20 @@ const queryClient = new QueryClient({
|
|||||||
|
|
||||||
const defaultConfig: AppConfig = {
|
const defaultConfig: AppConfig = {
|
||||||
theme: "light",
|
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 = {
|
const dmConfig: DMConfig = {
|
||||||
// Enable or disable DMs entirely
|
// Enable or disable DMs entirely
|
||||||
enabled: true, // Set to false to completely disable messaging functionality
|
enabled: true, // Set to false to completely disable messaging functionality
|
||||||
|
|
||||||
// Choose one protocol mode:
|
// Choose one protocol mode:
|
||||||
// PROTOCOL_MODE.NIP04_ONLY - Force NIP-04 (legacy) only
|
// PROTOCOL_MODE.NIP04_ONLY - Force NIP-04 (legacy) only
|
||||||
// PROTOCOL_MODE.NIP17_ONLY - Force NIP-17 (private) only
|
// PROTOCOL_MODE.NIP17_ONLY - Force NIP-17 (private) only
|
||||||
@@ -58,10 +59,11 @@ const dmConfig: DMConfig = {
|
|||||||
export function App() {
|
export function App() {
|
||||||
return (
|
return (
|
||||||
<UnheadProvider head={head}>
|
<UnheadProvider head={head}>
|
||||||
<AppProvider storageKey="nostr:app-config" defaultConfig={defaultConfig} presetRelays={presetRelays}>
|
<AppProvider storageKey="nostr:app-config" defaultConfig={defaultConfig}>
|
||||||
<QueryClientProvider client={queryClient}>
|
<QueryClientProvider client={queryClient}>
|
||||||
<NostrLoginProvider storageKey='nostr:login'>
|
<NostrLoginProvider storageKey='nostr:login'>
|
||||||
<NostrProvider>
|
<NostrProvider>
|
||||||
|
<NostrSync />
|
||||||
<NWCProvider>
|
<NWCProvider>
|
||||||
<DMProvider config={dmConfig}>
|
<DMProvider config={dmConfig}>
|
||||||
<TooltipProvider>
|
<TooltipProvider>
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { ReactNode, useEffect } from 'react';
|
import { ReactNode, useEffect } from 'react';
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
import { useLocalStorage } from '@/hooks/useLocalStorage';
|
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 {
|
interface AppProviderProps {
|
||||||
children: ReactNode;
|
children: ReactNode;
|
||||||
@@ -9,14 +9,22 @@ interface AppProviderProps {
|
|||||||
storageKey: string;
|
storageKey: string;
|
||||||
/** Default app configuration */
|
/** Default app configuration */
|
||||||
defaultConfig: AppConfig;
|
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<RelayMetadata>;
|
||||||
|
|
||||||
// Zod schema for AppConfig validation
|
// Zod schema for AppConfig validation
|
||||||
const AppConfigSchema = z.object({
|
const AppConfigSchema = z.object({
|
||||||
theme: z.enum(['dark', 'light', 'system']),
|
theme: z.enum(['dark', 'light', 'system']),
|
||||||
relayUrl: z.string().url(),
|
relayMetadata: RelayMetadataSchema,
|
||||||
}) satisfies z.ZodType<AppConfig>;
|
}) satisfies z.ZodType<AppConfig>;
|
||||||
|
|
||||||
export function AppProvider(props: AppProviderProps) {
|
export function AppProvider(props: AppProviderProps) {
|
||||||
@@ -24,7 +32,6 @@ export function AppProvider(props: AppProviderProps) {
|
|||||||
children,
|
children,
|
||||||
storageKey,
|
storageKey,
|
||||||
defaultConfig,
|
defaultConfig,
|
||||||
presetRelays,
|
|
||||||
} = props;
|
} = props;
|
||||||
|
|
||||||
// App configuration state with localStorage persistence
|
// App configuration state with localStorage persistence
|
||||||
@@ -50,7 +57,6 @@ export function AppProvider(props: AppProviderProps) {
|
|||||||
const appContextValue: AppContextType = {
|
const appContextValue: AppContextType = {
|
||||||
config,
|
config,
|
||||||
updateConfig,
|
updateConfig,
|
||||||
presetRelays,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// Apply theme effects to document
|
// Apply theme effects to document
|
||||||
@@ -90,11 +96,11 @@ function useApplyTheme(theme: Theme) {
|
|||||||
if (theme !== 'system') return;
|
if (theme !== 'system') return;
|
||||||
|
|
||||||
const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
|
const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
|
||||||
|
|
||||||
const handleChange = () => {
|
const handleChange = () => {
|
||||||
const root = window.document.documentElement;
|
const root = window.document.documentElement;
|
||||||
root.classList.remove('light', 'dark');
|
root.classList.remove('light', 'dark');
|
||||||
|
|
||||||
const systemTheme = mediaQuery.matches ? 'dark' : 'light';
|
const systemTheme = mediaQuery.matches ? 'dark' : 'light';
|
||||||
root.classList.add(systemTheme);
|
root.classList.add(systemTheme);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -137,7 +137,7 @@ interface DMProviderProps {
|
|||||||
*/
|
*/
|
||||||
function prepareMessageContent(content: string, attachments: FileAttachment[] = []): string {
|
function prepareMessageContent(content: string, attachments: FileAttachment[] = []): string {
|
||||||
if (attachments.length === 0) return content;
|
if (attachments.length === 0) return content;
|
||||||
|
|
||||||
const fileUrls = attachments.map(file => file.url).join('\n');
|
const fileUrls = attachments.map(file => file.url).join('\n');
|
||||||
return content ? `${content}\n\n${fileUrls}` : fileUrls;
|
return content ? `${content}\n\n${fileUrls}` : fileUrls;
|
||||||
}
|
}
|
||||||
@@ -176,10 +176,10 @@ export function DMProvider({ children, config }: DMProviderProps) {
|
|||||||
const { config: appConfig } = useAppContext();
|
const { config: appConfig } = useAppContext();
|
||||||
|
|
||||||
const userPubkey = useMemo(() => user?.pubkey, [user?.pubkey]);
|
const userPubkey = useMemo(() => user?.pubkey, [user?.pubkey]);
|
||||||
|
|
||||||
// Track relay URL to detect changes
|
// Track relay metadata to detect changes
|
||||||
const previousRelayUrl = useRef<string>(appConfig.relayUrl);
|
const previousRelayMetadata = useRef(appConfig.relayMetadata);
|
||||||
|
|
||||||
// Determine if NIP-17 is enabled based on protocol mode
|
// Determine if NIP-17 is enabled based on protocol mode
|
||||||
const enableNIP17 = protocolMode !== PROTOCOL_MODE.NIP04_ONLY;
|
const enableNIP17 = protocolMode !== PROTOCOL_MODE.NIP04_ONLY;
|
||||||
|
|
||||||
@@ -210,8 +210,8 @@ export function DMProvider({ children, config }: DMProviderProps) {
|
|||||||
// ============================================================================
|
// ============================================================================
|
||||||
|
|
||||||
// Send NIP-04 Message (internal)
|
// Send NIP-04 Message (internal)
|
||||||
const sendNIP4Message = useMutation<NostrEvent, Error, {
|
const sendNIP4Message = useMutation<NostrEvent, Error, {
|
||||||
recipientPubkey: string;
|
recipientPubkey: string;
|
||||||
content: string;
|
content: string;
|
||||||
attachments?: FileAttachment[];
|
attachments?: FileAttachment[];
|
||||||
}>({
|
}>({
|
||||||
@@ -254,8 +254,8 @@ export function DMProvider({ children, config }: DMProviderProps) {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// Send NIP-17 Message (internal)
|
// Send NIP-17 Message (internal)
|
||||||
const sendNIP17Message = useMutation<NostrEvent, Error, {
|
const sendNIP17Message = useMutation<NostrEvent, Error, {
|
||||||
recipientPubkey: string;
|
recipientPubkey: string;
|
||||||
content: string;
|
content: string;
|
||||||
attachments?: FileAttachment[];
|
attachments?: FileAttachment[];
|
||||||
}>({
|
}>({
|
||||||
@@ -270,7 +270,7 @@ export function DMProvider({ children, config }: DMProviderProps) {
|
|||||||
|
|
||||||
// Step 1: Create the inner Kind 14 Private Direct Message
|
// Step 1: Create the inner Kind 14 Private Direct Message
|
||||||
const now = Math.floor(Date.now() / 1000);
|
const now = Math.floor(Date.now() / 1000);
|
||||||
|
|
||||||
// Generate randomized timestamps for gift wraps (NIP-59 metadata privacy)
|
// Generate randomized timestamps for gift wraps (NIP-59 metadata privacy)
|
||||||
// Randomize within ±2 days in the PAST only (relays reject future timestamps > +30min)
|
// Randomize within ±2 days in the PAST only (relays reject future timestamps > +30min)
|
||||||
const randomizeTimestamp = (baseTime: number) => {
|
const randomizeTimestamp = (baseTime: number) => {
|
||||||
@@ -320,11 +320,11 @@ export function DMProvider({ children, config }: DMProviderProps) {
|
|||||||
// Step 3: Create TWO Kind 1059 Gift Wrap events
|
// Step 3: Create TWO Kind 1059 Gift Wrap events
|
||||||
// Per NIP-17/NIP-59: Gift wraps MUST be signed with random, ephemeral keys
|
// 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
|
// to hide the sender's identity and provide - some - metadata privacy
|
||||||
|
|
||||||
// Generate random secret keys for each gift wrap
|
// Generate random secret keys for each gift wrap
|
||||||
const recipientRandomKey = generateSecretKey();
|
const recipientRandomKey = generateSecretKey();
|
||||||
const senderRandomKey = generateSecretKey();
|
const senderRandomKey = generateSecretKey();
|
||||||
|
|
||||||
// Create signers with the random keys
|
// Create signers with the random keys
|
||||||
const recipientRandomSigner = new NSecSigner(recipientRandomKey);
|
const recipientRandomSigner = new NSecSigner(recipientRandomKey);
|
||||||
const senderRandomSigner = new NSecSigner(senderRandomKey);
|
const senderRandomSigner = new NSecSigner(senderRandomKey);
|
||||||
@@ -357,15 +357,15 @@ export function DMProvider({ children, config }: DMProviderProps) {
|
|||||||
nostr.event(recipientGiftWrap),
|
nostr.event(recipientGiftWrap),
|
||||||
nostr.event(senderGiftWrap),
|
nostr.event(senderGiftWrap),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
// Check for failures and log detailed errors
|
// Check for failures and log detailed errors
|
||||||
const recipientResult = results[0];
|
const recipientResult = results[0];
|
||||||
const senderResult = results[1];
|
const senderResult = results[1];
|
||||||
|
|
||||||
if (recipientResult.status === 'rejected') {
|
if (recipientResult.status === 'rejected') {
|
||||||
console.error('[DM] Failed to publish recipient gift wrap');
|
console.error('[DM] Failed to publish recipient gift wrap');
|
||||||
console.error('[DM] Recipient gift wrap event:', recipientGiftWrap);
|
console.error('[DM] Recipient gift wrap event:', recipientGiftWrap);
|
||||||
|
|
||||||
// Try to extract detailed errors from AggregateError
|
// Try to extract detailed errors from AggregateError
|
||||||
const error = recipientResult.reason;
|
const error = recipientResult.reason;
|
||||||
if (error && typeof error === 'object' && 'errors' in error) {
|
if (error && typeof error === 'object' && 'errors' in error) {
|
||||||
@@ -374,11 +374,11 @@ export function DMProvider({ children, config }: DMProviderProps) {
|
|||||||
console.error('[DM] Recipient error:', error);
|
console.error('[DM] Recipient error:', error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (senderResult.status === 'rejected') {
|
if (senderResult.status === 'rejected') {
|
||||||
console.error('[DM] Failed to publish sender gift wrap');
|
console.error('[DM] Failed to publish sender gift wrap');
|
||||||
console.error('[DM] Sender gift wrap event:', senderGiftWrap);
|
console.error('[DM] Sender gift wrap event:', senderGiftWrap);
|
||||||
|
|
||||||
// Try to extract detailed errors from AggregateError
|
// Try to extract detailed errors from AggregateError
|
||||||
const error = senderResult.reason;
|
const error = senderResult.reason;
|
||||||
if (error && typeof error === 'object' && 'errors' in error) {
|
if (error && typeof error === 'object' && 'errors' in error) {
|
||||||
@@ -387,7 +387,7 @@ export function DMProvider({ children, config }: DMProviderProps) {
|
|||||||
console.error('[DM] Sender error:', error);
|
console.error('[DM] Sender error:', error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// If both failed, throw error
|
// If both failed, throw error
|
||||||
if (recipientResult.status === 'rejected' && senderResult.status === 'rejected') {
|
if (recipientResult.status === 'rejected' && senderResult.status === 'rejected') {
|
||||||
throw new Error(`Both gift wraps rejected. Recipient: ${recipientResult.reason}, Sender: ${senderResult.reason}`);
|
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 allNIP17Events: NostrEvent[] = [];
|
||||||
let processedMessages = 0;
|
let processedMessages = 0;
|
||||||
|
|
||||||
// Adjust since timestamp to account for NIP-17 timestamp fuzzing (±2 days)
|
// 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
|
// 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
|
// 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(
|
const existingMessageIds = new Set(
|
||||||
existing.messages.map(msg => msg.originalGiftWrapId || msg.id)
|
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)
|
!existingMessageIds.has(msg.originalGiftWrapId || msg.id)
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -1052,7 +1052,7 @@ export function DMProvider({ children, config }: DMProviderProps) {
|
|||||||
if (!sinceTimestamp && lastSync.nip17) {
|
if (!sinceTimestamp && lastSync.nip17) {
|
||||||
subscriptionSince = lastSync.nip17 - DM_CONSTANTS.SUBSCRIPTION_OVERLAP_SECONDS;
|
subscriptionSince = lastSync.nip17 - DM_CONSTANTS.SUBSCRIPTION_OVERLAP_SECONDS;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Adjust for NIP-17 timestamp fuzzing (±2 days)
|
// Adjust for NIP-17 timestamp fuzzing (±2 days)
|
||||||
// Subscribe from (lastSync - 2 days) to catch messages with randomized past timestamps
|
// Subscribe from (lastSync - 2 days) to catch messages with randomized past timestamps
|
||||||
const TWO_DAYS_IN_SECONDS = 2 * 24 * 60 * 60;
|
const TWO_DAYS_IN_SECONDS = 2 * 24 * 60 * 60;
|
||||||
@@ -1101,7 +1101,7 @@ export function DMProvider({ children, config }: DMProviderProps) {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
const { readMessagesFromDB } = await import('@/lib/dmMessageStore');
|
const { readMessagesFromDB } = await import('@/lib/dmMessageStore');
|
||||||
|
|
||||||
const cachedStore = await readMessagesFromDB(userPubkey);
|
const cachedStore = await readMessagesFromDB(userPubkey);
|
||||||
|
|
||||||
if (!cachedStore || Object.keys(cachedStore.participants).length === 0) {
|
if (!cachedStore || Object.keys(cachedStore.participants).length === 0) {
|
||||||
@@ -1122,13 +1122,13 @@ export function DMProvider({ children, config }: DMProviderProps) {
|
|||||||
// Decrypt based on message kind
|
// Decrypt based on message kind
|
||||||
let decryptedContent: string | undefined;
|
let decryptedContent: string | undefined;
|
||||||
let error: string | undefined;
|
let error: string | undefined;
|
||||||
|
|
||||||
if (msg.kind === 4) {
|
if (msg.kind === 4) {
|
||||||
// NIP-04 message
|
// NIP-04 message
|
||||||
const otherPubkey = msg.pubkey === user?.pubkey
|
const otherPubkey = msg.pubkey === user?.pubkey
|
||||||
? msg.tags.find(([name]) => name === 'p')?.[1]
|
? msg.tags.find(([name]) => name === 'p')?.[1]
|
||||||
: msg.pubkey;
|
: msg.pubkey;
|
||||||
|
|
||||||
if (otherPubkey && user?.signer?.nip04) {
|
if (otherPubkey && user?.signer?.nip04) {
|
||||||
try {
|
try {
|
||||||
decryptedContent = await user.signer.nip04.decrypt(otherPubkey, msg.content);
|
decryptedContent = await user.signer.nip04.decrypt(otherPubkey, msg.content);
|
||||||
@@ -1142,7 +1142,7 @@ export function DMProvider({ children, config }: DMProviderProps) {
|
|||||||
try {
|
try {
|
||||||
const sealContent = await user.signer.nip44.decrypt(msg.pubkey, msg.content);
|
const sealContent = await user.signer.nip44.decrypt(msg.pubkey, msg.content);
|
||||||
const decryptedEvent = JSON.parse(sealContent) as NostrEvent;
|
const decryptedEvent = JSON.parse(sealContent) as NostrEvent;
|
||||||
|
|
||||||
// Keep seal structure but add decryptedEvent for access to inner fields
|
// Keep seal structure but add decryptedEvent for access to inner fields
|
||||||
return {
|
return {
|
||||||
...msg,
|
...msg,
|
||||||
@@ -1154,7 +1154,7 @@ export function DMProvider({ children, config }: DMProviderProps) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
...msg,
|
...msg,
|
||||||
id: msg.id || `missing-${msg.kind}-${msg.created_at}-${msg.pubkey.substring(0, 8)}-${msg.content?.substring(0, 16) || 'nocontent'}`,
|
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 {
|
try {
|
||||||
// ===== PHASE 1: Load cache and show immediately =====
|
// ===== PHASE 1: Load cache and show immediately =====
|
||||||
const { nip4Since, nip17Since } = await loadAllCachedMessages();
|
const { nip4Since, nip17Since } = await loadAllCachedMessages();
|
||||||
|
|
||||||
// Mark as completed BEFORE releasing isLoading to prevent re-trigger
|
// Mark as completed BEFORE releasing isLoading to prevent re-trigger
|
||||||
setHasInitialLoadCompleted(true);
|
setHasInitialLoadCompleted(true);
|
||||||
|
|
||||||
// Show cached messages immediately! Don't wait for relays
|
// Show cached messages immediately! Don't wait for relays
|
||||||
setLoadingPhase(LOADING_PHASES.READY);
|
setLoadingPhase(LOADING_PHASES.READY);
|
||||||
setIsLoading(false);
|
setIsLoading(false);
|
||||||
|
|
||||||
// ===== PHASE 2: Query relays in background (non-blocking, parallel) =====
|
// ===== PHASE 2: Query relays in background (non-blocking, parallel) =====
|
||||||
setLoadingPhase(LOADING_PHASES.RELAYS);
|
setLoadingPhase(LOADING_PHASES.RELAYS);
|
||||||
|
|
||||||
// Run NIP-04 and NIP-17 queries IN PARALLEL
|
// Run NIP-04 and NIP-17 queries IN PARALLEL
|
||||||
const [nip4Result, nip17Result] = await Promise.all([
|
const [nip4Result, nip17Result] = await Promise.all([
|
||||||
queryRelaysForMessagesSince(MESSAGE_PROTOCOL.NIP04, nip4Since),
|
queryRelaysForMessagesSince(MESSAGE_PROTOCOL.NIP04, nip4Since),
|
||||||
@@ -1261,7 +1261,7 @@ export function DMProvider({ children, config }: DMProviderProps) {
|
|||||||
setSubscriptions({ isNIP4Connected: false, isNIP17Connected: false });
|
setSubscriptions({ isNIP4Connected: false, isNIP17Connected: false });
|
||||||
setScanProgress({ nip4: null, nip17: null });
|
setScanProgress({ nip4: null, nip17: null });
|
||||||
setLoadingPhase(LOADING_PHASES.IDLE);
|
setLoadingPhase(LOADING_PHASES.IDLE);
|
||||||
|
|
||||||
// Trigger reload by setting hasInitialLoadCompleted to false
|
// Trigger reload by setting hasInitialLoadCompleted to false
|
||||||
setHasInitialLoadCompleted(false);
|
setHasInitialLoadCompleted(false);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -1279,7 +1279,7 @@ export function DMProvider({ children, config }: DMProviderProps) {
|
|||||||
// Cleanup effect
|
// Cleanup effect
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!enabled) return;
|
if (!enabled) return;
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
if (nip4SubscriptionRef.current) {
|
if (nip4SubscriptionRef.current) {
|
||||||
nip4SubscriptionRef.current.close();
|
nip4SubscriptionRef.current.close();
|
||||||
@@ -1295,7 +1295,7 @@ export function DMProvider({ children, config }: DMProviderProps) {
|
|||||||
// Cleanup subscriptions
|
// Cleanup subscriptions
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!enabled) return;
|
if (!enabled) return;
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
if (nip4SubscriptionRef.current) {
|
if (nip4SubscriptionRef.current) {
|
||||||
nip4SubscriptionRef.current.close();
|
nip4SubscriptionRef.current.close();
|
||||||
@@ -1312,14 +1312,14 @@ export function DMProvider({ children, config }: DMProviderProps) {
|
|||||||
|
|
||||||
// Detect relay changes and reload messages
|
// Detect relay changes and reload messages
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const relayChanged = previousRelayUrl.current !== appConfig.relayUrl;
|
const relayChanged = JSON.stringify(previousRelayMetadata.current) !== JSON.stringify(appConfig.relayMetadata);
|
||||||
|
|
||||||
previousRelayUrl.current = appConfig.relayUrl;
|
previousRelayMetadata.current = appConfig.relayMetadata;
|
||||||
|
|
||||||
if (relayChanged && enabled && userPubkey && hasInitialLoadCompleted) {
|
if (relayChanged && enabled && userPubkey && hasInitialLoadCompleted) {
|
||||||
clearCacheAndRefetch();
|
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
|
// Detect hard refresh shortcut (Ctrl+Shift+R / Cmd+Shift+R) to clear cache
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -1461,14 +1461,14 @@ export function DMProvider({ children, config }: DMProviderProps) {
|
|||||||
}, [enabled, messages, shouldSaveImmediately, writeAllMessagesToStore, triggerDebouncedWrite]);
|
}, [enabled, messages, shouldSaveImmediately, writeAllMessagesToStore, triggerDebouncedWrite]);
|
||||||
|
|
||||||
// Send message
|
// Send message
|
||||||
const sendMessage = useCallback(async (params: {
|
const sendMessage = useCallback(async (params: {
|
||||||
recipientPubkey: string;
|
recipientPubkey: string;
|
||||||
content: string;
|
content: string;
|
||||||
protocol?: MessageProtocol;
|
protocol?: MessageProtocol;
|
||||||
attachments?: FileAttachment[];
|
attachments?: FileAttachment[];
|
||||||
}) => {
|
}) => {
|
||||||
if (!enabled) return;
|
if (!enabled) return;
|
||||||
|
|
||||||
const { recipientPubkey, content, protocol = MESSAGE_PROTOCOL.NIP04, attachments } = params;
|
const { recipientPubkey, content, protocol = MESSAGE_PROTOCOL.NIP04, attachments } = params;
|
||||||
if (!userPubkey) return;
|
if (!userPubkey) return;
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import React, { useEffect, useRef } from 'react';
|
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 { NostrContext } from '@nostrify/react';
|
||||||
import { useQueryClient } from '@tanstack/react-query';
|
import { useQueryClient } from '@tanstack/react-query';
|
||||||
import { useAppContext } from '@/hooks/useAppContext';
|
import { useAppContext } from '@/hooks/useAppContext';
|
||||||
@@ -10,7 +10,7 @@ interface NostrProviderProps {
|
|||||||
|
|
||||||
const NostrProvider: React.FC<NostrProviderProps> = (props) => {
|
const NostrProvider: React.FC<NostrProviderProps> = (props) => {
|
||||||
const { children } = props;
|
const { children } = props;
|
||||||
const { config, presetRelays } = useAppContext();
|
const { config } = useAppContext();
|
||||||
|
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
@@ -18,13 +18,13 @@ const NostrProvider: React.FC<NostrProviderProps> = (props) => {
|
|||||||
const pool = useRef<NPool | undefined>(undefined);
|
const pool = useRef<NPool | undefined>(undefined);
|
||||||
|
|
||||||
// Use refs so the pool always has the latest data
|
// Use refs so the pool always has the latest data
|
||||||
const relayUrl = useRef<string>(config.relayUrl);
|
const relayMetadata = useRef(config.relayMetadata);
|
||||||
|
|
||||||
// Invalidate Nostr queries when relayUrl changes
|
// Invalidate Nostr queries when relay metadata changes
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
relayUrl.current = config.relayUrl;
|
relayMetadata.current = config.relayMetadata;
|
||||||
queryClient.invalidateQueries({ queryKey: ['nostr'] });
|
queryClient.invalidateQueries({ queryKey: ['nostr'] });
|
||||||
}, [config.relayUrl, queryClient]);
|
}, [config.relayMetadata, queryClient]);
|
||||||
|
|
||||||
// Initialize NPool only once
|
// Initialize NPool only once
|
||||||
if (!pool.current) {
|
if (!pool.current) {
|
||||||
@@ -32,21 +32,27 @@ const NostrProvider: React.FC<NostrProviderProps> = (props) => {
|
|||||||
open(url: string) {
|
open(url: string) {
|
||||||
return new NRelay1(url);
|
return new NRelay1(url);
|
||||||
},
|
},
|
||||||
reqRouter(filters) {
|
reqRouter(filters: NostrFilter[]) {
|
||||||
return new Map([[relayUrl.current, filters]]);
|
const routes = new Map<string, NostrFilter[]>();
|
||||||
|
|
||||||
|
// 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) {
|
eventRouter(_event: NostrEvent) {
|
||||||
// Publish to the selected relay
|
// Get write relays from metadata
|
||||||
const allRelays = new Set<string>([relayUrl.current]);
|
const writeRelays = relayMetadata.current.relays
|
||||||
|
.filter(r => r.write)
|
||||||
|
.map(r => r.url);
|
||||||
|
|
||||||
// Also publish to the preset relays, capped to 5
|
const allRelays = new Set<string>(writeRelays);
|
||||||
for (const { url } of (presetRelays ?? [])) {
|
|
||||||
allRelays.add(url);
|
|
||||||
|
|
||||||
if (allRelays.size >= 5) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return [...allRelays];
|
return [...allRelays];
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -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<Relay[]>(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 (
|
||||||
|
<div className="space-y-4">
|
||||||
|
{/* Relay List */}
|
||||||
|
<div className="space-y-2">
|
||||||
|
{relays.map((relay) => (
|
||||||
|
<div
|
||||||
|
key={relay.url}
|
||||||
|
className="flex items-center gap-3 p-3 rounded-md border bg-muted/20"
|
||||||
|
>
|
||||||
|
<Wifi className="h-4 w-4 text-muted-foreground shrink-0" />
|
||||||
|
<span className="font-mono text-sm flex-1 truncate" title={relay.url}>
|
||||||
|
{renderRelayUrl(relay.url)}
|
||||||
|
</span>
|
||||||
|
|
||||||
|
{/* Read Switch */}
|
||||||
|
<div className="flex items-center gap-2 shrink-0">
|
||||||
|
<Label htmlFor={`read-${relay.url}`} className="text-xs text-muted-foreground cursor-pointer">
|
||||||
|
Read
|
||||||
|
</Label>
|
||||||
|
<Switch
|
||||||
|
id={`read-${relay.url}`}
|
||||||
|
checked={relay.read}
|
||||||
|
onCheckedChange={() => handleToggleRead(relay.url)}
|
||||||
|
className="data-[state=checked]:bg-green-500"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Write Switch */}
|
||||||
|
<div className="flex items-center gap-2 shrink-0">
|
||||||
|
<Label htmlFor={`write-${relay.url}`} className="text-xs text-muted-foreground cursor-pointer">
|
||||||
|
Write
|
||||||
|
</Label>
|
||||||
|
<Switch
|
||||||
|
id={`write-${relay.url}`}
|
||||||
|
checked={relay.write}
|
||||||
|
onCheckedChange={() => handleToggleWrite(relay.url)}
|
||||||
|
className="data-[state=checked]:bg-blue-500"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Remove Button */}
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
onClick={() => handleRemoveRelay(relay.url)}
|
||||||
|
className="h-8 w-8 p-0 text-muted-foreground hover:text-destructive hover:bg-transparent shrink-0"
|
||||||
|
disabled={relays.length <= 1}
|
||||||
|
>
|
||||||
|
<X className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Add Relay Form */}
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<div className="flex-1">
|
||||||
|
<Label htmlFor="new-relay-url" className="sr-only">
|
||||||
|
Relay URL
|
||||||
|
</Label>
|
||||||
|
<Input
|
||||||
|
id="new-relay-url"
|
||||||
|
placeholder="Enter relay URL (e.g., wss://relay.example.com)"
|
||||||
|
value={newRelayUrl}
|
||||||
|
onChange={(e) => setNewRelayUrl(e.target.value)}
|
||||||
|
onKeyDown={(e) => {
|
||||||
|
if (e.key === 'Enter') {
|
||||||
|
handleAddRelay();
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<Button
|
||||||
|
onClick={handleAddRelay}
|
||||||
|
disabled={!newRelayUrl.trim()}
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
className="h-10 shrink-0"
|
||||||
|
>
|
||||||
|
<Plus className="h-4 w-4 mr-2" />
|
||||||
|
Add Relay
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{!user && (
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
Log in to sync your relay list with Nostr
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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 (
|
|
||||||
<Popover open={open} onOpenChange={setOpen}>
|
|
||||||
<PopoverTrigger asChild>
|
|
||||||
<Button
|
|
||||||
variant="outline"
|
|
||||||
role="combobox"
|
|
||||||
aria-expanded={open}
|
|
||||||
className={cn("justify-between", className)}
|
|
||||||
>
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<Wifi className="h-4 w-4" />
|
|
||||||
<span className="truncate">
|
|
||||||
{selectedOption
|
|
||||||
? selectedOption.name
|
|
||||||
: selectedRelay
|
|
||||||
? selectedRelay.replace(/^wss?:\/\//, '')
|
|
||||||
: "Select relay..."
|
|
||||||
}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
|
|
||||||
</Button>
|
|
||||||
</PopoverTrigger>
|
|
||||||
<PopoverContent className="w-[300px] p-0">
|
|
||||||
<Command>
|
|
||||||
<CommandInput
|
|
||||||
placeholder="Search relays or type URL..."
|
|
||||||
value={inputValue}
|
|
||||||
onValueChange={setInputValue}
|
|
||||||
/>
|
|
||||||
<CommandList>
|
|
||||||
<CommandEmpty>
|
|
||||||
{inputValue && isValidRelayInput(inputValue) ? (
|
|
||||||
<CommandItem
|
|
||||||
onSelect={() => handleAddCustomRelay(inputValue)}
|
|
||||||
className="cursor-pointer"
|
|
||||||
>
|
|
||||||
<Plus className="mr-2 h-4 w-4" />
|
|
||||||
<div className="flex flex-col">
|
|
||||||
<span className="font-medium">Add custom relay</span>
|
|
||||||
<span className="text-xs text-muted-foreground">
|
|
||||||
{normalizeRelayUrl(inputValue)}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</CommandItem>
|
|
||||||
) : (
|
|
||||||
<div className="py-6 text-center text-sm text-muted-foreground">
|
|
||||||
{inputValue ? "Invalid relay URL" : "No relay found."}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</CommandEmpty>
|
|
||||||
<CommandGroup>
|
|
||||||
{presetRelays
|
|
||||||
.filter((option) =>
|
|
||||||
!inputValue ||
|
|
||||||
option.name.toLowerCase().includes(inputValue.toLowerCase()) ||
|
|
||||||
option.url.toLowerCase().includes(inputValue.toLowerCase())
|
|
||||||
)
|
|
||||||
.map((option) => (
|
|
||||||
<CommandItem
|
|
||||||
key={option.url}
|
|
||||||
value={option.url}
|
|
||||||
onSelect={(currentValue) => {
|
|
||||||
setSelectedRelay(normalizeRelayUrl(currentValue));
|
|
||||||
setOpen(false);
|
|
||||||
setInputValue("");
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Check
|
|
||||||
className={cn(
|
|
||||||
"mr-2 h-4 w-4",
|
|
||||||
selectedRelay === option.url ? "opacity-100" : "opacity-0"
|
|
||||||
)}
|
|
||||||
/>
|
|
||||||
<div className="flex flex-col">
|
|
||||||
<span className="font-medium">{option.name}</span>
|
|
||||||
<span className="text-xs text-muted-foreground">{option.url}</span>
|
|
||||||
</div>
|
|
||||||
</CommandItem>
|
|
||||||
))}
|
|
||||||
{inputValue && isValidRelayInput(inputValue) && (
|
|
||||||
<CommandItem
|
|
||||||
onSelect={() => handleAddCustomRelay(inputValue)}
|
|
||||||
className="cursor-pointer border-t"
|
|
||||||
>
|
|
||||||
<Plus className="mr-2 h-4 w-4" />
|
|
||||||
<div className="flex flex-col">
|
|
||||||
<span className="font-medium">Add custom relay</span>
|
|
||||||
<span className="text-xs text-muted-foreground">
|
|
||||||
{normalizeRelayUrl(inputValue)}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</CommandItem>
|
|
||||||
)}
|
|
||||||
</CommandGroup>
|
|
||||||
</CommandList>
|
|
||||||
</Command>
|
|
||||||
</PopoverContent>
|
|
||||||
</Popover>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -10,7 +10,6 @@ import {
|
|||||||
DropdownMenuTrigger,
|
DropdownMenuTrigger,
|
||||||
} from '@/components/ui/dropdown-menu.tsx';
|
} from '@/components/ui/dropdown-menu.tsx';
|
||||||
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar.tsx';
|
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar.tsx';
|
||||||
import { RelaySelector } from '@/components/RelaySelector';
|
|
||||||
import { WalletModal } from '@/components/WalletModal';
|
import { WalletModal } from '@/components/WalletModal';
|
||||||
import { useLoggedInAccounts, type Account } from '@/hooks/useLoggedInAccounts';
|
import { useLoggedInAccounts, type Account } from '@/hooks/useLoggedInAccounts';
|
||||||
import { genUserName } from '@/lib/genUserName';
|
import { genUserName } from '@/lib/genUserName';
|
||||||
@@ -43,9 +42,6 @@ export function AccountSwitcher({ onAddAccountClick }: AccountSwitcherProps) {
|
|||||||
</button>
|
</button>
|
||||||
</DropdownMenuTrigger>
|
</DropdownMenuTrigger>
|
||||||
<DropdownMenuContent className='w-56 p-2 animate-scale-in'>
|
<DropdownMenuContent className='w-56 p-2 animate-scale-in'>
|
||||||
<div className='font-medium text-sm px-2 py-1.5'>Switch Relay</div>
|
|
||||||
<RelaySelector className="w-full" />
|
|
||||||
<DropdownMenuSeparator />
|
|
||||||
<div className='font-medium text-sm px-2 py-1.5'>Switch Account</div>
|
<div className='font-medium text-sm px-2 py-1.5'>Switch Account</div>
|
||||||
{otherUsers.map((user) => (
|
{otherUsers.map((user) => (
|
||||||
<DropdownMenuItem
|
<DropdownMenuItem
|
||||||
|
|||||||
@@ -2,11 +2,18 @@ import { createContext } from "react";
|
|||||||
|
|
||||||
export type Theme = "dark" | "light" | "system";
|
export type Theme = "dark" | "light" | "system";
|
||||||
|
|
||||||
|
export interface RelayMetadata {
|
||||||
|
/** List of relays with read/write permissions */
|
||||||
|
relays: { url: string; read: boolean; write: boolean }[];
|
||||||
|
/** Unix timestamp of when the relay list was last updated */
|
||||||
|
updatedAt: number;
|
||||||
|
}
|
||||||
|
|
||||||
export interface AppConfig {
|
export interface AppConfig {
|
||||||
/** Current theme */
|
/** Current theme */
|
||||||
theme: Theme;
|
theme: Theme;
|
||||||
/** Selected relay URL */
|
/** NIP-65 relay list metadata */
|
||||||
relayUrl: string;
|
relayMetadata: RelayMetadata;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface AppContextType {
|
export interface AppContextType {
|
||||||
@@ -14,8 +21,6 @@ export interface AppContextType {
|
|||||||
config: AppConfig;
|
config: AppConfig;
|
||||||
/** Update configuration using a callback that receives current config and returns new config */
|
/** Update configuration using a callback that receives current config and returns new config */
|
||||||
updateConfig: (updater: (currentConfig: Partial<AppConfig>) => Partial<AppConfig>) => void;
|
updateConfig: (updater: (currentConfig: Partial<AppConfig>) => Partial<AppConfig>) => void;
|
||||||
/** Optional list of preset relays to display in the RelaySelector */
|
|
||||||
presetRelays?: { name: string; url: string }[];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export const AppContext = createContext<AppContextType | undefined>(undefined);
|
export const AppContext = createContext<AppContextType | undefined>(undefined);
|
||||||
@@ -205,7 +205,7 @@ export function useZaps(
|
|||||||
profile: actualTarget.pubkey,
|
profile: actualTarget.pubkey,
|
||||||
event: event,
|
event: event,
|
||||||
amount: zapAmount,
|
amount: zapAmount,
|
||||||
relays: [config.relayUrl],
|
relays: config.relayMetadata.relays.map(r => r.url),
|
||||||
comment
|
comment
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
import { useSeoMeta } from '@unhead/react';
|
import { useSeoMeta } from '@unhead/react';
|
||||||
import { DMMessagingInterface } from '@/components/dm/DMMessagingInterface';
|
import { DMMessagingInterface } from '@/components/dm/DMMessagingInterface';
|
||||||
import { RelaySelector } from '@/components/RelaySelector';
|
|
||||||
|
|
||||||
const Messages = () => {
|
const Messages = () => {
|
||||||
useSeoMeta({
|
useSeoMeta({
|
||||||
@@ -14,7 +13,6 @@ const Messages = () => {
|
|||||||
{/* Header */}
|
{/* Header */}
|
||||||
<div className="flex items-center justify-between mb-4">
|
<div className="flex items-center justify-between mb-4">
|
||||||
<h1 className="text-2xl font-semibold">Messages</h1>
|
<h1 className="text-2xl font-semibold">Messages</h1>
|
||||||
<RelaySelector />
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<DMMessagingInterface className="flex-1" />
|
<DMMessagingInterface className="flex-1" />
|
||||||
|
|||||||
@@ -23,7 +23,12 @@ export function TestApp({ children }: TestAppProps) {
|
|||||||
|
|
||||||
const defaultConfig: AppConfig = {
|
const defaultConfig: AppConfig = {
|
||||||
theme: 'light',
|
theme: 'light',
|
||||||
relayUrl: 'wss://relay.nostr.band',
|
relayMetadata: {
|
||||||
|
relays: [
|
||||||
|
{ url: 'wss://relay.nostr.band', read: true, write: true },
|
||||||
|
],
|
||||||
|
updatedAt: 0,
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|||||||
Reference in new issue
Block a user