Author SHA1 Message Date
lemonknowsall 315989fc87 Update nostr-tools to ^2.21.0 and @getalby/sdk to ^7.0.0 2026-01-28 23:28:11 -08:00
Alex Gleason c1bd55108c Remove stray docs mentions from AGENTS.md 2026-01-24 21:21:09 -06:00
Alex Gleason 266e2c92d8 Replace docs with skills 2026-01-24 21:20:22 -06:00
Alex Gleason 8163f30011 You don't actually have to pass signal now 2026-01-24 00:02:15 -06:00
Alex Gleason b97db2ca77 Upgrade zod to v4 2026-01-23 23:59:13 -06:00
Alex Gleason cda1b903a9 Merge branch 'main' of gitlab.com:soapbox-pub/mkstack 2026-01-21 16:52:45 -06:00
Alex Gleason ead11c31fe Remove stack.json 2026-01-21 16:52:23 -06:00
Alex Gleason a9bbb5ab84 Merge branch 'remove-nostr-band-relay' into 'main'
Replace dead relay.nostr.band with relay.primal.net

See merge request soapbox-pub/mkstack!29
2026-01-21 20:32:10 +00:00
Derek Ross f87510bc3a Replace dead relay.nostr.band with relay.primal.net 2026-01-21 15:29:02 -05:00
Alex Gleason fc010f9b91 Add Nostr Security Model to AGENTS.md 2026-01-21 12:14:24 -06:00
Alex Gleason 20f9ea9069 npm audit fix 2026-01-17 19:19:05 -06:00
Alex Gleason fc4c4deded Upgrade Nostrify 2026-01-17 19:18:43 -06:00
Alex Gleason b3dac352a4 Remove deploy script 2026-01-11 22:21:47 -06:00
Alex Gleason e94f53f0e2 Add -z-10 isolate hint 2026-01-10 11:37:12 -06:00
Alex Gleason 74449cf0d7 Add opencode.json with Nostr MCP server 2026-01-09 16:27:49 -06:00
Alex Gleason e26ab6a433 Fix URL wrapping in NoteContent 2025-12-30 18:19:20 -06:00
Alex Gleason 816051f5ea Greatly simplify the login and signup dialogs 2025-12-30 17:53:32 -06:00
Alex Gleason 413aa93e4f Generate custom images liberally 2025-12-23 05:54:11 -06:00
Alex Gleason 6941aad2f5 Upgrade Nostrify 2025-12-22 13:28:39 -06:00
Alex Gleason 28aba4b3a4 Revert "Fix happy-dom vuln"
This reverts commit e5b3f249f8.
2025-12-21 04:11:11 -06:00
Alex Gleason e5b3f249f8 Fix happy-dom vuln 2025-12-21 02:28:15 -06:00
Alex Gleason 12e6465912 npm audit fix 2025-12-21 02:02:24 -06:00
Alex Gleason 722d138f35 Remove "Vibed with MKStack" 2025-12-02 20:26:37 -06:00
Alex Gleason 84a15aa077 Revert "Try adding cashu deps"
This reverts commit 6534c5fcea.
2025-11-20 11:14:14 -06:00
Alex Gleason 8c7b595d22 Revert "Use nutstack package.json and package-lock.json"
This reverts commit 0bf1e0e85e.
2025-11-20 11:14:07 -06:00
Alex Gleason 0bf1e0e85e Use nutstack package.json and package-lock.json 2025-11-19 18:47:04 -06:00
Alex Gleason 6534c5fcea Try adding cashu deps 2025-11-19 18:42:35 -06:00
Alex Gleason e4ee998500 Fix posting a comment not invalidating comment cache 2025-11-17 19:44:34 -06:00
Alex Gleason 000be63075 Don't redirect /assets/* in Netlify redirects file 2025-11-13 22:11:57 -06:00
Alex Gleason 5f14ac11fc Remove DM stuff from App.tsx, add instructions on how to add it in docs 2025-11-11 17:36:32 -06:00
Alex Gleason 0b7d86a16f Remove DMProvider from App.tsx and update DM documentation
- Removed DMProvider, DMConfig imports and configuration from App.tsx
- Updated docs/NOSTR_DIRECT_MESSAGES.md with setup instructions
- DM functionality now requires manual setup as documented
- Preserved all existing intentional test errors
2025-11-11 17:34:45 -06:00
Alex Gleason 8496cb99e5 Disable DM functionality by default 2025-11-11 17:31:46 -06:00
Alex Gleason 386d664a33 Merge branch 'main' of gitlab.com:soapbox-pub/mkstack 2025-11-10 17:49:28 -06:00
Alex Gleason 0a5e8fc9e0 Bully the robot to utilize git if it's available, and to always read files before writing to them 2025-11-10 17:45:42 -06:00
Alex Gleason 2ba510c54f Merge branch 'removeMessageRoute' into 'main'
Remove "/messages" route

See merge request soapbox-pub/mkstack!27
2025-11-07 12:19:29 +00:00
lemonknowsall eb0fd14e33 remove /messages route 2025-11-06 19:43:20 -08:00
Alex Gleason 0532d23b57 RelayListManager improved mobile support 2025-11-05 00:23:40 -06:00
Alex Gleason 8eddf49e61 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
2025-11-04 23:58:32 -06:00
Alex Gleason d7dee81b1c Split DM context up into multiple files 2025-11-04 23:33:58 -06:00
Alex Gleason fbafc52992 Stronger guidance to call the generate_kind tool 2025-11-03 22:33:18 -06:00
38 changed files with 1392 additions and 1373 deletions

No files matched your search

@@ -1,4 +1,9 @@
### AI Integration with Shakespeare API ---
name: ai-chat
description: Build AI-powered chat interfaces, implement streaming responses, or integrate with Shakespeare AI.
---
# AI Integration with Shakespeare API
Use the `useShakespeare` hook for AI chat completions with Nostr authentication. The API dynamically provides available models, so you should query them at runtime rather than hardcoding model names. Use the `useShakespeare` hook for AI chat completions with Nostr authentication. The API dynamically provides available models, so you should query them at runtime rather than hardcoding model names.
@@ -1,3 +1,8 @@
---
name: nostr-comments
description: Implement Nostr comment systems, add discussion features to posts/articles, or build community interaction features.
---
# Adding Nostr Comments Sections # Adding Nostr Comments Sections
The project includes a complete commenting system using NIP-22 (kind 1111) comments that can be added to any Nostr event or URL. The `CommentsSection` component provides a full-featured commenting interface with threaded replies, user authentication, and real-time updates. The project includes a complete commenting system using NIP-22 (kind 1111) comments that can be added to any Nostr event or URL. The `CommentsSection` component provides a full-featured commenting interface with threaded replies, user authentication, and real-time updates.
@@ -1,42 +1,81 @@
### Direct Messaging on Nostr ---
name: nostr-direct-messages
description: Implement Nostr direct messaging features, build chat interfaces, or work with encrypted peer-to-peer communication (NIP-04 and NIP-17).
---
This project includes a complete direct messaging system supporting both NIP-04 (legacy) and NIP-17 (modern, - more - private) encrypted messages with real-time subscriptions, optimistic updates, and a persistent - cache first - local storage. # Direct Messaging on Nostr
## Quick Start This project includes a complete direct messaging system supporting both NIP-04 (legacy) and NIP-17 (modern, more private) encrypted messages with real-time subscriptions, optimistic updates, and a persistent cache-first local storage.
### 1. Enable Direct Messaging **The DM system is not enabled by default** - follow the setup instructions below to add messaging functionality to your application.
The `DMProvider` is already added to your app, but **disabled by default**. To enable messaging, pass `enabled: true` in the config: ## Setup Instructions
### 1. Add DMProvider to Your App
First, add the `DMProvider` to your app's provider tree in `src/App.tsx`:
```tsx ```tsx
import { DMProvider } from '@/contexts/DMContext'; // Add these imports at the top of src/App.tsx
import { DMProvider, type DMConfig } from '@/components/DMProvider';
import { PROTOCOL_MODE } from '@/lib/dmConstants'; import { PROTOCOL_MODE } from '@/lib/dmConstants';
function App() { // Add this configuration before your App component
const dmConfig: DMConfig = {
// Enable or disable DMs entirely
enabled: true, // Set to true to enable messaging functionality
// Choose one protocol mode:
// PROTOCOL_MODE.NIP04_ONLY - Force NIP-04 (legacy) only
// PROTOCOL_MODE.NIP17_ONLY - Force NIP-17 (private) only
// PROTOCOL_MODE.NIP04_OR_NIP17 - Allow users to choose between NIP-04 and NIP-17 (defaults to NIP-17)
protocolMode: PROTOCOL_MODE.NIP17_ONLY, // Recommended for new apps
};
// Then wrap your app components with DMProvider:
export function App() {
return ( return (
<DMProvider config={{ <UnheadProvider head={head}>
enabled: true, // Enable the DM system <AppProvider storageKey="nostr:app-config" defaultConfig={defaultConfig}>
protocolMode: PROTOCOL_MODE.NIP17_ONLY <QueryClientProvider client={queryClient}>
}}> <NostrLoginProvider storageKey='nostr:login'>
{/* Your app components */} <NostrProvider>
</DMProvider> <NostrSync />
<DMProvider config={dmConfig}>
<TooltipProvider>
<Toaster />
<Suspense>
<AppRouter />
</Suspense>
</TooltipProvider>
</DMProvider>
</NostrProvider>
</NostrLoginProvider>
</QueryClientProvider>
</AppProvider>
</UnheadProvider>
); );
} }
``` ```
**Config Options:** ### 2. Configure DM Settings
The `DMConfig` object supports the following options:
- `enabled` (boolean, default: `false`) - Enable/disable entire DM system. When false, no messages are loaded, stored, or processed. - `enabled` (boolean, default: `false`) - Enable/disable entire DM system. When false, no messages are loaded, stored, or processed.
- `protocolMode` (ProtocolMode, default: `PROTOCOL_MODE.NIP17_ONLY`) - Which protocols to support: - `protocolMode` (ProtocolMode, default: `PROTOCOL_MODE.NIP17_ONLY`) - Which protocols to support:
- `PROTOCOL_MODE.NIP04_ONLY` - Legacy encryption only - `PROTOCOL_MODE.NIP04_ONLY` - Legacy encryption only
- `PROTOCOL_MODE.NIP17_ONLY` - Modern private messages (recommended) - `PROTOCOL_MODE.NIP17_ONLY` - Modern private messages (recommended)
- `PROTOCOL_MODE.BOTH` - Support both protocols (for backwards compatibility) - `PROTOCOL_MODE.NIP04_OR_NIP17` - Support both protocols (for backwards compatibility)
**Note**: The DM system uses domain-based IndexedDB naming (`nostr-dm-store-${hostname}`) to prevent conflicts between multiple apps on the same domain. **Note**: The DM system uses domain-based IndexedDB naming (`nostr-dm-store-${hostname}`) to prevent conflicts between multiple apps on the same domain.
### 2. Send Messages ## Quick Start
### 1. Send Messages
```tsx ```tsx
import { useDMContext } from '@/contexts/DMContext'; import { useDMContext } from '@/hooks/useDMContext';
import { MESSAGE_PROTOCOL } from '@/lib/dmConstants'; import { MESSAGE_PROTOCOL } from '@/lib/dmConstants';
function ComposeMessage({ recipientPubkey }: { recipientPubkey: string }) { function ComposeMessage({ recipientPubkey }: { recipientPubkey: string }) {
@@ -54,8 +93,8 @@ function ComposeMessage({ recipientPubkey }: { recipientPubkey: string }) {
return ( return (
<form onSubmit={(e) => { e.preventDefault(); handleSend(); }}> <form onSubmit={(e) => { e.preventDefault(); handleSend(); }}>
<textarea <textarea
value={content} value={content}
onChange={(e) => setContent(e.target.value)} onChange={(e) => setContent(e.target.value)}
placeholder="Type a message..." placeholder="Type a message..."
/> />
@@ -65,10 +104,10 @@ function ComposeMessage({ recipientPubkey }: { recipientPubkey: string }) {
} }
``` ```
### 3. Display Conversations ### 2. Display Conversations
```tsx ```tsx
import { useDMContext } from '@/contexts/DMContext'; import { useDMContext } from '@/hooks/useDMContext';
import { useAuthor } from '@/hooks/useAuthor'; import { useAuthor } from '@/hooks/useAuthor';
import { genUserName } from '@/lib/genUserName'; import { genUserName } from '@/lib/genUserName';
@@ -82,7 +121,7 @@ function ConversationList({ onSelectConversation }: { onSelectConversation: (pub
return ( return (
<div className="space-y-2"> <div className="space-y-2">
{conversations.map((conversation) => ( {conversations.map((conversation) => (
<ConversationItem <ConversationItem
key={conversation.pubkey} key={conversation.pubkey}
conversation={conversation} conversation={conversation}
onClick={() => onSelectConversation(conversation.pubkey)} onClick={() => onSelectConversation(conversation.pubkey)}
@@ -92,8 +131,8 @@ function ConversationList({ onSelectConversation }: { onSelectConversation: (pub
); );
} }
function ConversationItem({ conversation, onClick }: { function ConversationItem({ conversation, onClick }: {
conversation: ConversationSummary; conversation: ConversationSummary;
onClick: () => void; onClick: () => void;
}) { }) {
const author = useAuthor(conversation.pubkey); const author = useAuthor(conversation.pubkey);
@@ -119,10 +158,10 @@ function ConversationItem({ conversation, onClick }: {
} }
``` ```
### 4. Display Messages in a Conversation ### 3. Display Messages in a Conversation
```tsx ```tsx
import { useConversationMessages } from '@/contexts/DMContext'; import { useConversationMessages } from '@/hooks/useConversationMessages';
import { useCurrentUser } from '@/hooks/useCurrentUser'; import { useCurrentUser } from '@/hooks/useCurrentUser';
function MessageThread({ conversationPubkey }: { conversationPubkey: string }) { function MessageThread({ conversationPubkey }: { conversationPubkey: string }) {
@@ -136,12 +175,12 @@ function MessageThread({ conversationPubkey }: { conversationPubkey: string }) {
Load earlier messages Load earlier messages
</button> </button>
)} )}
{messages.map((message) => { {messages.map((message) => {
const isFromMe = message.pubkey === user?.pubkey; const isFromMe = message.pubkey === user?.pubkey;
return ( return (
<div <div
key={message.id} key={message.id}
className={cn( className={cn(
"flex", "flex",
@@ -201,9 +240,10 @@ It requires no props and works automatically when wrapped in `DMProvider`.
## Sending Files with Messages ## Sending Files with Messages
```tsx ```tsx
import { useDMContext, type FileAttachment } from '@/contexts/DMContext'; import { useDMContext } from '@/hooks/useDMContext';
import { useUploadFile } from '@/hooks/useUploadFile'; import { useUploadFile } from '@/hooks/useUploadFile';
import { MESSAGE_PROTOCOL } from '@/lib/dmConstants'; import { MESSAGE_PROTOCOL } from '@/lib/dmConstants';
import type { FileAttachment } from '@/contexts/DMContext';
function ComposeWithFiles({ recipientPubkey }: { recipientPubkey: string }) { function ComposeWithFiles({ recipientPubkey }: { recipientPubkey: string }) {
const { sendMessage } = useDMContext(); const { sendMessage } = useDMContext();
@@ -217,7 +257,7 @@ function ComposeWithFiles({ recipientPubkey }: { recipientPubkey: string }) {
// Upload file if one is selected // Upload file if one is selected
if (selectedFile) { if (selectedFile) {
const tags = await uploadFile(selectedFile); const tags = await uploadFile(selectedFile);
attachments = [{ attachments = [{
url: tags[0][1], // URL from first tag url: tags[0][1], // URL from first tag
mimeType: selectedFile.type, mimeType: selectedFile.type,
@@ -240,19 +280,19 @@ function ComposeWithFiles({ recipientPubkey }: { recipientPubkey: string }) {
return ( return (
<form onSubmit={(e) => { e.preventDefault(); handleSend(); }}> <form onSubmit={(e) => { e.preventDefault(); handleSend(); }}>
<textarea <textarea
value={content} value={content}
onChange={(e) => setContent(e.target.value)} onChange={(e) => setContent(e.target.value)}
placeholder="Type a message..." placeholder="Type a message..."
/> />
<input <input
type="file" type="file"
onChange={(e) => setSelectedFile(e.target.files?.[0] || null)} onChange={(e) => setSelectedFile(e.target.files?.[0] || null)}
/> />
{selectedFile && <div>Selected: {selectedFile.name}</div>} {selectedFile && <div>Selected: {selectedFile.name}</div>}
<button type="submit" disabled={isUploading}> <button type="submit" disabled={isUploading}>
{isUploading ? 'Uploading...' : 'Send'} {isUploading ? 'Uploading...' : 'Send'}
</button> </button>
@@ -321,7 +361,7 @@ if (scanProgress.nip17) {
### Clear Cache and Refresh ### Clear Cache and Refresh
```tsx ```tsx
import { useDMContext } from '@/contexts/DMContext'; import { useDMContext } from '@/hooks/useDMContext';
function SettingsButton() { function SettingsButton() {
const { clearCacheAndRefetch } = useDMContext(); const { clearCacheAndRefetch } = useDMContext();
@@ -1,4 +1,9 @@
### Infinite Scroll for Nostr Feeds ---
name: nostr-infinite-scroll
description: Build feed interfaces, implement pagination for Nostr events, or create social media-style infinite scroll experiences.
---
# Infinite Scroll for Nostr Feeds
For feed-like interfaces, implement infinite scroll using TanStack Query's `useInfiniteQuery` with Nostr's timestamp-based pagination: For feed-like interfaces, implement infinite scroll using TanStack Query's `useInfiniteQuery` with Nostr's timestamp-based pagination:
+157 -54
View File
@@ -15,7 +15,6 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3.
## Project Structure ## Project Structure
- `/docs/`: Specialized documentation for implementation patterns and features
- `/src/components/`: UI components including NostrProvider for Nostr integration - `/src/components/`: UI components including NostrProvider for Nostr integration
- `/src/components/ui/`: shadcn/ui components (48+ components available) - `/src/components/ui/`: shadcn/ui components (48+ components available)
- `/src/components/auth/`: Authentication-related components (LoginArea, LoginDialog, etc.) - `/src/components/auth/`: Authentication-related components (LoginArea, LoginDialog, etc.)
@@ -46,9 +45,11 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3.
- `useConversationMessages`: Hook exported from DMContext for paginated messages - `useConversationMessages`: Hook exported from DMContext for paginated messages
- `/src/test/`: Testing utilities including TestApp component - `/src/test/`: Testing utilities including TestApp component
- `/public/`: Static assets - `/public/`: Static assets
- `App.tsx`: Main app component with provider setup - `App.tsx`: Main app component with provider setup (**CRITICAL**: this file is **already configured** with `QueryClientProvider`, `NostrProvider`, `UnheadProvider` and other important providers - **read this file before making changes**. Changes are usually not necessary unless adding new providers. Changing this file may break the application)
- `AppRouter.tsx`: React Router configuration - `AppRouter.tsx`: React Router configuration
**CRITICAL**: Always read the files mentioned above before making changes, as they contain important setup and configuration for the application. Never directly write to these files without first reading their contents.
## UI Components ## UI Components
The project uses shadcn/ui components located in `@/components/ui`. These are unstyled, accessible components built with Radix UI and styled with Tailwind CSS. Available components include: The project uses shadcn/ui components located in `@/components/ui`. These are unstyled, accessible components built with Radix UI and styled with Tailwind CSS. Available components include:
@@ -102,18 +103,6 @@ The project uses shadcn/ui components located in `@/components/ui`. These are un
These components follow a consistent pattern using React's `forwardRef` and use the `cn()` utility for class name merging. Many are built on Radix UI primitives for accessibility and customized with Tailwind CSS. These components follow a consistent pattern using React's `forwardRef` and use the `cn()` utility for class name merging. Many are built on Radix UI primitives for accessibility and customized with Tailwind CSS.
## Documentation
The project includes a **`docs/`** directory containing specialized documentation for specific implementation tasks. You are encouraged to add new documentation files to help future development.
- **`docs/AI_CHAT.md`**: Read when building any AI-powered chat interfaces, implementing streaming responses, or integrating with the Shakespeare API.
- **`docs/NOSTR_COMMENTS.md`**: Read when implementing comment systems, adding discussion features to posts/articles, or building community interaction features.
- **`docs/NOSTR_INFINITE_SCROLL.md`**: Read when building feed interfaces, implementing pagination for Nostr events, or creating social media-style infinite scroll experiences.
- **`docs/NOSTR_DIRECT_MESSAGES.md`**: Read when implementing direct messaging features, building chat interfaces, or working with encrypted peer-to-peer communication (NIP-04 and NIP-17).
## System Prompt Management ## System Prompt Management
The AI assistant's behavior and knowledge is defined by the AGENTS.md file, which serves as the system prompt. To modify the assistant's instructions or add new project-specific guidelines: The AI assistant's behavior and knowledge is defined by the AGENTS.md file, which serves as the system prompt. To modify the assistant's instructions or add new project-specific guidelines:
@@ -121,10 +110,6 @@ The AI assistant's behavior and knowledge is defined by the AGENTS.md file, whic
1. Edit AGENTS.md directly 1. Edit AGENTS.md directly
2. The changes take effect in the next session 2. The changes take effect in the next session
## "Vibed with MKStack"
When building the site for the first time, include "Vibed with MKStack" somewhere in the UI, linked to this URL: https://soapbox.pub/mkstack
## Nostr Protocol Integration ## Nostr Protocol Integration
This project comes with custom hooks for querying and publishing events on the Nostr network. This project comes with custom hooks for querying and publishing events on the Nostr network.
@@ -158,6 +143,7 @@ When implementing features that could use existing NIPs, follow this decision fr
- No existing NIP covers the core functionality - No existing NIP covers the core functionality
- The data structure is fundamentally different from existing patterns - The data structure is fundamentally different from existing patterns
- The use case requires different storage characteristics (regular vs replaceable vs addressable) - The use case requires different storage characteristics (regular vs replaceable vs addressable)
- If you have a tool available to generate a kind, you **MUST** call the tool to generate a new kind rather than picking an arbitrary number
6. **Custom Kind Publishing**: When publishing events with custom generated kinds, always include a NIP-31 "alt" tag with a human-readable description of the event's purpose. 6. **Custom Kind Publishing**: When publishing events with custom generated kinds, always include a NIP-31 "alt" tag with a human-readable description of the event's purpose.
@@ -234,7 +220,7 @@ const events = await nostr.query([{
kinds: [1], kinds: [1],
'#t': ['farming'], '#t': ['farming'],
limit: 20 limit: 20
}], { signal }); }]);
``` ```
### Kind Ranges ### Kind Ranges
@@ -284,6 +270,104 @@ The file `NIP.md` is used by this project to define a custom Nostr protocol docu
Whenever new kinds are generated, the `NIP.md` file in the project must be created or updated to document the custom event schema. Whenever the schema of one of these custom events changes, `NIP.md` must also be updated accordingly. Whenever new kinds are generated, the `NIP.md` file in the project must be created or updated to document the custom event schema. Whenever the schema of one of these custom events changes, `NIP.md` must also be updated accordingly.
### Nostr Security Model
**CRITICAL**: Nostr is permissionless - **anyone can publish any event**. When implementing admin/moderation systems or any feature that should only trust specific users, you MUST filter queries by the `authors` field. Without author filtering, anyone can publish events claiming to be admin actions, moderator decisions, or trusted content.
#### Using the `authors` Filter
**Always filter by authors when querying:**
- **Admin/moderator actions** - MUST filter by trusted admin pubkeys
- **Addressable events (kinds 30000-39999)** - MUST include author to prevent anyone from publishing events with the same d-tag
- **Any privileged operations** - Filter by trusted pubkeys only
**✅ Secure - Filtering by trusted authors:**
```typescript
import { ADMIN_PUBKEYS } from '@/lib/admins';
// Query organizer appointments - ONLY accept events from admins
const events = await nostr.query([{
kinds: [30078],
authors: ADMIN_PUBKEYS, // CRITICAL: Only trust admin authors
'#d': ['pathos-organizers'],
limit: 1
}]);
```
**❌ INSECURE - No author filtering:**
```typescript
// DANGER: This accepts events from ANYONE who publishes kind 30078
// An attacker could appoint themselves as an organizer
const events = await nostr.query([{
kinds: [30078],
'#d': ['pathos-organizers'],
limit: 1
}]);
```
**Addressable Events Example:**
```typescript
// For addressable events, ALWAYS include the author in your filter
// This prevents attackers from publishing events with the same d-tag
const article = await nostr.query([{
kinds: [30023], // Long-form article
authors: [authorPubkey], // CRITICAL: Verify the author
'#d': ['my-article-slug'],
limit: 1
}]);
```
**URL Routing for Addressable/Replaceable Events:**
When creating URL paths for addressable or replaceable events, always include the author in the URL structure:
```typescript
// ❌ INSECURE: Missing author - anyone could publish an event with this d-tag
<Route path="/article/:slug" element={<Article />} />
// URL: /article/hello-world
// ✅ SECURE: Includes author - can safely filter by both author and d-tag
<Route path="/article/:npub/:slug" element={<Article />} />
// URL: /article/npub1abc.../hello-world
```
This ensures your route parameters provide both the author pubkey and the d-tag identifier needed to create a secure query filter.
**NIP-72 Community Moderation Example:**
When implementing moderated communities (NIP-72), you must query the community definition to get the moderator list, then filter approval events by those moderators:
```typescript
// Step 1: Query the community definition to get moderators
const communityEvents = await nostr.query([{
kinds: [34550],
authors: [communityOwnerPubkey], // CRITICAL: Only trust the community owner
'#d': [communityId],
limit: 1,
}]);
if (communityEvents.length === 0) return [];
// Step 2: Extract moderator pubkeys from p tags
const moderatorPubkeys = communityEvents[0].tags
.filter(([name, _, __, role]) => name === 'p' && role === 'moderator')
.map(([_, pubkey]) => pubkey);
// Step 3: Query approval events - ONLY from trusted moderators
const approvals = await nostr.query([{
kinds: [4550],
authors: moderatorPubkeys, // CRITICAL: Only accept approvals from moderators
'#a': [`34550:${communityOwnerPubkey}:${communityId}`],
limit: 100,
}]);
```
Without filtering approvals by the moderator list, anyone could publish kind 4550 events claiming to approve posts for the community.
#### When Author Filtering Is NOT Required
Author filtering is not needed for public user-generated content where anyone should be able to post (kind 1 notes, reactions, discovery queries, public feeds, etc.).
### The `useNostr` Hook ### The `useNostr` Hook
The `useNostr` hook returns an object containing a `nostr` property, with `.query()` and `.event()` methods for querying and publishing Nostr events respectively. The `useNostr` hook returns an object containing a `nostr` property, with `.query()` and `.event()` methods for querying and publishing Nostr events respectively.
@@ -316,7 +400,7 @@ function useSpecificRelay() {
const relay = nostr.relay('wss://relay.damus.io'); const relay = nostr.relay('wss://relay.damus.io');
// Query from this specific relay only // Query from this specific relay only
const events = await relay.query([{ kinds: [1], limit: 20 }], { signal }); const events = await relay.query([{ kinds: [1], limit: 20 }]);
// Publish to this specific relay only // Publish to this specific relay only
await relay.event({ kind: 1, content: 'Hello from specific relay!' }); await relay.event({ kind: 1, content: 'Hello from specific relay!' });
@@ -341,7 +425,7 @@ function useRelayGroup() {
]); ]);
// Query from all relays in the group // Query from all relays in the group
const events = await relayGroup.query([{ kinds: [1], limit: 20 }], { signal }); const events = await relayGroup.query([{ kinds: [1], limit: 20 }]);
// Publish to all relays in the group // Publish to all relays in the group
await relayGroup.event({ kind: 1, content: 'Hello from relay group!' }); await relayGroup.event({ kind: 1, content: 'Hello from relay group!' });
@@ -391,8 +475,7 @@ function usePosts() {
return useQuery({ return useQuery({
queryKey: ['posts'], queryKey: ['posts'],
queryFn: async (c) => { queryFn: async (c) => {
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(1500)]); const events = await nostr.query([{ kinds: [1], limit: 20 }]);
const events = await nostr.query([{ kinds: [1], limit: 20 }], { signal });
return events; // these events could be transformed into another format return events; // these events could be transformed into another format
}, },
}); });
@@ -412,7 +495,7 @@ const events = await nostr.query([
'#e': [eventId], '#e': [eventId],
limit: 150, limit: 150,
} }
], { signal }); ]);
// Separate by type in JavaScript // Separate by type in JavaScript
const notes = events.filter((e) => e.kind === 1); const notes = events.filter((e) => e.kind === 1);
@@ -424,9 +507,9 @@ const genericReposts = events.filter((e) => e.kind === 16);
```typescript ```typescript
// This creates unnecessary load and can trigger rate limiting // This creates unnecessary load and can trigger rate limiting
const [notes, reposts, genericReposts] = await Promise.all([ const [notes, reposts, genericReposts] = await Promise.all([
nostr.query([{ kinds: [1], '#e': [eventId] }], { signal }), nostr.query([{ kinds: [1], '#e': [eventId] }]),
nostr.query([{ kinds: [6], '#e': [eventId] }], { signal }), nostr.query([{ kinds: [6], '#e': [eventId] }]),
nostr.query([{ kinds: [16], '#e': [eventId] }], { signal }), nostr.query([{ kinds: [16], '#e': [eventId] }]),
]); ]);
``` ```
@@ -480,8 +563,7 @@ function useCalendarEvents() {
return useQuery({ return useQuery({
queryKey: ['calendar-events'], queryKey: ['calendar-events'],
queryFn: async (c) => { queryFn: async (c) => {
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(1500)]); const events = await nostr.query([{ kinds: [31922, 31923], limit: 20 }]);
const events = await nostr.query([{ kinds: [31922, 31923], limit: 20 }], { signal });
// Filter events through validator to ensure they meet NIP-52 requirements // Filter events through validator to ensure they meet NIP-52 requirements
return events.filter(validateCalendarEvent); return events.filter(validateCalendarEvent);
@@ -682,7 +764,6 @@ The base Nostr protocol uses hex string identifiers when filtering by event IDs
// ❌ Wrong: naddr is not decoded // ❌ Wrong: naddr is not decoded
const events = await nostr.query( const events = await nostr.query(
[{ ids: [naddr] }], [{ ids: [naddr] }],
{ signal }
); );
``` ```
@@ -710,7 +791,6 @@ const events = await nostr.query(
authors: [naddr.pubkey], authors: [naddr.pubkey],
'#d': [naddr.identifier], '#d': [naddr.identifier],
}], }],
{ signal }
); );
``` ```
@@ -749,20 +829,6 @@ function EditProfilePage() {
The `EditProfileForm` component displays just the form. It requires no props, and will "just work" automatically. The `EditProfileForm` component displays just the form. It requires no props, and will "just work" automatically.
### Direct Messaging (NIP-04 & NIP-17)
The project includes a complete direct messaging system with real-time updates, encrypted storage, and support for both NIP-04 (legacy) and NIP-17 (modern private messaging) protocols. **The system is disabled by default** - enable it by passing `enabled: true` in the `DMProvider` config.
For complete implementation guide including:
- Setup and configuration
- Sending messages and file attachments
- Using the `DMMessagingInterface` component
- Building custom messaging UIs
- Protocol comparison (NIP-04 vs NIP-17)
- Advanced features and architecture
See **`docs/NOSTR_DIRECT_MESSAGES.md`**
### Uploading Files on Nostr ### Uploading Files on Nostr
Use the `useUploadFile` hook to upload files. This hook uses Blossom servers for file storage and returns NIP-94 compatible tags. Use the `useUploadFile` hook to upload files. This hook uses Blossom servers for file storage and returns NIP-94 compatible tags.
@@ -831,16 +897,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.primal.net', 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
@@ -894,10 +990,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
@@ -906,9 +1001,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>
@@ -927,7 +1021,7 @@ import { Card, CardContent } from '@/components/ui/card';
- Achieve Apple-level refinement with meticulous attention to detail, ensuring designs evoke strong emotions (e.g., wonder, inspiration, energy) through color, motion, and composition - Achieve Apple-level refinement with meticulous attention to detail, ensuring designs evoke strong emotions (e.g., wonder, inspiration, energy) through color, motion, and composition
- Deliver fully functional interactive components with intuitive feedback states, ensuring every element has a clear purpose and enhances user engagement - Deliver fully functional interactive components with intuitive feedback states, ensuring every element has a clear purpose and enhances user engagement
- Use custom illustrations, 3D elements, or symbolic visuals instead of generic stock imagery to create a unique brand narrative; stock imagery, when required, must be sourced exclusively from Pexels (NEVER Unsplash) and align with the design’s emotional tone - **Generate custom images liberally** when image generation tools are available - this is ALWAYS preferred over stock photography for creating unique, brand-specific visuals that perfectly match the design intent
- Ensure designs feel alive and modern with dynamic elements like gradients, glows, or parallax effects, avoiding static or flat aesthetics - Ensure designs feel alive and modern with dynamic elements like gradients, glows, or parallax effects, avoiding static or flat aesthetics
- Before finalizing, ask: "Would this design make Apple or Stripe designers pause and take notice?" If not, iterate until it does - Before finalizing, ask: "Would this design make Apple or Stripe designers pause and take notice?" If not, iterate until it does
@@ -1026,12 +1120,14 @@ When users specify color schemes:
- Follow shadcn/ui patterns for component variants - Follow shadcn/ui patterns for component variants
- Implement responsive design with Tailwind breakpoints - Implement responsive design with Tailwind breakpoints
- Add hover and focus states for interactive elements - Add hover and focus states for interactive elements
- When using negative z-index (e.g., `-z-10`) for background images or decorative elements, **always add `isolate` to the parent container** to create a local stacking context. Without `isolate`, negative z-index pushes elements behind the page's background color, making them invisible.
## Writing Tests vs Running Tests ## Writing Tests vs Running Tests
There is an important distinction between **writing new tests** and **running existing tests**: There is an important distinction between **writing new tests** and **running existing tests**:
### Writing Tests (Creating New Test Files) ### Writing Tests (Creating New Test Files)
**Do not write tests** unless the user explicitly requests them in plain language. Writing unnecessary tests wastes significant time and money. Only create tests when: **Do not write tests** unless the user explicitly requests them in plain language. Writing unnecessary tests wastes significant time and money. Only create tests when:
1. **The user explicitly asks for tests** to be written in their message 1. **The user explicitly asks for tests** to be written in their message
@@ -1045,6 +1141,7 @@ There is an important distinction between **writing new tests** and **running ex
- Existing functionality needs verification - Existing functionality needs verification
### Running Tests (Executing the Test Suite) ### Running Tests (Executing the Test Suite)
**ALWAYS run the test script** after making any code changes. This is mandatory regardless of whether you wrote new tests or not. **ALWAYS run the test script** after making any code changes. This is mandatory regardless of whether you wrote new tests or not.
- **You must run the test script** to validate your changes - **You must run the test script** to validate your changes
@@ -1103,4 +1200,10 @@ Run available tools in this priority order:
- Fix any critical linting errors that would break functionality - Fix any critical linting errors that would break functionality
- Create a git commit when your changes are complete - Create a git commit when your changes are complete
The validation ensures code quality and catches errors before deployment, regardless of the development environment. The validation ensures code quality and catches errors before deployment, regardless of the development environment.
### Using Git
If git is available in your environment (through a `shell` tool, or other git-specific tools), you should utilize `git log` to understand project history. Use `git status` and `git diff` to check the status of your changes, and if you make a mistake use `git checkout` to restore files.
When your changes are complete and validated, create a git commit with a descriptive message summarizing your changes.
-1
View File
@@ -17,7 +17,6 @@ export default tseslint.config(
globals: globals.browser, globals: globals.browser,
}, },
linterOptions: { linterOptions: {
noInlineConfig: true, // Prevents all eslint-disable comments
reportUnusedDisableDirectives: "error", // Reports unused disable directives as errors reportUnusedDisableDirectives: "error", // Reports unused disable directives as errors
}, },
plugins: { plugins: {
+9
View File
@@ -0,0 +1,9 @@
{
"$schema": "https://opencode.ai/config.json",
"mcp": {
"nostr": {
"type": "local",
"command": ["npx", "-y", "@nostrbook/mcp@latest"]
}
}
}
+131 -105
View File
@@ -10,9 +10,9 @@
"dependencies": { "dependencies": {
"@fontsource-variable/inter": "^5.2.6", "@fontsource-variable/inter": "^5.2.6",
"@getalby/sdk": "^5.1.1", "@getalby/sdk": "^5.1.1",
"@hookform/resolvers": "^3.9.0", "@hookform/resolvers": "^5.2.2",
"@nostrify/nostrify": "^0.47.1", "@nostrify/nostrify": "^0.49.2",
"@nostrify/react": "^0.2.17", "@nostrify/react": "^0.2.24",
"@radix-ui/react-accordion": "^1.2.0", "@radix-ui/react-accordion": "^1.2.0",
"@radix-ui/react-alert-dialog": "^1.1.1", "@radix-ui/react-alert-dialog": "^1.1.1",
"@radix-ui/react-aspect-ratio": "^1.1.0", "@radix-ui/react-aspect-ratio": "^1.1.0",
@@ -57,7 +57,7 @@
"react": "^18.3.1", "react": "^18.3.1",
"react-day-picker": "^8.10.1", "react-day-picker": "^8.10.1",
"react-dom": "^18.3.1", "react-dom": "^18.3.1",
"react-hook-form": "^7.53.0", "react-hook-form": "^7.71.1",
"react-intersection-observer": "^9.16.0", "react-intersection-observer": "^9.16.0",
"react-resizable-panels": "^2.1.3", "react-resizable-panels": "^2.1.3",
"react-router-dom": "^6.26.2", "react-router-dom": "^6.26.2",
@@ -65,7 +65,7 @@
"tailwind-merge": "^2.5.2", "tailwind-merge": "^2.5.2",
"tailwindcss-animate": "^1.0.7", "tailwindcss-animate": "^1.0.7",
"vaul": "^0.9.3", "vaul": "^0.9.3",
"zod": "^3.25.71" "zod": "^4.3.6"
}, },
"devDependencies": { "devDependencies": {
"@eslint/js": "^9.9.0", "@eslint/js": "^9.9.0",
@@ -986,12 +986,15 @@
} }
}, },
"node_modules/@hookform/resolvers": { "node_modules/@hookform/resolvers": {
"version": "3.10.0", "version": "5.2.2",
"resolved": "https://registry.npmjs.org/@hookform/resolvers/-/resolvers-3.10.0.tgz", "resolved": "https://registry.npmjs.org/@hookform/resolvers/-/resolvers-5.2.2.tgz",
"integrity": "sha512-79Dv+3mDF7i+2ajj7SkypSKHhl1cbln1OGavqrsF7p6mbUv11xpqpacPsGDCTRvCSjEEIez2ef1NveSVL3b0Ag==", "integrity": "sha512-A/IxlMLShx3KjV/HeTcTfaMxdwy690+L/ZADoeaTltLx+CVuzkeVIPuybK3jrRfw7YZnmdKsVVHAlEPIAEUNlA==",
"license": "MIT", "license": "MIT",
"dependencies": {
"@standard-schema/utils": "^0.3.0"
},
"peerDependencies": { "peerDependencies": {
"react-hook-form": "^7.0.0" "react-hook-form": "^7.55.0"
} }
}, },
"node_modules/@html-eslint/eslint-plugin": { "node_modules/@html-eslint/eslint-plugin": {
@@ -1253,34 +1256,35 @@
} }
}, },
"node_modules/@nostrify/nostrify": { "node_modules/@nostrify/nostrify": {
"version": "0.47.1", "version": "0.49.2",
"resolved": "https://registry.npmjs.org/@nostrify/nostrify/-/nostrify-0.47.1.tgz", "resolved": "https://registry.npmjs.org/@nostrify/nostrify/-/nostrify-0.49.2.tgz",
"integrity": "sha512-8jdAeKIyyDK/UQN92WgrQn9+B067HYcjfW35TpIjNLAT9qYe+KYFHaC9O6PD+I1DvLHziJMxk4Q18Fu4fqOiAQ==", "integrity": "sha512-JMiGifc/XX4QhzFnmJVw00UjcOS295w/NYth9mJH0cbS0EqPQ/4HBn33P0DGW3iE5EAkk+n98cnwzYeIPtn9pQ==",
"dependencies": { "dependencies": {
"@nostrify/types": "0.36.7", "@nostrify/types": "0.36.9",
"@scure/base": "^1.2.6", "@scure/base": "^2.0.0",
"@std/encoding": "npm:@jsr/std__encoding@^0.224.1", "@smithy/util-base64": "^4.3.0",
"@smithy/util-hex-encoding": "^4.2.0",
"@types/node": "^24.1.0", "@types/node": "^24.1.0",
"lru-cache": "^10.2.0", "lru-cache": "^10.2.0",
"nostr-tools": "^2.13.0", "nostr-tools": "^2.13.0",
"websocket-ts": "^2.2.1", "websocket-ts": "^2.2.1",
"ws": "^8.18.3", "ws": "^8.18.3",
"zod": "^3.23.8" "zod": "^4.3.6"
} }
}, },
"node_modules/@nostrify/nostrify/node_modules/@scure/base": { "node_modules/@nostrify/nostrify/node_modules/@scure/base": {
"version": "1.2.6", "version": "2.0.0",
"resolved": "https://registry.npmjs.org/@scure/base/-/base-1.2.6.tgz", "resolved": "https://registry.npmjs.org/@scure/base/-/base-2.0.0.tgz",
"integrity": "sha512-g/nm5FgUa//MCj1gV09zTJTaM6KBAHqLN907YVQqf7zC49+DcO4B1so4ZX07Ef10Twr6nuqYEH9GEggFXA4Fmg==", "integrity": "sha512-3E1kpuZginKkek01ovG8krQ0Z44E3DHPjc5S2rjJw9lZn3KSQOs8S7wqikF/AH7iRanHypj85uGyxk0XAyC37w==",
"license": "MIT", "license": "MIT",
"funding": { "funding": {
"url": "https://paulmillr.com/funding/" "url": "https://paulmillr.com/funding/"
} }
}, },
"node_modules/@nostrify/nostrify/node_modules/@types/node": { "node_modules/@nostrify/nostrify/node_modules/@types/node": {
"version": "24.9.1", "version": "24.10.4",
"resolved": "https://registry.npmjs.org/@types/node/-/node-24.9.1.tgz", "resolved": "https://registry.npmjs.org/@types/node/-/node-24.10.4.tgz",
"integrity": "sha512-QoiaXANRkSXK6p0Duvt56W208du4P9Uye9hWLWgGMDTEoKPhuenzNcC4vGUmrNkiOKTlIrBoyNQYNpSwfEZXSg==", "integrity": "sha512-vnDVpYPMzs4wunl27jHrfmwojOGKya0xyM3sH+UE5iv5uPS6vX7UIoh6m+vQc5LGBq52HBKPIn/zcSZVzeDEZg==",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"undici-types": "~7.16.0" "undici-types": "~7.16.0"
@@ -1293,23 +1297,22 @@
"license": "MIT" "license": "MIT"
}, },
"node_modules/@nostrify/react": { "node_modules/@nostrify/react": {
"version": "0.2.17", "version": "0.2.24",
"resolved": "https://registry.npmjs.org/@nostrify/react/-/react-0.2.17.tgz", "resolved": "https://registry.npmjs.org/@nostrify/react/-/react-0.2.24.tgz",
"integrity": "sha512-IG6XPiNBe1nDFZ055EnWufxASPjgOZ2cE53Hjanj5xQQURwzA946yMhDDzaHmD9lvoBYjuijopmTiyFk2RObHQ==", "integrity": "sha512-LdB6UjNKZ/Xhz+jj8CRCcudHt4WNNVZMgJsiO+XAloqWE8oPRf1G2i1k6I/eF6buCJokKE1PFUTMlyieOpIXNQ==",
"dependencies": { "dependencies": {
"@nostrify/nostrify": "0.47.1", "@nostrify/nostrify": "0.49.2",
"@nostrify/types": "0.36.7", "@nostrify/types": "0.36.9",
"@tanstack/react-query": "^5.69.0", "@tanstack/react-query": "^5.69.0",
"happy-dom": "^17.4.4",
"nostr-tools": "^2.13.0", "nostr-tools": "^2.13.0",
"react": "^18.0.0", "react": "^18.0.0",
"react-dom": "^18.0.0" "react-dom": "^18.0.0"
} }
}, },
"node_modules/@nostrify/types": { "node_modules/@nostrify/types": {
"version": "0.36.7", "version": "0.36.9",
"resolved": "https://registry.npmjs.org/@nostrify/types/-/types-0.36.7.tgz", "resolved": "https://registry.npmjs.org/@nostrify/types/-/types-0.36.9.tgz",
"integrity": "sha512-Jdf2eWdIzonMzic/st4ltre7XIcXVNTjmcbKpw4xGEfNmoq2Y4wj8KcSB6s0TUqxcLEyiXnyGP8EDx/gEVri9A==" "integrity": "sha512-tMx/r0W+QoVRRgs8d6ltaSgrftasOXuFsi33kW8WirswCy2b3UR1tqRgc0iBU9zRa9XR0nlej/wJZW+6wUFi+Q=="
}, },
"node_modules/@pkgjs/parseargs": { "node_modules/@pkgjs/parseargs": {
"version": "0.11.0", "version": "0.11.0",
@@ -2676,9 +2679,9 @@
"license": "MIT" "license": "MIT"
}, },
"node_modules/@remix-run/router": { "node_modules/@remix-run/router": {
"version": "1.23.0", "version": "1.23.2",
"resolved": "https://registry.npmjs.org/@remix-run/router/-/router-1.23.0.tgz", "resolved": "https://registry.npmjs.org/@remix-run/router/-/router-1.23.2.tgz",
"integrity": "sha512-O3rHJzAQKamUz1fvE0Qaw0xSFqsA/yafi2iqeE0pvdFtCO1viYx8QL6f3Ln/aCCTLxs68SLf0KPM9eSeM8yBnA==", "integrity": "sha512-Ic6m2U/rMjTkhERIa/0ZtXJP17QUi2CbWE7cqx4J58M8aA3QTfW+2UlQ4psvTX9IO1RfNVhK3pcpdjej7L+t2w==",
"license": "MIT", "license": "MIT",
"engines": { "engines": {
"node": ">=14.0.0" "node": ">=14.0.0"
@@ -2731,7 +2734,6 @@
"cpu": [ "cpu": [
"arm" "arm"
], ],
"dev": true,
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
@@ -2745,7 +2747,6 @@
"cpu": [ "cpu": [
"arm64" "arm64"
], ],
"dev": true,
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
@@ -2759,7 +2760,6 @@
"cpu": [ "cpu": [
"arm64" "arm64"
], ],
"dev": true,
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
@@ -2773,7 +2773,6 @@
"cpu": [ "cpu": [
"x64" "x64"
], ],
"dev": true,
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
@@ -2787,7 +2786,6 @@
"cpu": [ "cpu": [
"arm64" "arm64"
], ],
"dev": true,
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
@@ -2801,7 +2799,6 @@
"cpu": [ "cpu": [
"x64" "x64"
], ],
"dev": true,
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
@@ -2815,7 +2812,6 @@
"cpu": [ "cpu": [
"arm" "arm"
], ],
"dev": true,
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
@@ -2829,7 +2825,6 @@
"cpu": [ "cpu": [
"arm" "arm"
], ],
"dev": true,
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
@@ -2843,7 +2838,6 @@
"cpu": [ "cpu": [
"arm64" "arm64"
], ],
"dev": true,
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
@@ -2857,7 +2851,6 @@
"cpu": [ "cpu": [
"arm64" "arm64"
], ],
"dev": true,
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
@@ -2871,7 +2864,6 @@
"cpu": [ "cpu": [
"loong64" "loong64"
], ],
"dev": true,
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
@@ -2885,7 +2877,6 @@
"cpu": [ "cpu": [
"ppc64" "ppc64"
], ],
"dev": true,
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
@@ -2899,7 +2890,6 @@
"cpu": [ "cpu": [
"riscv64" "riscv64"
], ],
"dev": true,
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
@@ -2913,7 +2903,6 @@
"cpu": [ "cpu": [
"riscv64" "riscv64"
], ],
"dev": true,
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
@@ -2927,7 +2916,6 @@
"cpu": [ "cpu": [
"s390x" "s390x"
], ],
"dev": true,
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
@@ -2941,7 +2929,6 @@
"cpu": [ "cpu": [
"x64" "x64"
], ],
"dev": true,
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
@@ -2955,7 +2942,6 @@
"cpu": [ "cpu": [
"x64" "x64"
], ],
"dev": true,
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
@@ -2969,7 +2955,6 @@
"cpu": [ "cpu": [
"arm64" "arm64"
], ],
"dev": true,
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
@@ -2983,7 +2968,6 @@
"cpu": [ "cpu": [
"ia32" "ia32"
], ],
"dev": true,
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
@@ -2997,7 +2981,6 @@
"cpu": [ "cpu": [
"x64" "x64"
], ],
"dev": true,
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
@@ -3055,11 +3038,75 @@
"url": "https://paulmillr.com/funding/" "url": "https://paulmillr.com/funding/"
} }
}, },
"node_modules/@std/encoding": { "node_modules/@smithy/is-array-buffer": {
"name": "@jsr/std__encoding", "version": "4.2.0",
"version": "0.224.3", "resolved": "https://registry.npmjs.org/@smithy/is-array-buffer/-/is-array-buffer-4.2.0.tgz",
"resolved": "https://npm.jsr.io/~/11/@jsr/std__encoding/0.224.3.tgz", "integrity": "sha512-DZZZBvC7sjcYh4MazJSGiWMI2L7E0oCiRHREDzIxi/M2LY79/21iXt6aPLHge82wi5LsuRF5A06Ds3+0mlh6CQ==",
"integrity": "sha512-zAuX2QV1zwJ5RSmrnDGVerAtN3pBXpYYNlGzhERW9AiQ1UJd2/xruyB3i5NdTWy2OK2pjETswOj+0+prYTPlxQ==" "license": "Apache-2.0",
"dependencies": {
"tslib": "^2.6.2"
},
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@smithy/util-base64": {
"version": "4.3.0",
"resolved": "https://registry.npmjs.org/@smithy/util-base64/-/util-base64-4.3.0.tgz",
"integrity": "sha512-GkXZ59JfyxsIwNTWFnjmFEI8kZpRNIBfxKjv09+nkAWPt/4aGaEWMM04m4sxgNVWkbt2MdSvE3KF/PfX4nFedQ==",
"license": "Apache-2.0",
"dependencies": {
"@smithy/util-buffer-from": "^4.2.0",
"@smithy/util-utf8": "^4.2.0",
"tslib": "^2.6.2"
},
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@smithy/util-buffer-from": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/@smithy/util-buffer-from/-/util-buffer-from-4.2.0.tgz",
"integrity": "sha512-kAY9hTKulTNevM2nlRtxAG2FQ3B2OR6QIrPY3zE5LqJy1oxzmgBGsHLWTcNhWXKchgA0WHW+mZkQrng/pgcCew==",
"license": "Apache-2.0",
"dependencies": {
"@smithy/is-array-buffer": "^4.2.0",
"tslib": "^2.6.2"
},
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@smithy/util-hex-encoding": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/@smithy/util-hex-encoding/-/util-hex-encoding-4.2.0.tgz",
"integrity": "sha512-CCQBwJIvXMLKxVbO88IukazJD9a4kQ9ZN7/UMGBjBcJYvatpWk+9g870El4cB8/EJxfe+k+y0GmR9CAzkF+Nbw==",
"license": "Apache-2.0",
"dependencies": {
"tslib": "^2.6.2"
},
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@smithy/util-utf8": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/@smithy/util-utf8/-/util-utf8-4.2.0.tgz",
"integrity": "sha512-zBPfuzoI8xyBtR2P6WQj63Rz8i3AmfAaJLuNG8dWsfvPe8lO4aCPYLn879mEgHndZH1zQ2oXmG8O1GGzzaoZiw==",
"license": "Apache-2.0",
"dependencies": {
"@smithy/util-buffer-from": "^4.2.0",
"tslib": "^2.6.2"
},
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@standard-schema/utils": {
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/@standard-schema/utils/-/utils-0.3.0.tgz",
"integrity": "sha512-e7Mew686owMaPJVNNLs55PUvgz371nKgwsc4vxE49zsODpJEnxgxRo2y/OKrqueavXgZNMDVj3DdHFlaSAeU8g==",
"license": "MIT"
}, },
"node_modules/@swc/core": { "node_modules/@swc/core": {
"version": "1.11.24", "version": "1.11.24",
@@ -5372,9 +5419,9 @@
} }
}, },
"node_modules/glob": { "node_modules/glob": {
"version": "10.4.5", "version": "10.5.0",
"resolved": "https://registry.npmjs.org/glob/-/glob-10.4.5.tgz", "resolved": "https://registry.npmjs.org/glob/-/glob-10.5.0.tgz",
"integrity": "sha512-7Bv8RF0k6xjo7d4A/PxYLbUCfb6c+Vpd2/mB2yRDlew7Jb5hEXiCD9ibfO7wpk8i4sevK6DFny9h7EYbM3/sHg==", "integrity": "sha512-DfXN8DfhJ7NH3Oe7cFmu3NCu1wKbkReJ8TorzSAFbSKrlNaQSKfIzqYqVY8zlbs2NLBbWpRiU52GX2PbaBVNkg==",
"license": "ISC", "license": "ISC",
"dependencies": { "dependencies": {
"foreground-child": "^3.1.0", "foreground-child": "^3.1.0",
@@ -5447,28 +5494,6 @@
"dev": true, "dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/happy-dom": {
"version": "17.6.3",
"resolved": "https://registry.npmjs.org/happy-dom/-/happy-dom-17.6.3.tgz",
"integrity": "sha512-UVIHeVhxmxedbWPCfgS55Jg2rDfwf2BCKeylcPSqazLz5w3Kri7Q4xdBJubsr/+VUzFLh0VjIvh13RaDA2/Xug==",
"license": "MIT",
"dependencies": {
"webidl-conversions": "^7.0.0",
"whatwg-mimetype": "^3.0.0"
},
"engines": {
"node": ">=20.0.0"
}
},
"node_modules/happy-dom/node_modules/whatwg-mimetype": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-3.0.0.tgz",
"integrity": "sha512-nt+N2dzIutVRxARx1nghPKGv1xHikU7HKdfafKkLNLindmPU/ch3U31NOCGGA/dmPcmb1VlofO0vnKAcsm0o/Q==",
"license": "MIT",
"engines": {
"node": ">=12"
}
},
"node_modules/has-flag": { "node_modules/has-flag": {
"version": "4.0.0", "version": "4.0.0",
"resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz",
@@ -5753,9 +5778,9 @@
"license": "MIT" "license": "MIT"
}, },
"node_modules/js-yaml": { "node_modules/js-yaml": {
"version": "4.1.0", "version": "4.1.1",
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz", "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.1.tgz",
"integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==", "integrity": "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
@@ -6704,9 +6729,9 @@
} }
}, },
"node_modules/react-hook-form": { "node_modules/react-hook-form": {
"version": "7.56.1", "version": "7.71.1",
"resolved": "https://registry.npmjs.org/react-hook-form/-/react-hook-form-7.56.1.tgz", "resolved": "https://registry.npmjs.org/react-hook-form/-/react-hook-form-7.71.1.tgz",
"integrity": "sha512-qWAVokhSpshhcEuQDSANHx3jiAEFzu2HAaaQIzi/r9FNPm1ioAvuJSD4EuZzWd7Al7nTRKcKPnBKO7sRn+zavQ==", "integrity": "sha512-9SUJKCGKo8HUSsCO+y0CtqkqI5nNuaDqTxyqPsZPqIwudpj4rCrAz/jZV+jn57bx5gtZKOh3neQu94DXMc+w5w==",
"license": "MIT", "license": "MIT",
"engines": { "engines": {
"node": ">=18.0.0" "node": ">=18.0.0"
@@ -6798,12 +6823,12 @@
} }
}, },
"node_modules/react-router": { "node_modules/react-router": {
"version": "6.30.0", "version": "6.30.3",
"resolved": "https://registry.npmjs.org/react-router/-/react-router-6.30.0.tgz", "resolved": "https://registry.npmjs.org/react-router/-/react-router-6.30.3.tgz",
"integrity": "sha512-D3X8FyH9nBcTSHGdEKurK7r8OYE1kKFn3d/CF+CoxbSHkxU7o37+Uh7eAHRXr6k2tSExXYO++07PeXJtA/dEhQ==", "integrity": "sha512-XRnlbKMTmktBkjCLE8/XcZFlnHvr2Ltdr1eJX4idL55/9BbORzyZEaIkBFDhFGCEWBBItsVrDxwx3gnisMitdw==",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@remix-run/router": "1.23.0" "@remix-run/router": "1.23.2"
}, },
"engines": { "engines": {
"node": ">=14.0.0" "node": ">=14.0.0"
@@ -6813,13 +6838,13 @@
} }
}, },
"node_modules/react-router-dom": { "node_modules/react-router-dom": {
"version": "6.30.0", "version": "6.30.3",
"resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-6.30.0.tgz", "resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-6.30.3.tgz",
"integrity": "sha512-x30B78HV5tFk8ex0ITwzC9TTZMua4jGyA9IUlH1JLQYQTFyxr/ZxwOJq7evg1JX1qGVUcvhsmQSKdPncQrjTgA==", "integrity": "sha512-pxPcv1AczD4vso7G4Z3TKcvlxK7g7TNt3/FNGMhfqyntocvYKj+GCatfigGDjbLozC4baguJ0ReCigoDJXb0ag==",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@remix-run/router": "1.23.0", "@remix-run/router": "1.23.2",
"react-router": "6.30.0" "react-router": "6.30.3"
}, },
"engines": { "engines": {
"node": ">=14.0.0" "node": ">=14.0.0"
@@ -7883,9 +7908,9 @@
} }
}, },
"node_modules/vite": { "node_modules/vite": {
"version": "6.3.5", "version": "6.4.1",
"resolved": "https://registry.npmjs.org/vite/-/vite-6.3.5.tgz", "resolved": "https://registry.npmjs.org/vite/-/vite-6.4.1.tgz",
"integrity": "sha512-cZn6NDFE7wdTpINgs++ZJ4N49W2vRp8LCKrn3Ob1kYNtOo21vfDoaV5GzBfLU4MovSAB8uNRm4jgzVQZ+mBzPQ==", "integrity": "sha512-+Oxm7q9hDoLMyJOYfUYBuHQo+dkAloi33apOPP56pzj+vsdJDzr+j1NISE5pyaAuKL4A3UD34qd0lx5+kfKp2g==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
@@ -8096,6 +8121,7 @@
"version": "7.0.0", "version": "7.0.0",
"resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz", "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz",
"integrity": "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==", "integrity": "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==",
"dev": true,
"license": "BSD-2-Clause", "license": "BSD-2-Clause",
"engines": { "engines": {
"node": ">=12" "node": ">=12"
@@ -8484,9 +8510,9 @@
} }
}, },
"node_modules/zod": { "node_modules/zod": {
"version": "3.25.71", "version": "4.3.6",
"resolved": "https://registry.npmjs.org/zod/-/zod-3.25.71.tgz", "resolved": "https://registry.npmjs.org/zod/-/zod-4.3.6.tgz",
"integrity": "sha512-BsBc/NPk7h8WsUWYWYL+BajcJPY8YhjelaWu2NMLuzgraKAz4Lb4/6K11g9jpuDetjMiqhZ6YaexFLOC0Ogi3Q==", "integrity": "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==",
"license": "MIT", "license": "MIT",
"funding": { "funding": {
"url": "https://github.com/sponsors/colinhacks" "url": "https://github.com/sponsors/colinhacks"
+8 -9
View File
@@ -6,15 +6,14 @@
"scripts": { "scripts": {
"dev": "npm i --silent && vite", "dev": "npm i --silent && vite",
"build": "npm i --silent && vite build -l error && cp dist/index.html dist/404.html && echo 'Project built successfully!'", "build": "npm i --silent && vite build -l error && cp dist/index.html dist/404.html && echo 'Project built successfully!'",
"test": "npm i --silent && tsc --noEmit && eslint && vitest run --reporter=dot --silent && vite build -l error && cp dist/index.html dist/404.html && echo 'All tests passed!'", "test": "npm i --silent && tsc --noEmit && eslint && vitest run --reporter=dot --silent && vite build -l error && cp dist/index.html dist/404.html && echo 'All tests passed!'"
"deploy": "npm run build && npx -y nostr-deploy-cli deploy --skip-setup"
}, },
"dependencies": { "dependencies": {
"@fontsource-variable/inter": "^5.2.6", "@fontsource-variable/inter": "^5.2.6",
"@getalby/sdk": "^5.1.1", "@getalby/sdk": "^7.0.0",
"@hookform/resolvers": "^3.9.0", "@hookform/resolvers": "^5.2.2",
"@nostrify/nostrify": "^0.47.1", "@nostrify/nostrify": "^0.49.2",
"@nostrify/react": "^0.2.17", "@nostrify/react": "^0.2.24",
"@radix-ui/react-accordion": "^1.2.0", "@radix-ui/react-accordion": "^1.2.0",
"@radix-ui/react-alert-dialog": "^1.1.1", "@radix-ui/react-alert-dialog": "^1.1.1",
"@radix-ui/react-aspect-ratio": "^1.1.0", "@radix-ui/react-aspect-ratio": "^1.1.0",
@@ -54,12 +53,12 @@
"idb": "^8.0.3", "idb": "^8.0.3",
"input-otp": "^1.2.4", "input-otp": "^1.2.4",
"lucide-react": "^0.462.0", "lucide-react": "^0.462.0",
"nostr-tools": "^2.13.0", "nostr-tools": "^2.21.0",
"qrcode": "^1.5.4", "qrcode": "^1.5.4",
"react": "^18.3.1", "react": "^18.3.1",
"react-day-picker": "^8.10.1", "react-day-picker": "^8.10.1",
"react-dom": "^18.3.1", "react-dom": "^18.3.1",
"react-hook-form": "^7.53.0", "react-hook-form": "^7.71.1",
"react-intersection-observer": "^9.16.0", "react-intersection-observer": "^9.16.0",
"react-resizable-panels": "^2.1.3", "react-resizable-panels": "^2.1.3",
"react-router-dom": "^6.26.2", "react-router-dom": "^6.26.2",
@@ -67,7 +66,7 @@
"tailwind-merge": "^2.5.2", "tailwind-merge": "^2.5.2",
"tailwindcss-animate": "^1.0.7", "tailwindcss-animate": "^1.0.7",
"vaul": "^0.9.3", "vaul": "^0.9.3",
"zod": "^3.25.71" "zod": "^4.3.6"
}, },
"devDependencies": { "devDependencies": {
"@eslint/js": "^9.9.0", "@eslint/js": "^9.9.0",
+2 -1
View File
@@ -1 +1,2 @@
/* /index.html 200 /assets/* /assets/:splat 200
/* /index.html 200
+17 -30
View File
@@ -6,14 +6,13 @@ 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';
import { AppProvider } from '@/components/AppProvider'; import { AppProvider } from '@/components/AppProvider';
import { NWCProvider } from '@/contexts/NWCContext'; import { NWCProvider } from '@/contexts/NWCContext';
import { DMProvider, type DMConfig } from '@/contexts/DMContext';
import { AppConfig } from '@/contexts/AppContext'; import { AppConfig } from '@/contexts/AppContext';
import { PROTOCOL_MODE } from '@/lib/dmConstants';
import AppRouter from './AppRouter'; import AppRouter from './AppRouter';
const head = createHead({ const head = createHead({
@@ -34,43 +33,31 @@ 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 },
const presetRelays = [ { url: 'wss://relay.nostr.band', read: true, write: true },
{ url: 'wss://relay.ditto.pub', name: 'Ditto' }, { url: 'wss://relay.damus.io', read: true, write: true },
{ url: 'wss://relay.nostr.band', name: 'Nostr.Band' }, ],
{ url: 'wss://relay.damus.io', name: 'Damus' }, updatedAt: 0,
{ 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
// PROTOCOL_MODE.NIP04_OR_NIP17 - Allow users to choose between NIP-04 and NIP-17 (defaults to NIP-17)
protocolMode: PROTOCOL_MODE.NIP04_OR_NIP17,
}; };
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}> <TooltipProvider>
<TooltipProvider> <Toaster />
<Toaster /> <Suspense>
<Suspense> <AppRouter />
<AppRouter /> </Suspense>
</Suspense> </TooltipProvider>
</TooltipProvider>
</DMProvider>
</NWCProvider> </NWCProvider>
</NostrProvider> </NostrProvider>
</NostrLoginProvider> </NostrLoginProvider>
-2
View File
@@ -2,7 +2,6 @@ import { BrowserRouter, Route, Routes } from "react-router-dom";
import { ScrollToTop } from "./components/ScrollToTop"; import { ScrollToTop } from "./components/ScrollToTop";
import Index from "./pages/Index"; import Index from "./pages/Index";
import Messages from "./pages/Messages";
import { NIP19Page } from "./pages/NIP19Page"; import { NIP19Page } from "./pages/NIP19Page";
import NotFound from "./pages/NotFound"; import NotFound from "./pages/NotFound";
@@ -12,7 +11,6 @@ export function AppRouter() {
<ScrollToTop /> <ScrollToTop />
<Routes> <Routes>
<Route path="/" element={<Index />} /> <Route path="/" element={<Index />} />
<Route path="/messages" element={<Messages />} />
{/* NIP-19 route for npub1, note1, naddr1, nevent1, nprofile1 */} {/* NIP-19 route for npub1, note1, naddr1, nevent1, nprofile1 */}
<Route path="/:nip19" element={<NIP19Page />} /> <Route path="/:nip19" element={<NIP19Page />} />
{/* ADD ALL CUSTOM ROUTES ABOVE THE CATCH-ALL "*" ROUTE */} {/* ADD ALL CUSTOM ROUTES ABOVE THE CATCH-ALL "*" ROUTE */}
+14 -8
View File
@@ -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.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);
}; };
@@ -1,4 +1,4 @@
import React, { createContext, useContext, useEffect, useState, ReactNode, useCallback, useMemo, useRef } from 'react'; import { useEffect, useState, ReactNode, useCallback, useMemo, useRef } from 'react';
import { useMutation } from '@tanstack/react-query'; import { useMutation } from '@tanstack/react-query';
import { useCurrentUser } from '@/hooks/useCurrentUser'; import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useNostr } from '@nostrify/react'; import { useNostr } from '@nostrify/react';
@@ -11,6 +11,7 @@ import { NSecSigner, type NostrEvent } from '@nostrify/nostrify';
import { generateSecretKey } from 'nostr-tools'; import { generateSecretKey } from 'nostr-tools';
import type { MessageProtocol } from '@/lib/dmConstants'; import type { MessageProtocol } from '@/lib/dmConstants';
import { MESSAGE_PROTOCOL } from '@/lib/dmConstants'; import { MESSAGE_PROTOCOL } from '@/lib/dmConstants';
import { DMContext, DMContextType, FileAttachment } from '@/contexts/DMContext';
// ============================================================================ // ============================================================================
// DM Types and Constants // DM Types and Constants
@@ -117,172 +118,6 @@ const createErrorLogger = (name: string) => {
const nip17ErrorLogger = createErrorLogger('NIP-17'); const nip17ErrorLogger = createErrorLogger('NIP-17');
/**
* Direct Messaging context interface providing access to all DM functionality.
*
* @property messages - Raw message state (Map of pubkey -> participant data)
* @property isLoading - True during initial load phases
* @property loadingPhase - Current loading phase (CACHE, RELAYS, SUBSCRIPTIONS, READY, IDLE)
* @property isDoingInitialLoad - True only during cache/relay loading (not subscriptions)
* @property lastSync - Unix timestamps of last successful sync for each protocol
* @property subscriptions - Connection status for real-time message subscriptions
* @property conversations - Array of conversation summaries sorted by last activity
* @property sendMessage - Send an encrypted direct message (NIP-04 or NIP-17)
* @property protocolMode - Current protocol mode (NIP04_ONLY, NIP17_ONLY, or BOTH)
* @property scanProgress - Progress info for large message history scans
* @property clearCacheAndRefetch - Clear IndexedDB cache and reload all messages from relays
*/
interface DMContextType {
messages: MessagesState;
isLoading: boolean;
loadingPhase: LoadingPhase;
isDoingInitialLoad: boolean;
lastSync: LastSyncData;
subscriptions: SubscriptionStatus;
conversations: ConversationSummary[];
sendMessage: (params: {
recipientPubkey: string;
content: string;
protocol?: MessageProtocol;
attachments?: FileAttachment[];
}) => Promise<void>;
protocolMode: ProtocolMode;
scanProgress: ScanProgressState;
clearCacheAndRefetch: () => Promise<void>;
}
const DMContext = createContext<DMContextType | null>(null);
/**
* Hook to access the direct messaging system.
*
* Provides access to conversations, message sending, loading states, and cache management.
* Must be used within a DMProvider.
*
* @example
* ```tsx
* import { useDMContext } from '@/contexts/DMContext';
* import { MESSAGE_PROTOCOL } from '@/lib/dmConstants';
*
* function MyComponent() {
* const { conversations, sendMessage, isLoading } = useDMContext();
*
* // Send a message
* await sendMessage({
* recipientPubkey: 'hex-pubkey',
* content: 'Hello!',
* protocol: MESSAGE_PROTOCOL.NIP17
* });
*
* // Display conversations
* return (
* <div>
* {isLoading ? 'Loading...' : conversations.map(c => (
* <div key={c.pubkey}>{c.lastMessage?.decryptedContent}</div>
* ))}
* </div>
* );
* }
* ```
*
* @returns DMContextType - The direct messaging context
* @throws Error if used outside DMProvider
*/
// eslint-disable-next-line react-refresh/only-export-components
export function useDMContext(): DMContextType {
const context = useContext(DMContext);
if (!context) {
throw new Error('useDMContext must be used within DMProvider');
}
return context;
}
const MESSAGES_PER_PAGE = 25;
/**
* Hook to access paginated messages for a specific conversation.
*
* Returns the most recent messages (default 25) with the ability to load earlier messages.
* Automatically resets to default page size when switching conversations.
*
* @example
* ```tsx
* import { useConversationMessages } from '@/contexts/DMContext';
*
* function MessageThread({ recipientPubkey }: { recipientPubkey: string }) {
* const {
* messages,
* hasMoreMessages,
* loadEarlierMessages,
* totalCount
* } = useConversationMessages(recipientPubkey);
*
* return (
* <div>
* {hasMoreMessages && (
* <button onClick={loadEarlierMessages}>
* Load Earlier ({totalCount - messages.length} more)
* </button>
* )}
* {messages.map(msg => (
* <div key={msg.id}>{msg.decryptedContent}</div>
* ))}
* </div>
* );
* }
* ```
*
* @param conversationId - The pubkey of the conversation participant
* @returns Paginated message data with loading function
*/
// eslint-disable-next-line react-refresh/only-export-components
export function useConversationMessages(conversationId: string) {
const { messages: allMessages } = useDMContext();
const [visibleCount, setVisibleCount] = useState(MESSAGES_PER_PAGE);
const result = useMemo(() => {
const conversationData = allMessages.get(conversationId);
if (!conversationData) {
return {
messages: [],
hasMoreMessages: false,
totalCount: 0,
lastMessage: null,
lastActivity: 0,
};
}
const totalMessages = conversationData.messages.length;
const hasMore = totalMessages > visibleCount;
// Return the most recent N messages (slice from the end)
const visibleMessages = conversationData.messages.slice(-visibleCount);
return {
messages: visibleMessages,
hasMoreMessages: hasMore,
totalCount: totalMessages,
lastMessage: conversationData.lastMessage,
lastActivity: conversationData.lastActivity,
};
}, [allMessages, conversationId, visibleCount]);
const loadEarlierMessages = useCallback(() => {
setVisibleCount(prev => prev + MESSAGES_PER_PAGE);
}, []);
// Reset visible count when conversation changes
useEffect(() => {
setVisibleCount(MESSAGES_PER_PAGE);
}, [conversationId]);
return {
...result,
loadEarlierMessages,
};
}
export interface DMConfig { export interface DMConfig {
enabled?: boolean; enabled?: boolean;
protocolMode?: ProtocolMode; protocolMode?: ProtocolMode;
@@ -297,55 +132,12 @@ interface DMProviderProps {
// Message Sending Types and Helpers (Internal) // Message Sending Types and Helpers (Internal)
// ============================================================================ // ============================================================================
/**
* File attachment for direct messages (NIP-92 compatible).
*
* All fields are required. Use with `useUploadFile` hook to upload files
* and generate the proper tags format.
*
* @example
* ```tsx
* import { useUploadFile } from '@/hooks/useUploadFile';
* import type { FileAttachment } from '@/contexts/DMContext';
*
* const { mutateAsync: uploadFile } = useUploadFile();
*
* const tags = await uploadFile(file);
* const attachment: FileAttachment = {
* url: tags[0][1],
* mimeType: file.type,
* size: file.size,
* name: file.name,
* tags: tags
* };
*
* await sendMessage({
* recipientPubkey: 'hex-pubkey',
* content: 'Check out this file!',
* attachments: [attachment]
* });
* ```
*
* @property url - Blossom server URL where file is hosted
* @property mimeType - MIME type of the file (e.g., 'image/png')
* @property size - File size in bytes
* @property name - Original filename
* @property tags - NIP-94 file metadata tags (includes hashes)
*/
export interface FileAttachment {
url: string;
mimeType: string;
size: number;
name: string;
tags: string[][];
}
/** /**
* Prepare message content with file URLs appended * Prepare message content with file URLs appended
*/ */
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;
} }
@@ -384,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;
@@ -418,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[];
}>({ }>({
@@ -462,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[];
}>({ }>({
@@ -478,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) => {
@@ -528,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);
@@ -565,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) {
@@ -582,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) {
@@ -595,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}`);
@@ -686,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
@@ -921,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)
); );
@@ -1260,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;
@@ -1309,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) {
@@ -1330,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);
@@ -1350,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,
@@ -1362,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'}`,
@@ -1405,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),
@@ -1469,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) {
@@ -1487,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();
@@ -1503,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();
@@ -1520,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(() => {
@@ -1669,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;
+24 -18
View File
@@ -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];
}, },
+62
View File
@@ -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;
}
+7 -2
View File
@@ -45,7 +45,7 @@ export function NoteContent({
href={url} href={url}
target="_blank" target="_blank"
rel="noopener noreferrer" rel="noopener noreferrer"
className="text-blue-500 hover:underline" className="text-blue-500 hover:underline break-all"
> >
{url} {url}
</a> </a>
@@ -61,13 +61,18 @@ export function NoteContent({
parts.push( parts.push(
<NostrMention key={`mention-${keyCounter++}`} pubkey={pubkey} /> <NostrMention key={`mention-${keyCounter++}`} pubkey={pubkey} />
); );
} else if (decoded.type === 'nprofile') {
const pubkey = decoded.data.pubkey;
parts.push(
<NostrMention key={`mention-${keyCounter++}`} pubkey={pubkey} />
);
} else { } else {
// For other types, just show as a link // For other types, just show as a link
parts.push( parts.push(
<Link <Link
key={`nostr-${keyCounter++}`} key={`nostr-${keyCounter++}`}
to={`/${nostrId}`} to={`/${nostrId}`}
className="text-blue-500 hover:underline" className="text-blue-500 hover:underline break-all"
> >
{fullMatch} {fullMatch}
</Link> </Link>
+286
View File
@@ -0,0 +1,286 @@
import { useState, useEffect } from 'react';
import { Plus, X, Wifi, Settings } 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 { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
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>
{/* Settings Popover */}
<Popover>
<PopoverTrigger asChild>
<Button
variant="ghost"
size="icon"
className="size-5 text-muted-foreground hover:text-foreground shrink-0"
>
<Settings className="h-4 w-4" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-48" align="end">
<div className="space-y-3">
<div className="flex items-center justify-between">
<Label htmlFor={`read-${relay.url}`} className="text-sm cursor-pointer">
Read
</Label>
<Switch
id={`read-${relay.url}`}
checked={relay.read}
onCheckedChange={() => handleToggleRead(relay.url)}
className="data-[state=checked]:bg-green-500 scale-75"
/>
</div>
<div className="flex items-center justify-between">
<Label htmlFor={`write-${relay.url}`} className="text-sm cursor-pointer">
Write
</Label>
<Switch
id={`write-${relay.url}`}
checked={relay.write}
onCheckedChange={() => handleToggleWrite(relay.url)}
className="data-[state=checked]:bg-blue-500 scale-75"
/>
</div>
</div>
</PopoverContent>
</Popover>
{/* Remove Button */}
<Button
variant="ghost"
size="icon"
onClick={() => handleRemoveRelay(relay.url)}
className="size-5 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>
);
}
-174
View File
@@ -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>
);
}
+1 -15
View File
@@ -1,7 +1,7 @@
// NOTE: This file is stable and usually should not be modified. // NOTE: This file is stable and usually should not be modified.
// It is important that all functionality in this file is preserved, and should only be modified if explicitly requested. // It is important that all functionality in this file is preserved, and should only be modified if explicitly requested.
import { ChevronDown, LogOut, UserIcon, UserPlus, Wallet } from 'lucide-react'; import { ChevronDown, LogOut, UserIcon, UserPlus } from 'lucide-react';
import { import {
DropdownMenu, DropdownMenu,
DropdownMenuContent, DropdownMenuContent,
@@ -10,8 +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 { 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 +41,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
@@ -64,15 +59,6 @@ export function AccountSwitcher({ onAddAccountClick }: AccountSwitcherProps) {
</DropdownMenuItem> </DropdownMenuItem>
))} ))}
<DropdownMenuSeparator /> <DropdownMenuSeparator />
<WalletModal>
<DropdownMenuItem
className='flex items-center gap-2 cursor-pointer p-2 rounded-md'
onSelect={(e) => e.preventDefault()}
>
<Wallet className='w-4 h-4' />
<span>Wallet Settings</span>
</DropdownMenuItem>
</WalletModal>
<DropdownMenuItem <DropdownMenuItem
onClick={onAddAccountClick} onClick={onAddAccountClick}
className='flex items-center gap-2 cursor-pointer p-2 rounded-md' className='flex items-center gap-2 cursor-pointer p-2 rounded-md'
+1 -5
View File
@@ -2,7 +2,6 @@
// It is important that all functionality in this file is preserved, and should only be modified if explicitly requested. // It is important that all functionality in this file is preserved, and should only be modified if explicitly requested.
import { useState } from 'react'; import { useState } from 'react';
import { User, UserPlus } from 'lucide-react';
import { Button } from '@/components/ui/button.tsx'; import { Button } from '@/components/ui/button.tsx';
import LoginDialog from './LoginDialog'; import LoginDialog from './LoginDialog';
import SignupDialog from './SignupDialog'; import SignupDialog from './SignupDialog';
@@ -34,15 +33,13 @@ export function LoginArea({ className }: LoginAreaProps) {
onClick={() => setLoginDialogOpen(true)} onClick={() => setLoginDialogOpen(true)}
className='flex items-center gap-2 px-4 py-2 rounded-full bg-primary text-primary-foreground w-full font-medium transition-all hover:bg-primary/90 animate-scale-in' className='flex items-center gap-2 px-4 py-2 rounded-full bg-primary text-primary-foreground w-full font-medium transition-all hover:bg-primary/90 animate-scale-in'
> >
<User className='w-4 h-4' />
<span className='truncate'>Log in</span> <span className='truncate'>Log in</span>
</Button><Button </Button><Button
onClick={() => setSignupDialogOpen(true)} onClick={() => setSignupDialogOpen(true)}
variant="outline" variant="outline"
className="flex items-center gap-2 px-4 py-2 rounded-full font-medium transition-all" className="flex items-center gap-2 px-4 py-2 rounded-full font-medium transition-all"
> >
<UserPlus className="w-4 h-4" /> <span>Sign up</span>
<span>Sign Up</span>
</Button> </Button>
</div> </div>
)} )}
@@ -51,7 +48,6 @@ export function LoginArea({ className }: LoginAreaProps) {
isOpen={loginDialogOpen} isOpen={loginDialogOpen}
onClose={() => setLoginDialogOpen(false)} onClose={() => setLoginDialogOpen(false)}
onLogin={handleLogin} onLogin={handleLogin}
onSignup={() => setSignupDialogOpen(true)}
/> />
<SignupDialog <SignupDialog
+151 -187
View File
@@ -2,20 +2,20 @@
// It is important that all functionality in this file is preserved, and should only be modified if explicitly requested. // It is important that all functionality in this file is preserved, and should only be modified if explicitly requested.
import React, { useRef, useState, useEffect } from 'react'; import React, { useRef, useState, useEffect } from 'react';
import { Shield, Upload, AlertTriangle, UserPlus, KeyRound, Sparkles, Cloud } from 'lucide-react'; import { Upload, AlertTriangle, ChevronDown } from 'lucide-react';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input'; import { Input } from '@/components/ui/input';
import { Dialog, DialogContent, DialogHeader, DialogDescription } from "@/components/ui/dialog"; import { Dialog, DialogContent, DialogHeader } from "@/components/ui/dialog";
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'; import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Alert, AlertDescription } from '@/components/ui/alert'; import { Alert, AlertDescription } from '@/components/ui/alert';
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
import { useLoginActions } from '@/hooks/useLoginActions'; import { useLoginActions } from '@/hooks/useLoginActions';
import { cn } from '@/lib/utils'; import { DialogTitle } from '@radix-ui/react-dialog';
interface LoginDialogProps { interface LoginDialogProps {
isOpen: boolean; isOpen: boolean;
onClose: () => void; onClose: () => void;
onLogin: () => void; onLogin: () => void;
onSignup?: () => void;
} }
const validateNsec = (nsec: string) => { const validateNsec = (nsec: string) => {
@@ -26,7 +26,7 @@ const validateBunkerUri = (uri: string) => {
return uri.startsWith('bunker://'); return uri.startsWith('bunker://');
}; };
const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onSignup }) => { const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin }) => {
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
const [isFileLoading, setIsFileLoading] = useState(false); const [isFileLoading, setIsFileLoading] = useState(false);
const [nsec, setNsec] = useState(''); const [nsec, setNsec] = useState('');
@@ -170,203 +170,167 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
reader.readAsText(file); reader.readAsText(file);
}; };
const handleSignupClick = () => { const hasExtension = 'nostr' in window;
onClose(); const [isMoreOptionsOpen, setIsMoreOptionsOpen] = useState(false);
if (onSignup) {
onSignup();
}
};
const defaultTab = 'nostr' in window ? 'extension' : 'key'; const renderTabs = () => (
<Tabs defaultValue="key" className="w-full">
<TabsList className="grid w-full grid-cols-2 bg-muted/80 rounded-lg mb-4">
<TabsTrigger value="key" className="flex items-center gap-2">
<span>Secret Key</span>
</TabsTrigger>
<TabsTrigger value="bunker" className="flex items-center gap-2">
<span>Remote Signer</span>
</TabsTrigger>
</TabsList>
<TabsContent value='key' className='space-y-4'>
<form onSubmit={(e) => {
e.preventDefault();
handleKeyLogin();
}} className='space-y-4'>
<div className='space-y-2'>
<Input
id='nsec'
type="password"
value={nsec}
onChange={(e) => {
setNsec(e.target.value);
if (errors.nsec) setErrors(prev => ({ ...prev, nsec: undefined }));
}}
className={`rounded-lg ${
errors.nsec ? 'border-red-500 focus-visible:ring-red-500' : ''
}`}
placeholder='nsec1...'
autoComplete="off"
/>
{errors.nsec && (
<p className="text-sm text-red-500">{errors.nsec}</p>
)}
</div>
<div className="flex space-x-2">
<Button
type="submit"
size="lg"
disabled={isLoading || !nsec.trim()}
className="flex-1"
>
{isLoading ? 'Verifying...' : 'Log in'}
</Button>
<input
type="file"
accept=".txt"
className="hidden"
ref={fileInputRef}
onChange={handleFileUpload}
/>
<Button
type="button"
variant="outline"
size="lg"
onClick={() => fileInputRef.current?.click()}
disabled={isLoading || isFileLoading}
className="px-3"
>
<Upload className="w-4 h-4" />
</Button>
</div>
{errors.file && (
<p className="text-sm text-red-500 text-center">{errors.file}</p>
)}
</form>
</TabsContent>
<TabsContent value='bunker' className='space-y-4'>
<form onSubmit={(e) => {
e.preventDefault();
handleBunkerLogin();
}} className='space-y-4'>
<div className='space-y-2'>
<Input
id='bunkerUri'
value={bunkerUri}
onChange={(e) => {
setBunkerUri(e.target.value);
if (errors.bunker) setErrors(prev => ({ ...prev, bunker: undefined }));
}}
className={`rounded-lg border-gray-300 dark:border-gray-700 focus-visible:ring-primary ${
errors.bunker ? 'border-red-500' : ''
}`}
placeholder='bunker://'
autoComplete="off"
/>
{errors.bunker && (
<p className="text-sm text-red-500">{errors.bunker}</p>
)}
</div>
<Button
type="submit"
size="lg"
className='w-full'
disabled={isLoading || !bunkerUri.trim()}
>
{isLoading ? 'Connecting...' : 'Log in'}
</Button>
</form>
</TabsContent>
</Tabs>
);
return ( return (
<Dialog open={isOpen} onOpenChange={onClose}> <Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent <DialogContent className="max-w-[95vw] sm:max-w-sm max-h-[90dvh] p-0 gap-6 overflow-hidden rounded-2xl overflow-y-auto">
className={cn("max-w-[95vw] sm:max-w-md max-h-[90vh] max-h-[90dvh] p-0 overflow-hidden rounded-2xl overflow-y-scroll")} <DialogHeader className="px-6 pt-6">
> <DialogTitle className="text-lg font-semibold leading-none tracking-tight text-center">
<DialogHeader className={cn('px-6 pt-6 pb-1 relative')}> Log in
</DialogTitle>
<DialogDescription className="text-center">
Sign up or log in to continue
</DialogDescription>
</DialogHeader> </DialogHeader>
<div className='px-6 pt-2 pb-4 space-y-4 overflow-y-auto flex-1'>
{/* Prominent Sign Up Section */}
<div className='relative p-4 rounded-2xl bg-gradient-to-br from-blue-50 to-indigo-100 dark:from-blue-950/50 dark:to-indigo-950/50 border border-blue-200 dark:border-blue-800 overflow-hidden'>
<div className='relative z-10 text-center space-y-3'>
<div className='flex justify-center items-center gap-2 mb-2'>
<Sparkles className='w-5 h-5 text-blue-600' />
<span className='font-semibold text-blue-800 dark:text-blue-200'>
New to Nostr?
</span>
</div>
<p className='text-sm text-blue-700 dark:text-blue-300'>
Create a new account to get started. It's free and open.
</p>
<Button
onClick={handleSignupClick}
className='w-full rounded-full py-3 text-base font-semibold bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 transform transition-all duration-200 hover:scale-105 shadow-lg border-0'
>
<UserPlus className='w-4 h-4 mr-2' />
<span>Sign Up</span>
</Button>
</div>
</div>
{/* Divider */} <div className="flex size-40 text-8xl bg-primary/10 rounded-full items-center justify-center justify-self-center">
<div className='relative'> 🔑
<div className='absolute inset-0 flex items-center'> </div>
<div className='w-full border-t border-gray-300 dark:border-gray-600'></div>
</div>
<div className='relative flex justify-center text-sm'>
<span className='px-3 bg-background text-muted-foreground'>
<span>Or log in</span>
</span>
</div>
</div>
{/* Login Methods */} <div className='px-6 pb-6 space-y-4 overflow-y-auto'>
<Tabs defaultValue={defaultTab} className="w-full"> {/* Extension Login Button - shown if extension is available */}
<TabsList className="grid w-full grid-cols-3 bg-muted/80 rounded-lg mb-4"> {hasExtension && (
<TabsTrigger value="extension" className="flex items-center gap-2"> <div className="space-y-4">
<Shield className="w-4 h-4" />
<span>Extension</span>
</TabsTrigger>
<TabsTrigger value="key" className="flex items-center gap-2">
<KeyRound className="w-4 h-4" />
<span>Key</span>
</TabsTrigger>
<TabsTrigger value="bunker" className="flex items-center gap-2">
<Cloud className="w-4 h-4" />
<span>Bunker</span>
</TabsTrigger>
</TabsList>
<TabsContent value='extension' className='space-y-3 bg-muted'>
{errors.extension && ( {errors.extension && (
<Alert variant="destructive"> <Alert variant="destructive">
<AlertTriangle className="h-4 w-4" /> <AlertTriangle className="h-4 w-4" />
<AlertDescription>{errors.extension}</AlertDescription> <AlertDescription>{errors.extension}</AlertDescription>
</Alert> </Alert>
)} )}
<div className='text-center p-4 rounded-lg bg-gray-50 dark:bg-gray-800'> <Button
<Shield className='w-12 h-12 mx-auto mb-3 text-primary' /> className="w-full h-12 px-9"
<p className='text-sm text-gray-600 dark:text-gray-300 mb-4'> onClick={handleExtensionLogin}
Login with one click using the browser extension disabled={isLoading}
</p> >
<div className="flex justify-center"> {isLoading ? 'Logging in...' : 'Log in with Extension'}
<Button </Button>
className='w-full rounded-full py-4' </div>
onClick={handleExtensionLogin} )}
disabled={isLoading}
>
{isLoading ? 'Logging in...' : 'Login with Extension'}
</Button>
</div>
</div>
</TabsContent>
<TabsContent value='key' className='space-y-4'> {/* Tabs - wrapped in collapsible if extension is available, otherwise shown directly */}
<div className='space-y-4'> {hasExtension ? (
<div className='space-y-2'> <Collapsible className="space-y-4" open={isMoreOptionsOpen} onOpenChange={setIsMoreOptionsOpen}>
<label htmlFor='nsec' className='text-sm font-medium'> <CollapsibleTrigger asChild>
Secret Key (nsec) <button className="w-full flex items-center justify-center gap-1 text-sm text-muted-foreground hover:text-foreground transition-colors">
</label> <span>More Options</span>
<Input <ChevronDown className={`w-4 h-4 transition-transform ${isMoreOptionsOpen ? 'rotate-180' : ''}`} />
id='nsec' </button>
type="password" </CollapsibleTrigger>
value={nsec}
onChange={(e) => {
setNsec(e.target.value);
if (errors.nsec) setErrors(prev => ({ ...prev, nsec: undefined }));
}}
className={`rounded-lg ${
errors.nsec ? 'border-red-500 focus-visible:ring-red-500' : ''
}`}
placeholder='nsec1...'
autoComplete="off"
/>
{errors.nsec && (
<p className="text-sm text-red-500">{errors.nsec}</p>
)}
</div>
<Button <CollapsibleContent>
className='w-full rounded-full py-3' {renderTabs()}
onClick={handleKeyLogin} </CollapsibleContent>
disabled={isLoading || !nsec.trim()} </Collapsible>
> ) : (
{isLoading ? 'Verifying...' : 'Log In'} renderTabs()
</Button> )}
<div className='relative'>
<div className='absolute inset-0 flex items-center'>
<div className='w-full border-t border-muted'></div>
</div>
<div className='relative flex justify-center text-xs'>
<span className='px-2 bg-background text-muted-foreground'>
or
</span>
</div>
</div>
<div className='text-center'>
<input
type='file'
accept='.txt'
className='hidden'
ref={fileInputRef}
onChange={handleFileUpload}
/>
<Button
variant='outline'
className='w-full'
onClick={() => fileInputRef.current?.click()}
disabled={isLoading || isFileLoading}
>
<Upload className='w-4 h-4 mr-2' />
{isFileLoading ? 'Reading File...' : 'Upload Your Key File'}
</Button>
{errors.file && (
<p className="text-sm text-red-500 mt-2">{errors.file}</p>
)}
</div>
</div>
</TabsContent>
<TabsContent value='bunker' className='space-y-3 bg-muted'>
<div className='space-y-2'>
<label htmlFor='bunkerUri' className='text-sm font-medium text-gray-700 dark:text-gray-400'>
Bunker URI
</label>
<Input
id='bunkerUri'
value={bunkerUri}
onChange={(e) => {
setBunkerUri(e.target.value);
if (errors.bunker) setErrors(prev => ({ ...prev, bunker: undefined }));
}}
className={`rounded-lg border-gray-300 dark:border-gray-700 focus-visible:ring-primary ${
errors.bunker ? 'border-red-500' : ''
}`}
placeholder='bunker://'
autoComplete="off"
/>
{errors.bunker && (
<p className="text-sm text-red-500">{errors.bunker}</p>
)}
</div>
<div className="flex justify-center">
<Button
className='w-full rounded-full py-4'
onClick={handleBunkerLogin}
disabled={isLoading || !bunkerUri.trim()}
>
{isLoading ? 'Connecting...' : 'Login with Bunker'}
</Button>
</div>
</TabsContent>
</Tabs>
</div> </div>
</DialogContent> </DialogContent>
</Dialog> </Dialog>
+88 -435
View File
@@ -2,35 +2,26 @@
// It is important that all functionality in this file is preserved, and should only be modified if explicitly requested. // It is important that all functionality in this file is preserved, and should only be modified if explicitly requested.
import React, { useState, useEffect, useRef } from 'react'; import React, { useState, useEffect, useRef } from 'react';
import { Download, Key, UserPlus, FileText, Shield, User, Sparkles, LogIn, CheckCircle, Upload, Globe } from 'lucide-react'; import { Download, Upload, Eye, EyeOff } from 'lucide-react';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input'; import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea'; import { Textarea } from '@/components/ui/textarea';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog"; import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Card, CardContent } from '@/components/ui/card';
import { toast } from '@/hooks/useToast'; import { toast } from '@/hooks/useToast';
import { useLoginActions } from '@/hooks/useLoginActions'; import { useLoginActions } from '@/hooks/useLoginActions';
import { useNostrPublish } from '@/hooks/useNostrPublish'; import { useNostrPublish } from '@/hooks/useNostrPublish';
import { useUploadFile } from '@/hooks/useUploadFile'; import { useUploadFile } from '@/hooks/useUploadFile';
import { generateSecretKey, nip19 } from 'nostr-tools'; import { generateSecretKey, getPublicKey, nip19 } from 'nostr-tools';
import { cn } from '@/lib/utils';
interface SignupDialogProps { interface SignupDialogProps {
isOpen: boolean; isOpen: boolean;
onClose: () => void; onClose: () => void;
onComplete?: () => void;
} }
const sanitizeFilename = (filename: string) => { const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose }) => {
return filename.replace(/[^a-z0-9_.-]/gi, '_'); const [step, setStep] = useState<'generate' | 'download' | 'profile'>('generate');
}
const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete }) => {
const [step, setStep] = useState<'welcome' | 'generate' | 'download' | 'profile' | 'done'>('welcome');
const [isLoading, setIsLoading] = useState(false);
const [nsec, setNsec] = useState(''); const [nsec, setNsec] = useState('');
const [showSparkles, setShowSparkles] = useState(false); const [showKey, setShowKey] = useState(false);
const [keySecured, setKeySecured] = useState<'none' | 'downloaded'>('none');
const [profileData, setProfileData] = useState({ const [profileData, setProfileData] = useState({
name: '', name: '',
about: '', about: '',
@@ -43,34 +34,9 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
// Generate a proper nsec key using nostr-tools // Generate a proper nsec key using nostr-tools
const generateKey = () => { const generateKey = () => {
setIsLoading(true); const sk = generateSecretKey();
setShowSparkles(true); setNsec(nip19.nsecEncode(sk));
setStep('download');
// Add a dramatic pause for the key generation effect
setTimeout(() => {
try {
// Generate a new secret key
const sk = generateSecretKey();
// Convert to nsec format
setNsec(nip19.nsecEncode(sk));
setStep('download');
toast({
title: 'Your Secret Key is Ready!',
description: 'A new secret key has been generated for you.',
});
} catch {
toast({
title: 'Error',
description: 'Failed to generate key. Please try again.',
variant: 'destructive',
});
} finally {
setIsLoading(false);
setShowSparkles(false);
}
}, 2000);
}; };
const downloadKey = () => { const downloadKey = () => {
@@ -79,8 +45,14 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
const blob = new Blob([nsec], { type: 'text/plain; charset=utf-8' }); const blob = new Blob([nsec], { type: 'text/plain; charset=utf-8' });
const url = globalThis.URL.createObjectURL(blob); const url = globalThis.URL.createObjectURL(blob);
// Sanitize filename const decoded = nip19.decode(nsec);
const filename = sanitizeFilename('nostr-nsec-key.txt'); if (decoded.type !== 'nsec') {
throw new Error('Invalid nsec key');
}
const pubkey = getPublicKey(decoded.data);
const npub = nip19.npubEncode(pubkey);
const filename = `nostr-${location.hostname.replaceAll(/\./g, '-')}-${npub.slice(5, 9)}.nsec.txt`;
// Create a temporary link element and trigger download // Create a temporary link element and trigger download
const a = document.createElement('a'); const a = document.createElement('a');
@@ -94,32 +66,13 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
globalThis.URL.revokeObjectURL(url); globalThis.URL.revokeObjectURL(url);
document.body.removeChild(a); document.body.removeChild(a);
// Mark as secured // Continue to profile step
setKeySecured('downloaded');
toast({
title: 'Secret Key Saved!',
description: 'Your key has been safely stored.',
});
} catch {
toast({
title: 'Download failed',
description: 'Could not download the key file. Please copy it manually.',
variant: 'destructive',
});
}
};
const finishKeySetup = () => {
try {
login.nsec(nsec); login.nsec(nsec);
setStep('profile'); setStep('profile');
} catch { } catch {
toast({ toast({
title: 'Login Failed', title: 'Download failed',
description: 'Failed to login with the generated key. Please try again.', description: 'Could not download the key file. Please copy it manually.',
variant: 'destructive', variant: 'destructive',
}); });
} }
@@ -158,10 +111,6 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
const url = tags[0]?.[1]; const url = tags[0]?.[1];
if (url) { if (url) {
setProfileData(prev => ({ ...prev, picture: url })); setProfileData(prev => ({ ...prev, picture: url }));
toast({
title: 'Avatar uploaded!',
description: 'Your avatar has been uploaded successfully.',
});
} }
} catch { } catch {
toast({ toast({
@@ -173,9 +122,6 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
}; };
const finishSignup = async (skipProfile = false) => { const finishSignup = async (skipProfile = false) => {
// Mark signup completion time for fallback welcome modal
localStorage.setItem('signup_completed', Date.now().toString());
try { try {
// Publish profile if user provided information // Publish profile if user provided information
if (!skipProfile && (profileData.name || profileData.about || profileData.picture)) { if (!skipProfile && (profileData.name || profileData.about || profileData.picture)) {
@@ -188,30 +134,6 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
kind: 0, kind: 0,
content: JSON.stringify(metadata), content: JSON.stringify(metadata),
}); });
toast({
title: 'Profile Created!',
description: 'Your profile has been set up.',
});
}
// Close signup and show welcome modal
onClose();
if (onComplete) {
// Add a longer delay to ensure login state has fully propagated
setTimeout(() => {
onComplete();
}, 600);
} else {
// Fallback for when used without onComplete
setStep('done');
setTimeout(() => {
onClose();
toast({
title: 'Welcome!',
description: 'Your account is ready.',
});
}, 3000);
} }
} catch { } catch {
toast({ toast({
@@ -219,372 +141,111 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
description: 'Your account was created but profile setup failed. You can update it later.', description: 'Your account was created but profile setup failed. You can update it later.',
variant: 'destructive', variant: 'destructive',
}); });
} finally {
// Still proceed to completion even if profile failed
onClose(); onClose();
if (onComplete) {
// Add a longer delay to ensure login state has fully propagated
setTimeout(() => {
onComplete();
}, 600);
} else {
// Fallback for when used without onComplete
setStep('done');
setTimeout(() => {
onClose();
toast({
title: 'Welcome!',
description: 'Your account is ready.',
});
}, 3000);
}
} }
}; };
const getTitle = () => { const getTitle = () => {
if (step === 'welcome') return ( if (step === 'generate') return 'Sign up';
<span className="flex items-center justify-center gap-2"> if (step === 'download') return 'Secret Key';
Create Your Account if (step === 'profile') return 'Create Your Profile';
</span>
);
if (step === 'generate') return (
<span className="flex items-center justify-center gap-2">
Generating Your Key
</span>
);
if (step === 'download') return (
<span className="flex items-center justify-center gap-2">
Secret Key
</span>
);
if (step === 'profile') return (
<span className="flex items-center justify-center gap-2">
Create Your Profile
</span>
);
return (
<span className="flex items-center justify-center gap-2">
Welcome!
</span>
);
}; };
// Reset state when dialog opens // Reset state when dialog opens
useEffect(() => { useEffect(() => {
if (isOpen) { if (isOpen) {
setStep('welcome'); setStep('generate');
setIsLoading(false);
setNsec(''); setNsec('');
setShowSparkles(false); setShowKey(false);
setKeySecured('none');
setProfileData({ name: '', about: '', picture: '' }); setProfileData({ name: '', about: '', picture: '' });
} }
}, [isOpen]); }, [isOpen]);
// Add sparkle animation effect
useEffect(() => {
if (showSparkles) {
const interval = setInterval(() => {
// This will trigger re-renders for sparkle animation
}, 100);
return () => clearInterval(interval);
}
}, [showSparkles]);
return ( return (
<Dialog open={isOpen} onOpenChange={onClose}> <Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent <DialogContent className="max-w-[95vw] sm:max-w-sm max-h-[90dvh] p-0 gap-6 overflow-hidden rounded-2xl overflow-y-auto">
className={cn("max-w-[95vw] sm:max-w-md max-h-[90vh] max-h-[90dvh] p-0 overflow-hidden rounded-2xl flex flex-col")} <DialogHeader className="px-6 pt-6">
> <DialogTitle className="text-lg font-semibold leading-none tracking-tight text-center">
<DialogHeader className={cn('px-6 pt-6 pb-1 relative flex-shrink-0')}>
<DialogTitle className={cn('font-semibold text-center text-lg')}>
{getTitle()} {getTitle()}
</DialogTitle> </DialogTitle>
</DialogHeader> </DialogHeader>
<div className='px-6 pt-2 pb-4 space-y-4 overflow-y-scroll flex-1'>
{/* Welcome Step - New engaging introduction */}
{step === 'welcome' && (
<div className='text-center space-y-4'>
{/* Hero illustration */}
<div className='relative p-6 rounded-2xl bg-gradient-to-br from-blue-50 to-indigo-100 dark:from-blue-950/50 dark:to-indigo-950/50'>
<div className='flex justify-center items-center space-x-4 mb-3'>
<div className='relative'>
<UserPlus className='w-12 h-12 text-blue-600' />
<Sparkles className='w-4 h-4 text-yellow-500 absolute -top-1 -right-1 animate-pulse' />
</div>
<Globe className='w-16 h-16 text-blue-700 animate-spin-slow' />
<div className='relative'>
<FileText className='w-12 h-12 text-blue-600' />
<Sparkles className='w-4 h-4 text-yellow-500 absolute -top-1 -left-1 animate-pulse' style={{animationDelay: '0.3s'}} />
</div>
</div>
{/* Benefits */} <div className='px-6 pb-6 space-y-4 overflow-y-auto flex-1'>
<div className='grid grid-cols-1 gap-2 text-sm'> {/* Generate Step */}
<div className='flex items-center justify-center gap-2 text-blue-700 dark:text-blue-300'>
<Shield className='w-4 h-4' />
Decentralized and censorship-resistant
</div>
<div className='flex items-center justify-center gap-2 text-blue-700 dark:text-blue-300'>
<User className='w-4 h-4' />
You are in control of your data
</div>
<div className='flex items-center justify-center gap-2 text-blue-700 dark:text-blue-300'>
<Globe className='w-4 h-4' />
Join a global network
</div>
</div>
</div>
<div className='space-y-3'>
<Button
className='w-full rounded-full py-6 text-lg font-semibold bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 transform transition-all duration-200 hover:scale-105 shadow-lg'
onClick={() => setStep('generate')}
>
<LogIn className='w-5 h-5 mr-2' />
Get Started
</Button>
</div>
</div>
)}
{/* Generate Step - Enhanced with animations */}
{step === 'generate' && ( {step === 'generate' && (
<div className='text-center space-y-4'> <div className='text-center space-y-6'>
<div className='relative p-6 rounded-2xl bg-gradient-to-br from-blue-50 to-purple-100 dark:from-blue-950/50 dark:to-purple-950/50 overflow-hidden'> <div className="flex size-40 text-8xl bg-primary/10 rounded-full items-center justify-center justify-self-center">
{/* Animated background elements */} 🔑
{showSparkles && (
<div className='absolute inset-0'>
{[...Array(12)].map((_, i) => (
<Sparkles
key={i}
className={`absolute w-4 h-4 text-yellow-400 animate-ping`}
style={{
left: `${Math.random() * 80 + 10}%`,
top: `${Math.random() * 80 + 10}%`,
animationDelay: `${Math.random() * 2}s`
}}
/>
))}
</div>
)}
<div className='relative z-10'>
{isLoading ? (
<div className='space-y-3'>
<div className='relative'>
<Key className='w-20 h-20 text-primary mx-auto animate-pulse' />
<div className='absolute inset-0 flex items-center justify-center'>
<div className='w-24 h-24 border-4 border-yellow-400 border-t-transparent rounded-full animate-spin'></div>
</div>
</div>
<div className='space-y-2'>
<p className='text-lg font-semibold text-primary flex items-center justify-center gap-2'>
<Sparkles className='w-5 h-5' />
Generating your secret key...
</p>
<p className='text-sm text-muted-foreground'>
Creating your secure key
</p>
</div>
</div>
) : (
<div className='space-y-3'>
<Key className='w-20 h-20 text-primary mx-auto' />
<div className='space-y-2'>
<p className='text-lg font-semibold'>
Ready to generate your secret key?
</p>
<p className='text-sm text-muted-foreground px-5'>
This key will be your password to access applications within the Nostr network.
</p>
</div>
</div>
)}
</div>
</div> </div>
{!isLoading && ( <Button className="w-full h-12 px-9" onClick={generateKey}>
<Button Generate key
className='w-full rounded-full py-6 text-lg font-semibold bg-gradient-to-r from-purple-600 to-blue-600 hover:from-purple-700 hover:to-blue-700 transform transition-all duration-200 hover:scale-105 shadow-lg' </Button>
onClick={generateKey}
disabled={isLoading}
>
<Sparkles className='w-5 h-5 mr-2' />
Generate My Secret Key
</Button>
)}
</div> </div>
)} )}
{/* Download Step - Whimsical and magical */} {/* Download Step */}
{step === 'download' && ( {step === 'download' && (
<div className='text-center space-y-4'> <div className='space-y-4'>
{/* Key reveal */} <div className="flex size-16 text-4xl bg-primary/10 rounded-full items-center justify-center justify-self-center">
<div className='relative p-6 rounded-2xl bg-gradient-to-br from-blue-50 to-indigo-100 dark:from-blue-950/50 dark:to-indigo-950/50 overflow-hidden'> 🔑
{/* Sparkles */}
<div className='absolute inset-0 pointer-events-none'>
<Sparkles className='absolute top-3 left-4 w-3 h-3 text-yellow-400 animate-pulse' style={{animationDelay: '0s'}} />
<Sparkles className='absolute top-6 right-6 w-3 h-3 text-yellow-500 animate-pulse' style={{animationDelay: '0.5s'}} />
<Sparkles className='absolute bottom-4 left-6 w-3 h-3 text-yellow-400 animate-pulse' style={{animationDelay: '1s'}} />
<Sparkles className='absolute bottom-3 right-4 w-3 h-3 text-yellow-500 animate-pulse' style={{animationDelay: '1.5s'}} />
</div>
<div className='relative z-10 flex justify-center items-center mb-3'>
<div className='relative'>
<div className='w-16 h-16 bg-gradient-to-br from-blue-200 to-indigo-300 rounded-full flex items-center justify-center shadow-lg animate-pulse'>
<Key className='w-8 h-8 text-indigo-800' />
</div>
<div className='absolute -top-1 -right-1 w-5 h-5 bg-blue-500 rounded-full flex items-center justify-center animate-bounce'>
<Sparkles className='w-3 h-3 text-white' />
</div>
</div>
</div>
<div className='relative z-10 space-y-2'>
<p className='text-base font-semibold'>
Your secret key has been generated!
</p>
{/* Warning */}
<div className='relative mx-auto max-w-sm'>
<div className='p-3 bg-gradient-to-r from-amber-100 via-yellow-50 to-amber-100 dark:from-amber-950/40 dark:via-yellow-950/20 dark:to-amber-950/40 rounded-lg border-2 border-amber-300 dark:border-amber-700 shadow-md'>
<div className='flex items-center gap-2 mb-1'>
<FileText className='w-3 h-3 text-amber-700' />
<span className='text-xs font-bold text-amber-800 dark:text-amber-200'>
Important Warning
</span>
</div>
<p className='text-xs text-red-700 dark:text-amber-300 italic'>
This key is your primary and only means of accessing your account. Store it safely and securely.
</p>
</div>
</div>
</div>
</div> </div>
{/* Key vault */} <div className="relative">
<Input
type={showKey ? "text" : "password"}
{/* Security options */} value={nsec}
<div className='space-y-3'> readOnly
className="pr-10 font-mono text-sm"
/>
<div className='grid grid-cols-1 gap-2'>
{/* Download Option */}
<Card className={`cursor-pointer transition-all duration-200 ${
keySecured === 'downloaded'
? 'ring-2 ring-green-500 bg-green-50 dark:bg-green-950/20'
: 'hover:bg-primary/5 hover:border-primary/20'
}`}>
<CardContent className='p-3'>
<Button
variant="ghost"
className='w-full h-auto p-0 justify-start hover:bg-transparent'
onClick={downloadKey}
>
<div className='flex items-center gap-3 w-full'>
<div className={`p-1.5 rounded-lg ${
keySecured === 'downloaded'
? 'bg-green-100 dark:bg-green-900'
: 'bg-primary/10'
}`}>
{keySecured === 'downloaded' ? (
<CheckCircle className='w-4 h-4 text-green-600' />
) : (
<Download className='w-4 h-4 text-primary' />
)}
</div>
<div className='flex-1 text-left'>
<div className='font-medium text-sm'>
Download as File
</div>
<div className='text-xs text-muted-foreground'>
Save as nostr-nsec-key.txt file
</div>
</div>
{keySecured === 'downloaded' && (
<div className='text-xs font-medium text-green-600'>
✓ Downloaded
</div>
)}
</div>
</Button>
</CardContent>
</Card>
</div>
{/* Continue button */}
<Button <Button
className={`w-full rounded-full py-4 text-base font-semibold transform transition-all duration-200 shadow-lg ${ type="button"
keySecured === 'downloaded' variant="ghost"
? 'bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 dark:from-blue-950/50 dark:to-purple-950/50 hover:scale-105' size="icon"
: 'bg-gradient-to-r from-blue-600/60 to-indigo-600/60 text-muted cursor-not-allowed' className="absolute right-0 top-0 h-full px-3 hover:bg-transparent"
}`} onClick={() => setShowKey(!showKey)}
onClick={finishKeySetup}
disabled={keySecured !== 'downloaded'}
> >
<LogIn className='w-4 h-4 mr-2 flex-shrink-0' /> {showKey ? (
<span className="text-center leading-tight"> <EyeOff className="h-4 w-4 text-muted-foreground" />
{keySecured === 'none' ? ( ) : (
<> <Eye className="h-4 w-4 text-muted-foreground" />
Please download your key first )}
</>
) : (
<>
<span className="hidden sm:inline">My Key is Safe - Continue</span>
<span className="sm:hidden">Key Secured - Continue</span>
</>
)}
</span>
</Button> </Button>
</div> </div>
<Button
className="w-full h-12 px-9"
onClick={downloadKey}
>
<Download className="size-4" />
Download key
</Button>
<div className='mx-auto max-w-sm'>
<div className='p-3 bg-amber-50 dark:bg-amber-950/20 rounded-lg border border-amber-200 dark:border-amber-800'>
<div className='flex items-center gap-2 mb-1'>
<span className='text-xs font-semibold text-amber-800 dark:text-amber-200'>
Important Warning
</span>
</div>
<p className='text-xs text-amber-900 dark:text-amber-300'>
This key is your primary and only means of accessing your account. Store it safely and securely. Please download your key to continue.
</p>
</div>
</div>
</div> </div>
)} )}
{/* Profile Step - Optional profile setup */} {/* Profile Step */}
{step === 'profile' && ( {step === 'profile' && (
<div className='text-center space-y-4'> <div className='text-center space-y-4'>
{/* Profile setup illustration */}
<div className='relative p-6 rounded-2xl bg-gradient-to-br from-blue-50 to-indigo-100 dark:from-blue-950/50 dark:to-indigo-950/50 overflow-hidden'>
{/* Sparkles */}
<div className='absolute inset-0 pointer-events-none'>
<Sparkles className='absolute top-3 left-4 w-3 h-3 text-yellow-400 animate-pulse' style={{animationDelay: '0s'}} />
<Sparkles className='absolute top-6 right-6 w-3 h-3 text-yellow-500 animate-pulse' style={{animationDelay: '0.5s'}} />
<Sparkles className='absolute bottom-4 left-6 w-3 h-3 text-yellow-400 animate-pulse' style={{animationDelay: '1s'}} />
</div>
<div className='relative z-10 flex justify-center items-center mb-3'>
<div className='relative'>
<div className='w-16 h-16 bg-gradient-to-br from-blue-200 to-indigo-300 rounded-full flex items-center justify-center shadow-lg'>
<User className='w-8 h-8 text-blue-800' />
</div>
<div className='absolute -top-1 -right-1 w-5 h-5 bg-blue-500 rounded-full flex items-center justify-center animate-bounce'>
<Sparkles className='w-3 h-3 text-white' />
</div>
</div>
</div>
<div className='relative z-10 space-y-2'>
<p className='text-base font-semibold'>
Almost there! Let's set up your profile
</p>
<p className='text-sm text-muted-foreground'>
Your profile is your identity on Nostr.
</p>
</div>
</div>
{/* Publishing status indicator */} {/* Publishing status indicator */}
{isPublishing && ( {isPublishing && (
<div className='relative p-4 rounded-xl bg-gradient-to-r from-blue-50 to-indigo-50 dark:from-blue-950/30 dark:to-indigo-950/30 border border-blue-200 dark:border-blue-800'> <div className='p-4 rounded-lg bg-muted border'>
<div className='flex items-center justify-center gap-3'> <div className='flex items-center justify-center gap-3'>
<div className='w-5 h-5 border-2 border-blue-600 border-t-transparent rounded-full animate-spin' /> <div className='w-5 h-5 border-2 border-primary border-t-transparent rounded-full animate-spin' />
<span className='text-sm font-medium text-blue-700 dark:text-blue-300'> <span className='text-sm font-medium'>
Publishing your profile... Publishing your profile...
</span> </span>
</div> </div>
@@ -602,7 +263,6 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
value={profileData.name} value={profileData.name}
onChange={(e) => setProfileData(prev => ({ ...prev, name: e.target.value }))} onChange={(e) => setProfileData(prev => ({ ...prev, name: e.target.value }))}
placeholder='Your name' placeholder='Your name'
className='rounded-lg'
disabled={isPublishing} disabled={isPublishing}
/> />
</div> </div>
@@ -616,7 +276,7 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
value={profileData.about} value={profileData.about}
onChange={(e) => setProfileData(prev => ({ ...prev, about: e.target.value }))} onChange={(e) => setProfileData(prev => ({ ...prev, about: e.target.value }))}
placeholder='Tell others about yourself...' placeholder='Tell others about yourself...'
className='rounded-lg resize-none' className='resize-none'
rows={3} rows={3}
disabled={isPublishing} disabled={isPublishing}
/> />
@@ -632,7 +292,7 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
value={profileData.picture} value={profileData.picture}
onChange={(e) => setProfileData(prev => ({ ...prev, picture: e.target.value }))} onChange={(e) => setProfileData(prev => ({ ...prev, picture: e.target.value }))}
placeholder='https://example.com/your-avatar.jpg' placeholder='https://example.com/your-avatar.jpg'
className='rounded-lg flex-1' className='flex-1'
disabled={isPublishing} disabled={isPublishing}
/> />
<input <input
@@ -648,7 +308,6 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
size='icon' size='icon'
onClick={() => avatarFileInputRef.current?.click()} onClick={() => avatarFileInputRef.current?.click()}
disabled={isUploading || isPublishing} disabled={isUploading || isPublishing}
className='rounded-lg shrink-0'
title='Upload avatar image' title='Upload avatar image'
> >
{isUploading ? ( {isUploading ? (
@@ -664,7 +323,7 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
{/* Action buttons */} {/* Action buttons */}
<div className='space-y-3'> <div className='space-y-3'>
<Button <Button
className='w-full rounded-full py-4 text-base font-semibold bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 transform transition-all duration-200 hover:scale-105 shadow-lg disabled:opacity-50 disabled:cursor-not-allowed disabled:transform-none' className='w-full'
onClick={() => finishSignup(false)} onClick={() => finishSignup(false)}
disabled={isPublishing || isUploading} disabled={isPublishing || isUploading}
> >
@@ -674,24 +333,18 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
Creating Profile... Creating Profile...
</> </>
) : ( ) : (
<> 'Create profile'
<User className='w-4 h-4 mr-2' />
Create Profile & Finish
</>
)} )}
</Button> </Button>
<Button <Button
variant='outline' variant='outline'
className='w-full rounded-full py-3 disabled:opacity-50 disabled:cursor-not-allowed' className='w-full'
onClick={() => finishSignup(true)} onClick={() => finishSignup(true)}
disabled={isPublishing || isUploading} disabled={isPublishing || isUploading}
> >
{isPublishing ? ( {isPublishing ? (
<> 'Setting up account...'
<div className='w-4 h-4 mr-2 border-2 border-current border-t-transparent rounded-full animate-spin' />
Setting up account...
</>
) : ( ) : (
'Skip for now' 'Skip for now'
)} )}
+2 -1
View File
@@ -1,5 +1,6 @@
import { useState, useRef, useEffect, useCallback, memo } from 'react'; import { useState, useRef, useEffect, useCallback, memo } from 'react';
import { useConversationMessages, useDMContext } from '@/contexts/DMContext'; import { useConversationMessages } from '@/hooks/useConversationMessages';
import { useDMContext } from '@/hooks/useDMContext';
import { useCurrentUser } from '@/hooks/useCurrentUser'; import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useAuthor } from '@/hooks/useAuthor'; import { useAuthor } from '@/hooks/useAuthor';
import { genUserName } from '@/lib/genUserName'; import { genUserName } from '@/lib/genUserName';
+1 -1
View File
@@ -1,6 +1,6 @@
import { useMemo, useState, memo } from 'react'; import { useMemo, useState, memo } from 'react';
import { AlertTriangle, Info, Loader2 } from 'lucide-react'; import { AlertTriangle, Info, Loader2 } from 'lucide-react';
import { useDMContext } from '@/contexts/DMContext'; import { useDMContext } from '@/hooks/useDMContext';
import { useAuthor } from '@/hooks/useAuthor'; import { useAuthor } from '@/hooks/useAuthor';
import { genUserName } from '@/lib/genUserName'; import { genUserName } from '@/lib/genUserName';
import { formatConversationTime, formatFullDateTime } from '@/lib/dmUtils'; import { formatConversationTime, formatFullDateTime } from '@/lib/dmUtils';
+1 -1
View File
@@ -2,7 +2,7 @@ import { useState, useCallback } from 'react';
import { DMConversationList } from '@/components/dm/DMConversationList'; import { DMConversationList } from '@/components/dm/DMConversationList';
import { DMChatArea } from '@/components/dm/DMChatArea'; import { DMChatArea } from '@/components/dm/DMChatArea';
import { DMStatusInfo } from '@/components/dm/DMStatusInfo'; import { DMStatusInfo } from '@/components/dm/DMStatusInfo';
import { useDMContext } from '@/contexts/DMContext'; import { useDMContext } from '@/hooks/useDMContext';
import { useIsMobile } from '@/hooks/useIsMobile'; import { useIsMobile } from '@/hooks/useIsMobile';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
import { import {
+1 -1
View File
@@ -1,6 +1,6 @@
import { useState } from 'react'; import { useState } from 'react';
import { RefreshCw, Database, Wifi, CheckCircle2, Loader2 } from 'lucide-react'; import { RefreshCw, Database, Wifi, CheckCircle2, Loader2 } from 'lucide-react';
import { useDMContext } from '@/contexts/DMContext'; import { useDMContext } from '@/hooks/useDMContext';
import { LOADING_PHASES } from '@/lib/dmConstants'; import { LOADING_PHASES } from '@/lib/dmConstants';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card'; import { Card, CardContent } from '@/components/ui/card';
+1 -1
View File
@@ -43,7 +43,7 @@ const DialogContent = React.forwardRef<
> >
{children} {children}
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground"> <DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
<X className="h-4 w-4" /> <X className="size-5" />
<span className="sr-only">Close</span> <span className="sr-only">Close</span>
</DialogPrimitive.Close> </DialogPrimitive.Close>
</DialogPrimitive.Content> </DialogPrimitive.Content>
+9 -4
View File
@@ -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);
+138
View File
@@ -0,0 +1,138 @@
import { createContext } from 'react';
import { type LoadingPhase, type ProtocolMode } from '@/lib/dmConstants';
import { type NostrEvent } from '@nostrify/nostrify';
import type { MessageProtocol } from '@/lib/dmConstants';
// ============================================================================
// DM Types and Constants
// ============================================================================
interface ParticipantData {
messages: DecryptedMessage[];
lastActivity: number;
lastMessage: DecryptedMessage | null;
hasNIP4: boolean;
hasNIP17: boolean;
}
type MessagesState = Map<string, ParticipantData>;
interface LastSyncData {
nip4: number | null;
nip17: number | null;
}
interface SubscriptionStatus {
isNIP4Connected: boolean;
isNIP17Connected: boolean;
}
interface ScanProgress {
current: number;
status: string;
}
interface ScanProgressState {
nip4: ScanProgress | null;
nip17: ScanProgress | null;
}
interface ConversationSummary {
id: string;
pubkey: string;
lastMessage: DecryptedMessage | null;
lastActivity: number;
hasNIP4Messages: boolean;
hasNIP17Messages: boolean;
isKnown: boolean;
isRequest: boolean;
lastMessageFromUser: boolean;
}
interface DecryptedMessage extends NostrEvent {
decryptedContent?: string;
error?: string;
isSending?: boolean;
clientFirstSeen?: number;
decryptedEvent?: NostrEvent; // For NIP-17: the inner kind 14/15 event
originalGiftWrapId?: string; // Store gift wrap ID for NIP-17 deduplication
}
/**
* File attachment for direct messages (NIP-92 compatible).
*
* All fields are required. Use with `useUploadFile` hook to upload files
* and generate the proper tags format.
*
* @example
* ```tsx
* import { useUploadFile } from '@/hooks/useUploadFile';
* import type { FileAttachment } from '@/contexts/DMContext';
*
* const { mutateAsync: uploadFile } = useUploadFile();
*
* const tags = await uploadFile(file);
* const attachment: FileAttachment = {
* url: tags[0][1],
* mimeType: file.type,
* size: file.size,
* name: file.name,
* tags: tags
* };
*
* await sendMessage({
* recipientPubkey: 'hex-pubkey',
* content: 'Check out this file!',
* attachments: [attachment]
* });
* ```
*
* @property url - Blossom server URL where file is hosted
* @property mimeType - MIME type of the file (e.g., 'image/png')
* @property size - File size in bytes
* @property name - Original filename
* @property tags - NIP-94 file metadata tags (includes hashes)
*/
export interface FileAttachment {
url: string;
mimeType: string;
size: number;
name: string;
tags: string[][];
}
/**
* Direct Messaging context interface providing access to all DM functionality.
*
* @property messages - Raw message state (Map of pubkey -> participant data)
* @property isLoading - True during initial load phases
* @property loadingPhase - Current loading phase (CACHE, RELAYS, SUBSCRIPTIONS, READY, IDLE)
* @property isDoingInitialLoad - True only during cache/relay loading (not subscriptions)
* @property lastSync - Unix timestamps of last successful sync for each protocol
* @property subscriptions - Connection status for real-time message subscriptions
* @property conversations - Array of conversation summaries sorted by last activity
* @property sendMessage - Send an encrypted direct message (NIP-04 or NIP-17)
* @property protocolMode - Current protocol mode (NIP04_ONLY, NIP17_ONLY, or BOTH)
* @property scanProgress - Progress info for large message history scans
* @property clearCacheAndRefetch - Clear IndexedDB cache and reload all messages from relays
*/
export interface DMContextType {
messages: MessagesState;
isLoading: boolean;
loadingPhase: LoadingPhase;
isDoingInitialLoad: boolean;
lastSync: LastSyncData;
subscriptions: SubscriptionStatus;
conversations: ConversationSummary[];
sendMessage: (params: {
recipientPubkey: string;
content: string;
protocol?: MessageProtocol;
attachments?: FileAttachment[];
}) => Promise<void>;
protocolMode: ProtocolMode;
scanProgress: ScanProgressState;
clearCacheAndRefetch: () => Promise<void>;
}
export const DMContext = createContext<DMContextType | null>(null);
+87
View File
@@ -0,0 +1,87 @@
import { useCallback, useEffect, useMemo, useState } from "react";
import { useDMContext } from "@/hooks/useDMContext";
const MESSAGES_PER_PAGE = 25;
/**
* Hook to access paginated messages for a specific conversation.
*
* Returns the most recent messages (default 25) with the ability to load earlier messages.
* Automatically resets to default page size when switching conversations.
*
* @example
* ```tsx
* import { useConversationMessages } from '@/contexts/DMContext';
*
* function MessageThread({ recipientPubkey }: { recipientPubkey: string }) {
* const {
* messages,
* hasMoreMessages,
* loadEarlierMessages,
* totalCount
* } = useConversationMessages(recipientPubkey);
*
* return (
* <div>
* {hasMoreMessages && (
* <button onClick={loadEarlierMessages}>
* Load Earlier ({totalCount - messages.length} more)
* </button>
* )}
* {messages.map(msg => (
* <div key={msg.id}>{msg.decryptedContent}</div>
* ))}
* </div>
* );
* }
* ```
*
* @param conversationId - The pubkey of the conversation participant
* @returns Paginated message data with loading function
*/
export function useConversationMessages(conversationId: string) {
const { messages: allMessages } = useDMContext();
const [visibleCount, setVisibleCount] = useState(MESSAGES_PER_PAGE);
const result = useMemo(() => {
const conversationData = allMessages.get(conversationId);
if (!conversationData) {
return {
messages: [],
hasMoreMessages: false,
totalCount: 0,
lastMessage: null,
lastActivity: 0,
};
}
const totalMessages = conversationData.messages.length;
const hasMore = totalMessages > visibleCount;
// Return the most recent N messages (slice from the end)
const visibleMessages = conversationData.messages.slice(-visibleCount);
return {
messages: visibleMessages,
hasMoreMessages: hasMore,
totalCount: totalMessages,
lastMessage: conversationData.lastMessage,
lastActivity: conversationData.lastActivity,
};
}, [allMessages, conversationId, visibleCount]);
const loadEarlierMessages = useCallback(() => {
setVisibleCount(prev => prev + MESSAGES_PER_PAGE);
}, []);
// Reset visible count when conversation changes
useEffect(() => {
setVisibleCount(MESSAGES_PER_PAGE);
}, [conversationId]);
return {
...result,
loadEarlierMessages,
};
}
+45
View File
@@ -0,0 +1,45 @@
import { useContext } from "react";
import { DMContext, DMContextType } from "@/contexts/DMContext";
/**
* Hook to access the direct messaging system.
*
* Provides access to conversations, message sending, loading states, and cache management.
* Must be used within a DMProvider.
*
* @example
* ```tsx
* import { useDMContext } from '@/hooks/useDMContext';
* import { MESSAGE_PROTOCOL } from '@/lib/dmConstants';
*
* function MyComponent() {
* const { conversations, sendMessage, isLoading } = useDMContext();
*
* // Send a message
* await sendMessage({
* recipientPubkey: 'hex-pubkey',
* content: 'Hello!',
* protocol: MESSAGE_PROTOCOL.NIP17
* });
*
* // Display conversations
* return (
* <div>
* {isLoading ? 'Loading...' : conversations.map(c => (
* <div key={c.pubkey}>{c.lastMessage?.decryptedContent}</div>
* ))}
* </div>
* );
* }
* ```
*
* @returns DMContextType - The direct messaging context
* @throws Error if used outside DMProvider
*/
export function useDMContext(): DMContextType {
const context = useContext(DMContext);
if (!context) {
throw new Error('useDMContext must be used within DMProvider');
}
return context;
}
+1 -1
View File
@@ -85,7 +85,7 @@ export function usePostComment() {
onSuccess: (_, { root }) => { onSuccess: (_, { root }) => {
// Invalidate and refetch comments // Invalidate and refetch comments
queryClient.invalidateQueries({ queryClient.invalidateQueries({
queryKey: ['comments', root instanceof URL ? root.toString() : root.id] queryKey: ['nostr', 'comments', root instanceof URL ? root.toString() : root.id]
}); });
}, },
}); });
+1 -1
View File
@@ -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 -1
View File
@@ -32,7 +32,7 @@
--input: 214.3 31.8% 91.4%; --input: 214.3 31.8% 91.4%;
--ring: 222.2 84% 4.9%; --ring: 222.2 84% 4.9%;
--radius: 0.5rem; --radius: 0.75rem;
--sidebar-background: 0 0% 98%; --sidebar-background: 0 0% 98%;
-2
View File
@@ -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" />
+6 -1
View File
@@ -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 (
-19
View File
@@ -1,19 +0,0 @@
{
"name": "mkstack",
"title": "MKStack",
"description": "Build Nostr apps in minutes with this React framework",
"uri": "git+https://gitlab.com/soapbox-pub/mkstack.git",
"image": "https://gitlab.com/-/project/69048882/uploads/0a9e3a19f2901d5c772952c1de10ce4f/image.png",
"commands": [
"npm",
"npx"
],
"tech": [
"react",
"typescript",
"tailwind",
"shadcn-ui",
"nostrify",
"vite"
]
}