Author SHA1 Message Date
Derek Ross 8a4f97beba fix: callback enhancements 2025-12-30 21:13:23 -05:00
Derek Ross ac88a3a5c1 fix: callback for non-mobile and localstorage 2025-12-30 20:31:46 -05:00
Derek Ross 86d3d67eef feat: add callback URL to nostrconnect URI 2025-12-30 13:53:37 -05:00
Derek Ross 2f6994f1e2 fix: add button on mobile web 2025-12-29 23:02:53 -05:00
Derek Ross ca1b0cd303 feat: add NIP-46 nostrconnect with QR code for web login 2025-12-29 15:07:33 -05: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
30 changed files with 1436 additions and 665 deletions

No files matched your search

+50 -15
View File
@@ -46,9 +46,11 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3.
- `useConversationMessages`: Hook exported from DMContext for paginated messages
- `/src/test/`: Testing utilities including TestApp component
- `/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
**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
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:
@@ -121,10 +123,6 @@ The AI assistant's behavior and knowledge is defined by the AGENTS.md file, whic
1. Edit AGENTS.md directly
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
This project comes with custom hooks for querying and publishing events on the Nostr network.
@@ -158,6 +156,7 @@ When implementing features that could use existing NIPs, follow this decision fr
- No existing NIP covers the core functionality
- The data structure is fundamentally different from existing patterns
- 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.
@@ -755,7 +754,7 @@ The project includes a complete direct messaging system with real-time updates,
For complete implementation guide including:
- Setup and configuration
- Sending messages and file attachments
- Sending messages and file attachments
- Using the `DMMessagingInterface` component
- Building custom messaging UIs
- Protocol comparison (NIP-04 vs NIP-17)
@@ -831,16 +830,46 @@ export function Post(/* ...props */) {
## App Configuration
The project includes an `AppProvider` that manages global application state including theme and relay configuration. The default configuration includes:
The project includes an `AppProvider` that manages global application state including theme and NIP-65 relay configuration. The default configuration includes:
```typescript
const defaultConfig: AppConfig = {
theme: "light",
relayUrl: "wss://relay.nostr.band",
relayMetadata: {
relays: [
{ url: 'wss://relay.ditto.pub', read: true, write: true },
{ url: 'wss://relay.nostr.band', read: true, write: true },
{ url: 'wss://relay.damus.io', read: true, write: true },
],
updatedAt: 0,
},
};
```
Preset relays are available including Ditto, Nostr.Band, Damus, and Primal. The app uses local storage to persist user preferences.
The app uses NIP-65 compatible relay management with automatic sync when users log in. Local storage persists user preferences and relay configurations.
### Relay Management
The project includes a complete NIP-65 relay management system:
- **RelayListManager**: Component for managing multiple relays with read/write permissions
- **NostrSync**: Automatically syncs user's NIP-65 relay list when they log in
- **Automatic Publishing**: Changes to relay configuration are automatically published as NIP-65 events when the user is logged in
Use the `RelayListManager` component to provide relay management interfaces:
```tsx
import { RelayListManager } from '@/components/RelayListManager';
function SettingsPage() {
return (
<div>
<h2>Relay Settings</h2>
<RelayListManager />
</div>
);
}
```
## Routing
@@ -894,10 +923,9 @@ The router includes automatic scroll-to-top functionality and a 404 NotFound pag
### Empty States and No Content Found
When no content is found (empty search results, no data available, etc.), display a minimalist empty state with the `RelaySelector` component. This allows users to easily switch relays to discover content from different sources.
When no content is found (empty search results, no data available, etc.), display a minimalist empty state with helpful messaging. The application uses NIP-65 relay management, so users can manage their relays through the settings or relay management interface.
```tsx
import { RelaySelector } from '@/components/RelaySelector';
import { Card, CardContent } from '@/components/ui/card';
// Empty state example
@@ -906,9 +934,8 @@ import { Card, CardContent } from '@/components/ui/card';
<CardContent className="py-12 px-8 text-center">
<div className="max-w-sm mx-auto space-y-6">
<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>
<RelaySelector className="w-full" />
</div>
</CardContent>
</Card>
@@ -927,7 +954,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
- 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
- Before finalizing, ask: "Would this design make Apple or Stripe designers pause and take notice?" If not, iterate until it does
@@ -1032,6 +1059,7 @@ When users specify color schemes:
There is an important distinction between **writing new tests** and **running existing tests**:
### 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:
1. **The user explicitly asks for tests** to be written in their message
@@ -1045,6 +1073,7 @@ There is an important distinction between **writing new tests** and **running ex
- Existing functionality needs verification
### 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.
- **You must run the test script** to validate your changes
@@ -1103,4 +1132,10 @@ Run available tools in this priority order:
- Fix any critical linting errors that would break functionality
- 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.
+73 -38
View File
@@ -1,42 +1,76 @@
### Direct Messaging on Nostr
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.
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.
## Quick Start
**The DM system is not enabled by default** - follow the setup instructions below to add messaging functionality to your application.
### 1. Enable Direct Messaging
## Setup Instructions
The `DMProvider` is already added to your app, but **disabled by default**. To enable messaging, pass `enabled: true` in the config:
### 1. Add DMProvider to Your App
First, add the `DMProvider` to your app's provider tree in `src/App.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';
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 (
<DMProvider config={{
enabled: true, // Enable the DM system
protocolMode: PROTOCOL_MODE.NIP17_ONLY
}}>
{/* Your app components */}
</DMProvider>
<UnheadProvider head={head}>
<AppProvider storageKey="nostr:app-config" defaultConfig={defaultConfig}>
<QueryClientProvider client={queryClient}>
<NostrLoginProvider storageKey='nostr:login'>
<NostrProvider>
<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.
- `protocolMode` (ProtocolMode, default: `PROTOCOL_MODE.NIP17_ONLY`) - Which protocols to support:
- `PROTOCOL_MODE.NIP04_ONLY` - Legacy encryption only
- `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.
### 2. Send Messages
## Quick Start
### 1. Send Messages
```tsx
import { useDMContext } from '@/contexts/DMContext';
import { useDMContext } from '@/hooks/useDMContext';
import { MESSAGE_PROTOCOL } from '@/lib/dmConstants';
function ComposeMessage({ recipientPubkey }: { recipientPubkey: string }) {
@@ -54,8 +88,8 @@ function ComposeMessage({ recipientPubkey }: { recipientPubkey: string }) {
return (
<form onSubmit={(e) => { e.preventDefault(); handleSend(); }}>
<textarea
value={content}
<textarea
value={content}
onChange={(e) => setContent(e.target.value)}
placeholder="Type a message..."
/>
@@ -65,10 +99,10 @@ function ComposeMessage({ recipientPubkey }: { recipientPubkey: string }) {
}
```
### 3. Display Conversations
### 2. Display Conversations
```tsx
import { useDMContext } from '@/contexts/DMContext';
import { useDMContext } from '@/hooks/useDMContext';
import { useAuthor } from '@/hooks/useAuthor';
import { genUserName } from '@/lib/genUserName';
@@ -82,7 +116,7 @@ function ConversationList({ onSelectConversation }: { onSelectConversation: (pub
return (
<div className="space-y-2">
{conversations.map((conversation) => (
<ConversationItem
<ConversationItem
key={conversation.pubkey}
conversation={conversation}
onClick={() => onSelectConversation(conversation.pubkey)}
@@ -92,8 +126,8 @@ function ConversationList({ onSelectConversation }: { onSelectConversation: (pub
);
}
function ConversationItem({ conversation, onClick }: {
conversation: ConversationSummary;
function ConversationItem({ conversation, onClick }: {
conversation: ConversationSummary;
onClick: () => void;
}) {
const author = useAuthor(conversation.pubkey);
@@ -119,10 +153,10 @@ function ConversationItem({ conversation, onClick }: {
}
```
### 4. Display Messages in a Conversation
### 3. Display Messages in a Conversation
```tsx
import { useConversationMessages } from '@/contexts/DMContext';
import { useConversationMessages } from '@/hooks/useConversationMessages';
import { useCurrentUser } from '@/hooks/useCurrentUser';
function MessageThread({ conversationPubkey }: { conversationPubkey: string }) {
@@ -136,12 +170,12 @@ function MessageThread({ conversationPubkey }: { conversationPubkey: string }) {
Load earlier messages
</button>
)}
{messages.map((message) => {
const isFromMe = message.pubkey === user?.pubkey;
return (
<div
<div
key={message.id}
className={cn(
"flex",
@@ -201,9 +235,10 @@ It requires no props and works automatically when wrapped in `DMProvider`.
## Sending Files with Messages
```tsx
import { useDMContext, type FileAttachment } from '@/contexts/DMContext';
import { useDMContext } from '@/hooks/useDMContext';
import { useUploadFile } from '@/hooks/useUploadFile';
import { MESSAGE_PROTOCOL } from '@/lib/dmConstants';
import type { FileAttachment } from '@/contexts/DMContext';
function ComposeWithFiles({ recipientPubkey }: { recipientPubkey: string }) {
const { sendMessage } = useDMContext();
@@ -217,7 +252,7 @@ function ComposeWithFiles({ recipientPubkey }: { recipientPubkey: string }) {
// Upload file if one is selected
if (selectedFile) {
const tags = await uploadFile(selectedFile);
attachments = [{
url: tags[0][1], // URL from first tag
mimeType: selectedFile.type,
@@ -240,19 +275,19 @@ function ComposeWithFiles({ recipientPubkey }: { recipientPubkey: string }) {
return (
<form onSubmit={(e) => { e.preventDefault(); handleSend(); }}>
<textarea
value={content}
<textarea
value={content}
onChange={(e) => setContent(e.target.value)}
placeholder="Type a message..."
/>
<input
type="file"
<input
type="file"
onChange={(e) => setSelectedFile(e.target.files?.[0] || null)}
/>
{selectedFile && <div>Selected: {selectedFile.name}</div>}
<button type="submit" disabled={isUploading}>
{isUploading ? 'Uploading...' : 'Send'}
</button>
@@ -321,7 +356,7 @@ if (scanProgress.nip17) {
### Clear Cache and Refresh
```tsx
import { useDMContext } from '@/contexts/DMContext';
import { useDMContext } from '@/hooks/useDMContext';
function SettingsButton() {
const { clearCacheAndRefetch } = useDMContext();
-1
View File
@@ -17,7 +17,6 @@ export default tseslint.config(
globals: globals.browser,
},
linterOptions: {
noInlineConfig: true, // Prevents all eslint-disable comments
reportUnusedDisableDirectives: "error", // Reports unused disable directives as errors
},
plugins: {
+106 -59
View File
@@ -11,8 +11,8 @@
"@fontsource-variable/inter": "^5.2.6",
"@getalby/sdk": "^5.1.1",
"@hookform/resolvers": "^3.9.0",
"@nostrify/nostrify": "^0.47.1",
"@nostrify/react": "^0.2.17",
"@nostrify/nostrify": "^0.48.2",
"@nostrify/react": "^0.2.20",
"@radix-ui/react-accordion": "^1.2.0",
"@radix-ui/react-alert-dialog": "^1.1.1",
"@radix-ui/react-aspect-ratio": "^1.1.0",
@@ -54,6 +54,7 @@
"lucide-react": "^0.462.0",
"nostr-tools": "^2.13.0",
"qrcode": "^1.5.4",
"qrcode.react": "^4.2.0",
"react": "^18.3.1",
"react-day-picker": "^8.10.1",
"react-dom": "^18.3.1",
@@ -1253,13 +1254,14 @@
}
},
"node_modules/@nostrify/nostrify": {
"version": "0.47.1",
"resolved": "https://registry.npmjs.org/@nostrify/nostrify/-/nostrify-0.47.1.tgz",
"integrity": "sha512-8jdAeKIyyDK/UQN92WgrQn9+B067HYcjfW35TpIjNLAT9qYe+KYFHaC9O6PD+I1DvLHziJMxk4Q18Fu4fqOiAQ==",
"version": "0.48.2",
"resolved": "https://registry.npmjs.org/@nostrify/nostrify/-/nostrify-0.48.2.tgz",
"integrity": "sha512-Zze3RASsgn4MLQCuC5I4XR0WJi9G3J8qZpVjVIPvkw6vbZRct++JgavcZSxwKjJH1hHq+8d90IrHMOrskNQ8NQ==",
"dependencies": {
"@nostrify/types": "0.36.7",
"@scure/base": "^1.2.6",
"@std/encoding": "npm:@jsr/std__encoding@^0.224.1",
"@nostrify/types": "0.36.8",
"@scure/base": "^2.0.0",
"@smithy/util-base64": "^4.3.0",
"@smithy/util-hex-encoding": "^4.2.0",
"@types/node": "^24.1.0",
"lru-cache": "^10.2.0",
"nostr-tools": "^2.13.0",
@@ -1269,18 +1271,18 @@
}
},
"node_modules/@nostrify/nostrify/node_modules/@scure/base": {
"version": "1.2.6",
"resolved": "https://registry.npmjs.org/@scure/base/-/base-1.2.6.tgz",
"integrity": "sha512-g/nm5FgUa//MCj1gV09zTJTaM6KBAHqLN907YVQqf7zC49+DcO4B1so4ZX07Ef10Twr6nuqYEH9GEggFXA4Fmg==",
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/@scure/base/-/base-2.0.0.tgz",
"integrity": "sha512-3E1kpuZginKkek01ovG8krQ0Z44E3DHPjc5S2rjJw9lZn3KSQOs8S7wqikF/AH7iRanHypj85uGyxk0XAyC37w==",
"license": "MIT",
"funding": {
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/@nostrify/nostrify/node_modules/@types/node": {
"version": "24.9.1",
"resolved": "https://registry.npmjs.org/@types/node/-/node-24.9.1.tgz",
"integrity": "sha512-QoiaXANRkSXK6p0Duvt56W208du4P9Uye9hWLWgGMDTEoKPhuenzNcC4vGUmrNkiOKTlIrBoyNQYNpSwfEZXSg==",
"version": "24.10.4",
"resolved": "https://registry.npmjs.org/@types/node/-/node-24.10.4.tgz",
"integrity": "sha512-vnDVpYPMzs4wunl27jHrfmwojOGKya0xyM3sH+UE5iv5uPS6vX7UIoh6m+vQc5LGBq52HBKPIn/zcSZVzeDEZg==",
"license": "MIT",
"dependencies": {
"undici-types": "~7.16.0"
@@ -1293,23 +1295,22 @@
"license": "MIT"
},
"node_modules/@nostrify/react": {
"version": "0.2.17",
"resolved": "https://registry.npmjs.org/@nostrify/react/-/react-0.2.17.tgz",
"integrity": "sha512-IG6XPiNBe1nDFZ055EnWufxASPjgOZ2cE53Hjanj5xQQURwzA946yMhDDzaHmD9lvoBYjuijopmTiyFk2RObHQ==",
"version": "0.2.20",
"resolved": "https://registry.npmjs.org/@nostrify/react/-/react-0.2.20.tgz",
"integrity": "sha512-Tvkdr5X+MQxh6CKKthk9Idch3vFp5nPcm57uJZJWrIqBtuj9jxMamM6uEo2lQAr0ugK52xDlyD50lRDRe0RMbQ==",
"dependencies": {
"@nostrify/nostrify": "0.47.1",
"@nostrify/types": "0.36.7",
"@nostrify/nostrify": "0.48.2",
"@nostrify/types": "0.36.8",
"@tanstack/react-query": "^5.69.0",
"happy-dom": "^17.4.4",
"nostr-tools": "^2.13.0",
"react": "^18.0.0",
"react-dom": "^18.0.0"
}
},
"node_modules/@nostrify/types": {
"version": "0.36.7",
"resolved": "https://registry.npmjs.org/@nostrify/types/-/types-0.36.7.tgz",
"integrity": "sha512-Jdf2eWdIzonMzic/st4ltre7XIcXVNTjmcbKpw4xGEfNmoq2Y4wj8KcSB6s0TUqxcLEyiXnyGP8EDx/gEVri9A=="
"version": "0.36.8",
"resolved": "https://registry.npmjs.org/@nostrify/types/-/types-0.36.8.tgz",
"integrity": "sha512-tmpz5pkU8oXu7+V1qxvAzuoo8s5x4Gvo7h+JRm+JAW6x/2VZ8aQoA54yhn89qZ9agciMJhVdhqCm1PlK55w17A=="
},
"node_modules/@pkgjs/parseargs": {
"version": "0.11.0",
@@ -3055,11 +3056,69 @@
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/@std/encoding": {
"name": "@jsr/std__encoding",
"version": "0.224.3",
"resolved": "https://npm.jsr.io/~/11/@jsr/std__encoding/0.224.3.tgz",
"integrity": "sha512-zAuX2QV1zwJ5RSmrnDGVerAtN3pBXpYYNlGzhERW9AiQ1UJd2/xruyB3i5NdTWy2OK2pjETswOj+0+prYTPlxQ=="
"node_modules/@smithy/is-array-buffer": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/@smithy/is-array-buffer/-/is-array-buffer-4.2.0.tgz",
"integrity": "sha512-DZZZBvC7sjcYh4MazJSGiWMI2L7E0oCiRHREDzIxi/M2LY79/21iXt6aPLHge82wi5LsuRF5A06Ds3+0mlh6CQ==",
"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/@swc/core": {
"version": "1.11.24",
@@ -5372,9 +5431,9 @@
}
},
"node_modules/glob": {
"version": "10.4.5",
"resolved": "https://registry.npmjs.org/glob/-/glob-10.4.5.tgz",
"integrity": "sha512-7Bv8RF0k6xjo7d4A/PxYLbUCfb6c+Vpd2/mB2yRDlew7Jb5hEXiCD9ibfO7wpk8i4sevK6DFny9h7EYbM3/sHg==",
"version": "10.5.0",
"resolved": "https://registry.npmjs.org/glob/-/glob-10.5.0.tgz",
"integrity": "sha512-DfXN8DfhJ7NH3Oe7cFmu3NCu1wKbkReJ8TorzSAFbSKrlNaQSKfIzqYqVY8zlbs2NLBbWpRiU52GX2PbaBVNkg==",
"license": "ISC",
"dependencies": {
"foreground-child": "^3.1.0",
@@ -5447,28 +5506,6 @@
"dev": true,
"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": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz",
@@ -5753,9 +5790,9 @@
"license": "MIT"
},
"node_modules/js-yaml": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz",
"integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==",
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.1.tgz",
"integrity": "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -6644,6 +6681,15 @@
"node": ">=10.13.0"
}
},
"node_modules/qrcode.react": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/qrcode.react/-/qrcode.react-4.2.0.tgz",
"integrity": "sha512-QpgqWi8rD9DsS9EP3z7BT+5lY5SFhsqGjpgW5DY/i3mK4M9DTBNz3ErMi8BWYEfI3L0d8GIbGmcdFAS1uIRGjA==",
"license": "ISC",
"peerDependencies": {
"react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
}
},
"node_modules/queue-microtask": {
"version": "1.2.3",
"resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz",
@@ -7883,9 +7929,9 @@
}
},
"node_modules/vite": {
"version": "6.3.5",
"resolved": "https://registry.npmjs.org/vite/-/vite-6.3.5.tgz",
"integrity": "sha512-cZn6NDFE7wdTpINgs++ZJ4N49W2vRp8LCKrn3Ob1kYNtOo21vfDoaV5GzBfLU4MovSAB8uNRm4jgzVQZ+mBzPQ==",
"version": "6.4.1",
"resolved": "https://registry.npmjs.org/vite/-/vite-6.4.1.tgz",
"integrity": "sha512-+Oxm7q9hDoLMyJOYfUYBuHQo+dkAloi33apOPP56pzj+vsdJDzr+j1NISE5pyaAuKL4A3UD34qd0lx5+kfKp2g==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -8096,6 +8142,7 @@
"version": "7.0.0",
"resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz",
"integrity": "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==",
"dev": true,
"license": "BSD-2-Clause",
"engines": {
"node": ">=12"
+3 -2
View File
@@ -13,8 +13,8 @@
"@fontsource-variable/inter": "^5.2.6",
"@getalby/sdk": "^5.1.1",
"@hookform/resolvers": "^3.9.0",
"@nostrify/nostrify": "^0.47.1",
"@nostrify/react": "^0.2.17",
"@nostrify/nostrify": "^0.48.2",
"@nostrify/react": "^0.2.20",
"@radix-ui/react-accordion": "^1.2.0",
"@radix-ui/react-alert-dialog": "^1.1.1",
"@radix-ui/react-aspect-ratio": "^1.1.0",
@@ -56,6 +56,7 @@
"lucide-react": "^0.462.0",
"nostr-tools": "^2.13.0",
"qrcode": "^1.5.4",
"qrcode.react": "^4.2.0",
"react": "^18.3.1",
"react-day-picker": "^8.10.1",
"react-dom": "^18.3.1",
+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 { Suspense } from 'react';
import NostrProvider from '@/components/NostrProvider';
import { NostrSync } from '@/components/NostrSync';
import { Toaster } from "@/components/ui/toaster";
import { TooltipProvider } from "@/components/ui/tooltip";
import { NostrLoginProvider } from '@nostrify/react/login';
import { AppProvider } from '@/components/AppProvider';
import { NWCProvider } from '@/contexts/NWCContext';
import { DMProvider, type DMConfig } from '@/contexts/DMContext';
import { AppConfig } from '@/contexts/AppContext';
import { PROTOCOL_MODE } from '@/lib/dmConstants';
import AppRouter from './AppRouter';
const head = createHead({
@@ -34,43 +33,31 @@ const queryClient = new QueryClient({
const defaultConfig: AppConfig = {
theme: "light",
relayUrl: "wss://relay.ditto.pub",
};
const presetRelays = [
{ url: 'wss://relay.ditto.pub', name: 'Ditto' },
{ url: 'wss://relay.nostr.band', name: 'Nostr.Band' },
{ url: 'wss://relay.damus.io', name: 'Damus' },
{ url: 'wss://relay.primal.net', name: 'Primal' },
];
const dmConfig: DMConfig = {
// Enable or disable DMs entirely
enabled: true, // Set to false to completely disable messaging functionality
// Choose one protocol mode:
// PROTOCOL_MODE.NIP04_ONLY - Force NIP-04 (legacy) only
// PROTOCOL_MODE.NIP17_ONLY - Force NIP-17 (private) only
// 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,
relayMetadata: {
relays: [
{ url: 'wss://relay.ditto.pub', read: true, write: true },
{ url: 'wss://relay.nostr.band', read: true, write: true },
{ url: 'wss://relay.damus.io', read: true, write: true },
],
updatedAt: 0,
},
};
export function App() {
return (
<UnheadProvider head={head}>
<AppProvider storageKey="nostr:app-config" defaultConfig={defaultConfig} presetRelays={presetRelays}>
<AppProvider storageKey="nostr:app-config" defaultConfig={defaultConfig}>
<QueryClientProvider client={queryClient}>
<NostrLoginProvider storageKey='nostr:login'>
<NostrProvider>
<NostrSync />
<NWCProvider>
<DMProvider config={dmConfig}>
<TooltipProvider>
<Toaster />
<Suspense>
<AppRouter />
</Suspense>
</TooltipProvider>
</DMProvider>
<TooltipProvider>
<Toaster />
<Suspense>
<AppRouter />
</Suspense>
</TooltipProvider>
</NWCProvider>
</NostrProvider>
</NostrLoginProvider>
+2 -2
View File
@@ -2,8 +2,8 @@ import { BrowserRouter, Route, Routes } from "react-router-dom";
import { ScrollToTop } from "./components/ScrollToTop";
import Index from "./pages/Index";
import Messages from "./pages/Messages";
import { NIP19Page } from "./pages/NIP19Page";
import { RemoteLoginSuccess } from "./pages/RemoteLoginSuccess";
import NotFound from "./pages/NotFound";
export function AppRouter() {
@@ -12,7 +12,7 @@ export function AppRouter() {
<ScrollToTop />
<Routes>
<Route path="/" element={<Index />} />
<Route path="/messages" element={<Messages />} />
<Route path="/remoteloginsuccess" element={<RemoteLoginSuccess />} />
{/* NIP-19 route for npub1, note1, naddr1, nevent1, nprofile1 */}
<Route path="/:nip19" element={<NIP19Page />} />
{/* ADD ALL CUSTOM ROUTES ABOVE THE CATCH-ALL "*" ROUTE */}
+14 -8
View File
@@ -1,7 +1,7 @@
import { ReactNode, useEffect } from 'react';
import { z } from 'zod';
import { useLocalStorage } from '@/hooks/useLocalStorage';
import { AppContext, type AppConfig, type AppContextType, type Theme } from '@/contexts/AppContext';
import { AppContext, type AppConfig, type AppContextType, type Theme, type RelayMetadata } from '@/contexts/AppContext';
interface AppProviderProps {
children: ReactNode;
@@ -9,14 +9,22 @@ interface AppProviderProps {
storageKey: string;
/** Default app configuration */
defaultConfig: AppConfig;
/** Optional list of preset relays to display in the RelaySelector */
presetRelays?: { name: string; url: string }[];
}
// Zod schema for RelayMetadata validation
const RelayMetadataSchema = z.object({
relays: z.array(z.object({
url: z.string().url(),
read: z.boolean(),
write: z.boolean(),
})),
updatedAt: z.number(),
}) satisfies z.ZodType<RelayMetadata>;
// Zod schema for AppConfig validation
const AppConfigSchema = z.object({
theme: z.enum(['dark', 'light', 'system']),
relayUrl: z.string().url(),
relayMetadata: RelayMetadataSchema,
}) satisfies z.ZodType<AppConfig>;
export function AppProvider(props: AppProviderProps) {
@@ -24,7 +32,6 @@ export function AppProvider(props: AppProviderProps) {
children,
storageKey,
defaultConfig,
presetRelays,
} = props;
// App configuration state with localStorage persistence
@@ -50,7 +57,6 @@ export function AppProvider(props: AppProviderProps) {
const appContextValue: AppContextType = {
config,
updateConfig,
presetRelays,
};
// Apply theme effects to document
@@ -90,11 +96,11 @@ function useApplyTheme(theme: Theme) {
if (theme !== 'system') return;
const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
const handleChange = () => {
const root = window.document.documentElement;
root.classList.remove('light', 'dark');
const systemTheme = mediaQuery.matches ? 'dark' : 'light';
root.classList.add(systemTheme);
};
@@ -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 { useCurrentUser } from '@/hooks/useCurrentUser';
import { useNostr } from '@nostrify/react';
@@ -11,6 +11,7 @@ import { NSecSigner, type NostrEvent } from '@nostrify/nostrify';
import { generateSecretKey } from 'nostr-tools';
import type { MessageProtocol } from '@/lib/dmConstants';
import { MESSAGE_PROTOCOL } from '@/lib/dmConstants';
import { DMContext, DMContextType, FileAttachment } from '@/contexts/DMContext';
// ============================================================================
// DM Types and Constants
@@ -117,172 +118,6 @@ const createErrorLogger = (name: string) => {
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 {
enabled?: boolean;
protocolMode?: ProtocolMode;
@@ -297,55 +132,12 @@ interface DMProviderProps {
// 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
*/
function prepareMessageContent(content: string, attachments: FileAttachment[] = []): string {
if (attachments.length === 0) return content;
const fileUrls = attachments.map(file => file.url).join('\n');
return content ? `${content}\n\n${fileUrls}` : fileUrls;
}
@@ -384,10 +176,10 @@ export function DMProvider({ children, config }: DMProviderProps) {
const { config: appConfig } = useAppContext();
const userPubkey = useMemo(() => user?.pubkey, [user?.pubkey]);
// Track relay URL to detect changes
const previousRelayUrl = useRef<string>(appConfig.relayUrl);
// Track relay metadata to detect changes
const previousRelayMetadata = useRef(appConfig.relayMetadata);
// Determine if NIP-17 is enabled based on protocol mode
const enableNIP17 = protocolMode !== PROTOCOL_MODE.NIP04_ONLY;
@@ -418,8 +210,8 @@ export function DMProvider({ children, config }: DMProviderProps) {
// ============================================================================
// Send NIP-04 Message (internal)
const sendNIP4Message = useMutation<NostrEvent, Error, {
recipientPubkey: string;
const sendNIP4Message = useMutation<NostrEvent, Error, {
recipientPubkey: string;
content: string;
attachments?: FileAttachment[];
}>({
@@ -462,8 +254,8 @@ export function DMProvider({ children, config }: DMProviderProps) {
});
// Send NIP-17 Message (internal)
const sendNIP17Message = useMutation<NostrEvent, Error, {
recipientPubkey: string;
const sendNIP17Message = useMutation<NostrEvent, Error, {
recipientPubkey: string;
content: string;
attachments?: FileAttachment[];
}>({
@@ -478,7 +270,7 @@ export function DMProvider({ children, config }: DMProviderProps) {
// Step 1: Create the inner Kind 14 Private Direct Message
const now = Math.floor(Date.now() / 1000);
// Generate randomized timestamps for gift wraps (NIP-59 metadata privacy)
// Randomize within ±2 days in the PAST only (relays reject future timestamps > +30min)
const randomizeTimestamp = (baseTime: number) => {
@@ -528,11 +320,11 @@ export function DMProvider({ children, config }: DMProviderProps) {
// Step 3: Create TWO Kind 1059 Gift Wrap events
// Per NIP-17/NIP-59: Gift wraps MUST be signed with random, ephemeral keys
// to hide the sender's identity and provide - some - metadata privacy
// Generate random secret keys for each gift wrap
const recipientRandomKey = generateSecretKey();
const senderRandomKey = generateSecretKey();
// Create signers with the random keys
const recipientRandomSigner = new NSecSigner(recipientRandomKey);
const senderRandomSigner = new NSecSigner(senderRandomKey);
@@ -565,15 +357,15 @@ export function DMProvider({ children, config }: DMProviderProps) {
nostr.event(recipientGiftWrap),
nostr.event(senderGiftWrap),
]);
// Check for failures and log detailed errors
const recipientResult = results[0];
const senderResult = results[1];
if (recipientResult.status === 'rejected') {
console.error('[DM] Failed to publish recipient gift wrap');
console.error('[DM] Recipient gift wrap event:', recipientGiftWrap);
// Try to extract detailed errors from AggregateError
const error = recipientResult.reason;
if (error && typeof error === 'object' && 'errors' in error) {
@@ -582,11 +374,11 @@ export function DMProvider({ children, config }: DMProviderProps) {
console.error('[DM] Recipient error:', error);
}
}
if (senderResult.status === 'rejected') {
console.error('[DM] Failed to publish sender gift wrap');
console.error('[DM] Sender gift wrap event:', senderGiftWrap);
// Try to extract detailed errors from AggregateError
const error = senderResult.reason;
if (error && typeof error === 'object' && 'errors' in error) {
@@ -595,7 +387,7 @@ export function DMProvider({ children, config }: DMProviderProps) {
console.error('[DM] Sender error:', error);
}
}
// If both failed, throw error
if (recipientResult.status === 'rejected' && senderResult.status === 'rejected') {
throw new Error(`Both gift wraps rejected. Recipient: ${recipientResult.reason}, Sender: ${senderResult.reason}`);
@@ -686,7 +478,7 @@ export function DMProvider({ children, config }: DMProviderProps) {
let allNIP17Events: NostrEvent[] = [];
let processedMessages = 0;
// Adjust since timestamp to account for NIP-17 timestamp fuzzing (±2 days)
// We need to query from (lastSync - 2 days) to catch messages with randomized past timestamps
// This may fetch duplicates, but they're filtered by message ID in addMessageToState
@@ -921,7 +713,7 @@ export function DMProvider({ children, config }: DMProviderProps) {
const existingMessageIds = new Set(
existing.messages.map(msg => msg.originalGiftWrapId || msg.id)
);
const newMessages = value.messages.filter(msg =>
const newMessages = value.messages.filter(msg =>
!existingMessageIds.has(msg.originalGiftWrapId || msg.id)
);
@@ -1260,7 +1052,7 @@ export function DMProvider({ children, config }: DMProviderProps) {
if (!sinceTimestamp && lastSync.nip17) {
subscriptionSince = lastSync.nip17 - DM_CONSTANTS.SUBSCRIPTION_OVERLAP_SECONDS;
}
// Adjust for NIP-17 timestamp fuzzing (±2 days)
// Subscribe from (lastSync - 2 days) to catch messages with randomized past timestamps
const TWO_DAYS_IN_SECONDS = 2 * 24 * 60 * 60;
@@ -1309,7 +1101,7 @@ export function DMProvider({ children, config }: DMProviderProps) {
try {
const { readMessagesFromDB } = await import('@/lib/dmMessageStore');
const cachedStore = await readMessagesFromDB(userPubkey);
if (!cachedStore || Object.keys(cachedStore.participants).length === 0) {
@@ -1330,13 +1122,13 @@ export function DMProvider({ children, config }: DMProviderProps) {
// Decrypt based on message kind
let decryptedContent: string | undefined;
let error: string | undefined;
if (msg.kind === 4) {
// NIP-04 message
const otherPubkey = msg.pubkey === user?.pubkey
const otherPubkey = msg.pubkey === user?.pubkey
? msg.tags.find(([name]) => name === 'p')?.[1]
: msg.pubkey;
if (otherPubkey && user?.signer?.nip04) {
try {
decryptedContent = await user.signer.nip04.decrypt(otherPubkey, msg.content);
@@ -1350,7 +1142,7 @@ export function DMProvider({ children, config }: DMProviderProps) {
try {
const sealContent = await user.signer.nip44.decrypt(msg.pubkey, msg.content);
const decryptedEvent = JSON.parse(sealContent) as NostrEvent;
// Keep seal structure but add decryptedEvent for access to inner fields
return {
...msg,
@@ -1362,7 +1154,7 @@ export function DMProvider({ children, config }: DMProviderProps) {
}
}
}
return {
...msg,
id: msg.id || `missing-${msg.kind}-${msg.created_at}-${msg.pubkey.substring(0, 8)}-${msg.content?.substring(0, 16) || 'nocontent'}`,
@@ -1405,17 +1197,17 @@ export function DMProvider({ children, config }: DMProviderProps) {
try {
// ===== PHASE 1: Load cache and show immediately =====
const { nip4Since, nip17Since } = await loadAllCachedMessages();
// Mark as completed BEFORE releasing isLoading to prevent re-trigger
setHasInitialLoadCompleted(true);
// Show cached messages immediately! Don't wait for relays
setLoadingPhase(LOADING_PHASES.READY);
setIsLoading(false);
// ===== PHASE 2: Query relays in background (non-blocking, parallel) =====
setLoadingPhase(LOADING_PHASES.RELAYS);
// Run NIP-04 and NIP-17 queries IN PARALLEL
const [nip4Result, nip17Result] = await Promise.all([
queryRelaysForMessagesSince(MESSAGE_PROTOCOL.NIP04, nip4Since),
@@ -1469,7 +1261,7 @@ export function DMProvider({ children, config }: DMProviderProps) {
setSubscriptions({ isNIP4Connected: false, isNIP17Connected: false });
setScanProgress({ nip4: null, nip17: null });
setLoadingPhase(LOADING_PHASES.IDLE);
// Trigger reload by setting hasInitialLoadCompleted to false
setHasInitialLoadCompleted(false);
} catch (error) {
@@ -1487,7 +1279,7 @@ export function DMProvider({ children, config }: DMProviderProps) {
// Cleanup effect
useEffect(() => {
if (!enabled) return;
return () => {
if (nip4SubscriptionRef.current) {
nip4SubscriptionRef.current.close();
@@ -1503,7 +1295,7 @@ export function DMProvider({ children, config }: DMProviderProps) {
// Cleanup subscriptions
useEffect(() => {
if (!enabled) return;
return () => {
if (nip4SubscriptionRef.current) {
nip4SubscriptionRef.current.close();
@@ -1520,14 +1312,14 @@ export function DMProvider({ children, config }: DMProviderProps) {
// Detect relay changes and reload messages
useEffect(() => {
const relayChanged = previousRelayUrl.current !== appConfig.relayUrl;
previousRelayUrl.current = appConfig.relayUrl;
const relayChanged = JSON.stringify(previousRelayMetadata.current) !== JSON.stringify(appConfig.relayMetadata);
previousRelayMetadata.current = appConfig.relayMetadata;
if (relayChanged && enabled && userPubkey && hasInitialLoadCompleted) {
clearCacheAndRefetch();
}
}, [enabled, userPubkey, appConfig.relayUrl, hasInitialLoadCompleted, clearCacheAndRefetch]);
}, [enabled, userPubkey, appConfig.relayMetadata, hasInitialLoadCompleted, clearCacheAndRefetch]);
// Detect hard refresh shortcut (Ctrl+Shift+R / Cmd+Shift+R) to clear cache
useEffect(() => {
@@ -1669,14 +1461,14 @@ export function DMProvider({ children, config }: DMProviderProps) {
}, [enabled, messages, shouldSaveImmediately, writeAllMessagesToStore, triggerDebouncedWrite]);
// Send message
const sendMessage = useCallback(async (params: {
recipientPubkey: string;
content: string;
const sendMessage = useCallback(async (params: {
recipientPubkey: string;
content: string;
protocol?: MessageProtocol;
attachments?: FileAttachment[];
}) => {
if (!enabled) return;
const { recipientPubkey, content, protocol = MESSAGE_PROTOCOL.NIP04, attachments } = params;
if (!userPubkey) return;
+24 -18
View File
@@ -1,5 +1,5 @@
import React, { useEffect, useRef } from 'react';
import { NostrEvent, NPool, NRelay1 } from '@nostrify/nostrify';
import { NostrEvent, NostrFilter, NPool, NRelay1 } from '@nostrify/nostrify';
import { NostrContext } from '@nostrify/react';
import { useQueryClient } from '@tanstack/react-query';
import { useAppContext } from '@/hooks/useAppContext';
@@ -10,7 +10,7 @@ interface NostrProviderProps {
const NostrProvider: React.FC<NostrProviderProps> = (props) => {
const { children } = props;
const { config, presetRelays } = useAppContext();
const { config } = useAppContext();
const queryClient = useQueryClient();
@@ -18,13 +18,13 @@ const NostrProvider: React.FC<NostrProviderProps> = (props) => {
const pool = useRef<NPool | undefined>(undefined);
// 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(() => {
relayUrl.current = config.relayUrl;
relayMetadata.current = config.relayMetadata;
queryClient.invalidateQueries({ queryKey: ['nostr'] });
}, [config.relayUrl, queryClient]);
}, [config.relayMetadata, queryClient]);
// Initialize NPool only once
if (!pool.current) {
@@ -32,21 +32,27 @@ const NostrProvider: React.FC<NostrProviderProps> = (props) => {
open(url: string) {
return new NRelay1(url);
},
reqRouter(filters) {
return new Map([[relayUrl.current, filters]]);
reqRouter(filters: NostrFilter[]) {
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) {
// Publish to the selected relay
const allRelays = new Set<string>([relayUrl.current]);
// Get write relays from metadata
const writeRelays = relayMetadata.current.relays
.filter(r => r.write)
.map(r => r.url);
// Also publish to the preset relays, capped to 5
for (const { url } of (presetRelays ?? [])) {
allRelays.add(url);
if (allRelays.size >= 5) {
break;
}
}
const allRelays = new Set<string>(writeRelays);
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;
}
+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>
);
}
-4
View File
@@ -10,7 +10,6 @@ import {
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu.tsx';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar.tsx';
import { RelaySelector } from '@/components/RelaySelector';
import { WalletModal } from '@/components/WalletModal';
import { useLoggedInAccounts, type Account } from '@/hooks/useLoggedInAccounts';
import { genUserName } from '@/lib/genUserName';
@@ -43,9 +42,6 @@ export function AccountSwitcher({ onAddAccountClick }: AccountSwitcherProps) {
</button>
</DropdownMenuTrigger>
<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>
{otherUsers.map((user) => (
<DropdownMenuItem
+221 -48
View File
@@ -1,14 +1,21 @@
// 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.
import React, { useRef, useState, useEffect } from 'react';
import { Shield, Upload, AlertTriangle, UserPlus, KeyRound, Sparkles, Cloud } from 'lucide-react';
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { QRCodeSVG } from 'qrcode.react';
import { Shield, Upload, AlertTriangle, UserPlus, KeyRound, Sparkles, Loader2, Copy, Check, ChevronDown, ChevronUp, Link, ExternalLink } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Dialog, DialogContent, DialogHeader, DialogDescription } from "@/components/ui/dialog";
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { useLoginActions } from '@/hooks/useLoginActions';
import {
useLoginActions,
generateNostrConnectParams,
generateNostrConnectURI,
type NostrConnectParams,
} from '@/hooks/useLoginActions';
import { useIsMobile } from '@/hooks/useIsMobile';
import { cn } from '@/lib/utils';
interface LoginDialogProps {
@@ -23,7 +30,7 @@ const validateNsec = (nsec: string) => {
};
const validateBunkerUri = (uri: string) => {
return uri.startsWith('bunker://');
return uri.startsWith('bunker://') || uri.startsWith('nostrconnect://');
};
const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onSignup }) => {
@@ -31,6 +38,12 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
const [isFileLoading, setIsFileLoading] = useState(false);
const [nsec, setNsec] = useState('');
const [bunkerUri, setBunkerUri] = useState('');
const [nostrConnectParams, setNostrConnectParams] = useState<NostrConnectParams | null>(null);
const [nostrConnectUri, setNostrConnectUri] = useState<string>('');
const [isWaitingForConnect, setIsWaitingForConnect] = useState(false);
const [connectError, setConnectError] = useState<string | null>(null);
const [copied, setCopied] = useState(false);
const [showBunkerInput, setShowBunkerInput] = useState(false);
const [errors, setErrors] = useState<{
nsec?: string;
bunker?: string;
@@ -38,17 +51,63 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
extension?: string;
}>({});
const fileInputRef = useRef<HTMLInputElement>(null);
const abortControllerRef = useRef<AbortController | null>(null);
const login = useLoginActions();
// Check if on mobile device
const isMobile = useIsMobile();
// Check if extension is available
const hasExtension = 'nostr' in window;
// Generate nostrconnect params (sync) - just creates the QR code data
const generateConnectSession = useCallback(() => {
const relayUrl = login.getRelayUrl();
const params = generateNostrConnectParams([relayUrl]);
const uri = generateNostrConnectURI(params, 'MKStack');
setNostrConnectParams(params);
setNostrConnectUri(uri);
setConnectError(null);
}, [login]);
// Start listening for connection (async) - runs after params are set
useEffect(() => {
if (!nostrConnectParams || isWaitingForConnect) return;
const startListening = async () => {
setIsWaitingForConnect(true);
abortControllerRef.current = new AbortController();
try {
await login.nostrconnect(nostrConnectParams);
onLogin();
onClose();
} catch (error) {
console.error('Nostrconnect failed:', error);
setConnectError(error instanceof Error ? error.message : 'Connection failed');
setIsWaitingForConnect(false);
}
};
startListening();
}, [nostrConnectParams, login, onLogin, onClose, isWaitingForConnect]);
// Reset all state when dialog opens/closes
useEffect(() => {
if (isOpen) {
// Reset state when dialog opens
if (!isOpen) {
// Reset state when dialog closes
setIsLoading(false);
setIsFileLoading(false);
setNsec('');
setBunkerUri('');
setNostrConnectParams(null);
setNostrConnectUri('');
setIsWaitingForConnect(false);
setConnectError(null);
setShowBunkerInput(false);
setErrors({});
if (abortControllerRef.current) {
abortControllerRef.current.abort();
}
// Reset file input
if (fileInputRef.current) {
fileInputRef.current.value = '';
@@ -56,6 +115,29 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
}
}, [isOpen]);
// Retry connection with new params
const handleRetry = useCallback(() => {
setNostrConnectParams(null);
setNostrConnectUri('');
setIsWaitingForConnect(false);
setConnectError(null);
// Generate new session after state clears
setTimeout(() => generateConnectSession(), 0);
}, [generateConnectSession]);
const handleCopyUri = async () => {
await navigator.clipboard.writeText(nostrConnectUri);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
};
// Open the nostrconnect URI in the system - this will launch a signer app like Amber if installed
const handleOpenSignerApp = () => {
if (!nostrConnectUri) return;
// On mobile, this will trigger the system to find an app that handles nostrconnect:// URIs
window.location.href = nostrConnectUri;
};
const handleExtensionLogin = async () => {
setIsLoading(true);
setErrors(prev => ({ ...prev, extension: undefined }));
@@ -69,8 +151,6 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
onClose();
} catch (e: unknown) {
const error = e as Error;
console.error('Bunker login failed:', error);
console.error('Nsec login failed:', error);
console.error('Extension login failed:', error);
setErrors(prev => ({
...prev,
@@ -118,7 +198,7 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
}
if (!validateBunkerUri(bunkerUri)) {
setErrors(prev => ({ ...prev, bunker: 'Invalid bunker URI format. Must start with bunker://' }));
setErrors(prev => ({ ...prev, bunker: 'Invalid URI format. Must start with bunker:// or nostrconnect://' }));
return;
}
@@ -177,7 +257,7 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
}
};
const defaultTab = 'nostr' in window ? 'extension' : 'key';
const defaultTab = hasExtension ? 'extension' : 'connect';
return (
<Dialog open={isOpen} onOpenChange={onClose}>
@@ -226,21 +306,30 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
</div>
{/* Login Methods */}
<Tabs defaultValue={defaultTab} className="w-full">
<Tabs
defaultValue={defaultTab}
className="w-full"
onValueChange={(value) => {
if (value === 'connect' && !nostrConnectParams && !connectError) {
generateConnectSession();
}
}}
>
<TabsList className="grid w-full grid-cols-3 bg-muted/80 rounded-lg mb-4">
<TabsTrigger value="extension" className="flex items-center gap-2">
<Shield className="w-4 h-4" />
<span>Extension</span>
</TabsTrigger>
<TabsTrigger value="connect" className="flex items-center gap-2">
<Link className="w-4 h-4" />
<span>Connect</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 && (
<Alert variant="destructive">
@@ -265,6 +354,123 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
</div>
</TabsContent>
<TabsContent value='connect' className='space-y-4'>
{/* Nostrconnect Section */}
<div className='flex flex-col items-center space-y-4'>
{connectError ? (
<div className='flex flex-col items-center space-y-4 py-4'>
<p className='text-sm text-red-500 text-center'>{connectError}</p>
<Button variant='outline' onClick={handleRetry}>
Try Again
</Button>
</div>
) : nostrConnectUri ? (
<>
{/* QR Code - only show on desktop */}
{!isMobile && (
<div className='p-4 bg-white rounded-xl'>
<QRCodeSVG
value={nostrConnectUri}
size={180}
level='M'
includeMargin={false}
/>
</div>
)}
{/* Status message */}
<div className='flex items-center gap-2 text-sm text-muted-foreground'>
{isWaitingForConnect ? (
<>
<Loader2 className='w-4 h-4 animate-spin' />
<span>Waiting for connection...</span>
</>
) : (
<span>{isMobile ? 'Open your signer app to connect' : 'Scan with your signer app'}</span>
)}
</div>
{/* Open Signer App button - primary action on mobile */}
{isMobile && (
<Button
className='w-full gap-2 py-6 rounded-full'
onClick={handleOpenSignerApp}
>
<ExternalLink className='w-5 h-5' />
Open Signer App
</Button>
)}
{/* Copy button */}
<Button
variant='outline'
size={isMobile ? 'default' : 'sm'}
className={isMobile ? 'w-full gap-2 rounded-full' : 'gap-2'}
onClick={handleCopyUri}
>
{copied ? (
<>
<Check className='w-4 h-4' />
Copied!
</>
) : (
<>
<Copy className='w-4 h-4' />
Copy Connection String
</>
)}
</Button>
</>
) : (
<div className='flex items-center justify-center h-[100px]'>
<Loader2 className='w-8 h-8 animate-spin text-muted-foreground' />
</div>
)}
</div>
{/* Manual URI input section - collapsible */}
<div className='pt-4 border-t border-gray-200 dark:border-gray-700'>
<button
type='button'
onClick={() => setShowBunkerInput(!showBunkerInput)}
className='flex items-center justify-center gap-2 w-full text-sm text-muted-foreground hover:text-foreground transition-colors py-2'
>
<span>Manual bunker connection</span>
{showBunkerInput ? (
<ChevronUp className='w-4 h-4' />
) : (
<ChevronDown className='w-4 h-4' />
)}
</button>
{showBunkerInput && (
<div className='space-y-3 mt-3'>
<div className='space-y-2'>
<Input
id='connectBunkerUri'
value={bunkerUri}
onChange={(e) => setBunkerUri(e.target.value)}
className='rounded-lg border-gray-300 dark:border-gray-700 focus-visible:ring-primary text-sm'
placeholder='bunker://'
/>
{bunkerUri && !validateBunkerUri(bunkerUri) && (
<p className='text-red-500 text-xs'>URI must start with bunker:// or nostrconnect://</p>
)}
</div>
<Button
className='w-full rounded-full py-4'
variant='outline'
onClick={handleBunkerLogin}
disabled={isLoading || !bunkerUri.trim() || !validateBunkerUri(bunkerUri)}
>
{isLoading ? 'Connecting...' : 'Connect with Bunker'}
</Button>
</div>
)}
</div>
</TabsContent>
<TabsContent value='key' className='space-y-4'>
<div className='space-y-4'>
<div className='space-y-2'>
@@ -333,39 +539,6 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
</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>
</DialogContent>
+2 -1
View File
@@ -1,5 +1,6 @@
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 { useAuthor } from '@/hooks/useAuthor';
import { genUserName } from '@/lib/genUserName';
+1 -1
View File
@@ -1,6 +1,6 @@
import { useMemo, useState, memo } from 'react';
import { AlertTriangle, Info, Loader2 } from 'lucide-react';
import { useDMContext } from '@/contexts/DMContext';
import { useDMContext } from '@/hooks/useDMContext';
import { useAuthor } from '@/hooks/useAuthor';
import { genUserName } from '@/lib/genUserName';
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 { DMChatArea } from '@/components/dm/DMChatArea';
import { DMStatusInfo } from '@/components/dm/DMStatusInfo';
import { useDMContext } from '@/contexts/DMContext';
import { useDMContext } from '@/hooks/useDMContext';
import { useIsMobile } from '@/hooks/useIsMobile';
import { cn } from '@/lib/utils';
import {
+1 -1
View File
@@ -1,6 +1,6 @@
import { useState } from '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 { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
+9 -4
View File
@@ -2,11 +2,18 @@ import { createContext } from "react";
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 {
/** Current theme */
theme: Theme;
/** Selected relay URL */
relayUrl: string;
/** NIP-65 relay list metadata */
relayMetadata: RelayMetadata;
}
export interface AppContextType {
@@ -14,8 +21,6 @@ export interface AppContextType {
config: AppConfig;
/** Update configuration using a callback that receives current config and returns new config */
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);
+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;
}
+124
View File
@@ -1,11 +1,67 @@
import { NConnectSigner, NSecSigner } from '@nostrify/nostrify';
import { useNostr } from '@nostrify/react';
import { NLogin, useNostrLogin } from '@nostrify/react/login';
import { generateSecretKey, getPublicKey } from 'nostr-tools';
import { nip19 } from 'nostr-tools';
import { useAppContext } from '@/hooks/useAppContext';
// NOTE: This file should not be edited except for adding new login methods.
/** Check if running on actual mobile device (not just small screen) */
function isMobileDevice(): boolean {
if (typeof navigator === 'undefined') return false;
return /Android|iPhone|iPad|iPod/i.test(navigator.userAgent);
}
/** Parameters for initiating a nostrconnect:// session */
export interface NostrConnectParams {
clientSecretKey: Uint8Array;
clientPubkey: string;
secret: string;
relays: string[];
}
/** Generates a nostrconnect:// URI for QR code display */
export function generateNostrConnectURI(params: NostrConnectParams, appName?: string): string {
const searchParams = new URLSearchParams();
for (const relay of params.relays) {
searchParams.append('relay', relay);
}
searchParams.set('secret', params.secret);
if (appName) {
searchParams.set('name', appName);
}
// Add callback URL only on mobile devices (not desktop QR code scanning)
// When scanning QR from desktop, the signer app is on the phone but the session is on desktop
if (typeof window !== 'undefined' && isMobileDevice()) {
searchParams.set('callback', `${window.location.origin}/remoteloginsuccess`);
}
return `nostrconnect://${params.clientPubkey}?${searchParams.toString()}`;
}
/** Generates random parameters for a nostrconnect session */
export function generateNostrConnectParams(relays: string[]): NostrConnectParams {
const clientSecretKey = generateSecretKey();
const clientPubkey = getPublicKey(clientSecretKey);
const secret = crypto.randomUUID().slice(0, 8);
return {
clientSecretKey,
clientPubkey,
secret,
relays,
};
}
export function useLoginActions() {
const { nostr } = useNostr();
const { logins, addLogin, removeLogin } = useNostrLogin();
const { config } = useAppContext();
return {
// Login with a Nostr secret key
@@ -23,6 +79,74 @@ export function useLoginActions() {
const login = await NLogin.fromExtension();
addLogin(login);
},
// Login via nostrconnect:// (client-initiated NIP-46)
// The client displays a QR code and waits for the remote signer to connect
async nostrconnect(params: NostrConnectParams): Promise<void> {
const clientSigner = new NSecSigner(params.clientSecretKey);
const clientPubkey = getPublicKey(params.clientSecretKey);
// Create a relay group for the connection
const relayGroup = nostr.group(params.relays);
// Wait for the connect response from the remote signer
// We subscribe to kind 24133 events p-tagged to our client pubkey
const signal = AbortSignal.timeout(120_000); // 2 minute timeout
const sub = relayGroup.req(
[{ kinds: [24133], '#p': [clientPubkey], limit: 1 }],
{ signal }
);
for await (const msg of sub) {
if (msg[0] === 'CLOSED') {
throw new Error('Connection closed before remote signer responded');
}
if (msg[0] === 'EVENT') {
const event = msg[2];
// Decrypt the response
const decrypted = await clientSigner.nip44!.decrypt(event.pubkey, event.content);
const response = JSON.parse(decrypted);
// Validate the secret matches
if (response.result !== params.secret && response.result !== 'ack') {
continue; // Not our response, keep waiting
}
// Success! The remote signer has connected
// Now create the NConnectSigner for ongoing use
const bunkerPubkey = event.pubkey;
const signer = new NConnectSigner({
relay: relayGroup,
pubkey: bunkerPubkey,
signer: clientSigner,
timeout: 60_000,
});
// Get the actual user pubkey
const userPubkey = await signer.getPublicKey();
// Create and add the login
const login = new NLogin('bunker', userPubkey, {
bunkerPubkey,
clientNsec: nip19.nsecEncode(params.clientSecretKey),
relays: params.relays,
});
addLogin(login);
return;
}
}
throw new Error('Timeout waiting for remote signer');
},
// Get the current relay URL for nostrconnect
getRelayUrl(): string {
// Get the first write-enabled relay, or fallback to a default
const writeRelay = config.relayMetadata?.relays?.find(r => r.write);
return writeRelay?.url ?? 'wss://relay.nostr.band';
},
// Log out the current user
async logout(): Promise<void> {
const login = logins[0];
+1 -1
View File
@@ -85,7 +85,7 @@ export function usePostComment() {
onSuccess: (_, { root }) => {
// Invalidate and refetch comments
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,
event: event,
amount: zapAmount,
relays: [config.relayUrl],
relays: config.relayMetadata.relays.map(r => r.url),
comment
});
-2
View File
@@ -1,6 +1,5 @@
import { useSeoMeta } from '@unhead/react';
import { DMMessagingInterface } from '@/components/dm/DMMessagingInterface';
import { RelaySelector } from '@/components/RelaySelector';
const Messages = () => {
useSeoMeta({
@@ -14,7 +13,6 @@ const Messages = () => {
{/* Header */}
<div className="flex items-center justify-between mb-4">
<h1 className="text-2xl font-semibold">Messages</h1>
<RelaySelector />
</div>
<DMMessagingInterface className="flex-1" />
+116
View File
@@ -0,0 +1,116 @@
import { useEffect, useState, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import { useNostrLogin } from '@nostrify/react/login';
import { Loader2, CheckCircle, XCircle } from 'lucide-react';
// Storage key must match the one in App.tsx NostrLoginProvider
const LOGINS_STORAGE_KEY = 'nostr:login';
export function RemoteLoginSuccess() {
const navigate = useNavigate();
const { logins } = useNostrLogin();
const [checkCount, setCheckCount] = useState(0);
const [status, setStatus] = useState<'checking' | 'success' | 'timeout'>('checking');
// Check localStorage directly as a fallback
const checkLocalStorage = useCallback(() => {
try {
const stored = localStorage.getItem(LOGINS_STORAGE_KEY);
if (stored) {
const parsed = JSON.parse(stored);
return Array.isArray(parsed) && parsed.length > 0;
}
} catch {
// Ignore parse errors
}
return false;
}, []);
// Check if logged in via React state or localStorage
const isLoggedIn = logins.length > 0 || checkLocalStorage();
useEffect(() => {
if (isLoggedIn) {
setStatus('success');
const timer = setTimeout(() => {
// Try to close this tab (works if opened by signer app)
// This leaves the user on the original tab which should detect the login
window.close();
// If we're still here (close didn't work), do a full page redirect
window.location.href = '/';
}, 1500);
return () => clearTimeout(timer);
}
// Check up to 20 times (10 seconds total) for the session to become active
if (checkCount < 20) {
const timer = setTimeout(() => {
setCheckCount(prev => prev + 1);
}, 500);
return () => clearTimeout(timer);
} else {
setStatus('timeout');
}
}, [isLoggedIn, checkCount, navigate, checkLocalStorage]);
// Listen for storage events (in case login is added from another context)
useEffect(() => {
const handleStorage = (e: StorageEvent) => {
if (e.key === LOGINS_STORAGE_KEY && e.newValue) {
try {
const parsed = JSON.parse(e.newValue);
if (Array.isArray(parsed) && parsed.length > 0) {
setStatus('success');
setTimeout(() => {
window.close();
window.location.href = '/';
}, 1500);
}
} catch {
// Ignore parse errors
}
}
};
window.addEventListener('storage', handleStorage);
return () => window.removeEventListener('storage', handleStorage);
}, []);
return (
<div className="min-h-screen flex items-center justify-center bg-background">
<div className="text-center p-8">
{status === 'checking' && (
<>
<Loader2 className="h-16 w-16 animate-spin text-primary mx-auto mb-4" />
<h1 className="text-2xl font-bold mb-2">Completing Login...</h1>
<p className="text-muted-foreground">Please wait while we verify your session.</p>
</>
)}
{status === 'success' && (
<>
<CheckCircle className="h-16 w-16 text-green-500 mx-auto mb-4" />
<h1 className="text-2xl font-bold mb-2">Login Successful!</h1>
<p className="text-muted-foreground">Redirecting you now...</p>
</>
)}
{status === 'timeout' && (
<>
<XCircle className="h-16 w-16 text-destructive mx-auto mb-4" />
<h1 className="text-2xl font-bold mb-2">Session Not Found</h1>
<p className="text-muted-foreground mb-4">
We couldn't detect an active login session.
</p>
<a
href="/"
className="text-primary hover:underline"
>
Return to home page
</a>
</>
)}
</div>
</div>
);
}
+6 -1
View File
@@ -23,7 +23,12 @@ export function TestApp({ children }: TestAppProps) {
const defaultConfig: AppConfig = {
theme: 'light',
relayUrl: 'wss://relay.nostr.band',
relayMetadata: {
relays: [
{ url: 'wss://relay.nostr.band', read: true, write: true },
],
updatedAt: 0,
},
};
return (