20 changed files with 1174 additions and 422 deletions

No files matched your search

+41 -109
View File
@@ -15,6 +15,7 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3.
## Project Structure ## Project Structure
- `/docs/`: Specialized documentation for implementation patterns and features
- `/src/components/`: UI components including NostrProvider for Nostr integration - `/src/components/`: UI components including NostrProvider for Nostr integration
- `/src/components/ui/`: shadcn/ui components (48+ components available) - `/src/components/ui/`: shadcn/ui components (48+ components available)
- `/src/components/auth/`: Authentication-related components (LoginArea, LoginDialog, etc.) - `/src/components/auth/`: Authentication-related components (LoginArea, LoginDialog, etc.)
@@ -103,6 +104,18 @@ The project uses shadcn/ui components located in `@/components/ui`. These are un
These components follow a consistent pattern using React's `forwardRef` and use the `cn()` utility for class name merging. Many are built on Radix UI primitives for accessibility and customized with Tailwind CSS. These components follow a consistent pattern using React's `forwardRef` and use the `cn()` utility for class name merging. Many are built on Radix UI primitives for accessibility and customized with Tailwind CSS.
## Documentation
The project includes a **`docs/`** directory containing specialized documentation for specific implementation tasks. You are encouraged to add new documentation files to help future development.
- **`docs/AI_CHAT.md`**: Read when building any AI-powered chat interfaces, implementing streaming responses, or integrating with the Shakespeare API.
- **`docs/NOSTR_COMMENTS.md`**: Read when implementing comment systems, adding discussion features to posts/articles, or building community interaction features.
- **`docs/NOSTR_INFINITE_SCROLL.md`**: Read when building feed interfaces, implementing pagination for Nostr events, or creating social media-style infinite scroll experiences.
- **`docs/NOSTR_DIRECT_MESSAGES.md`**: Read when implementing direct messaging features, building chat interfaces, or working with encrypted peer-to-peer communication (NIP-04 and NIP-17).
## System Prompt Management ## System Prompt Management
The AI assistant's behavior and knowledge is defined by the AGENTS.md file, which serves as the system prompt. To modify the assistant's instructions or add new project-specific guidelines: The AI assistant's behavior and knowledge is defined by the AGENTS.md file, which serves as the system prompt. To modify the assistant's instructions or add new project-specific guidelines:
@@ -220,7 +233,7 @@ const events = await nostr.query([{
kinds: [1], kinds: [1],
'#t': ['farming'], '#t': ['farming'],
limit: 20 limit: 20
}]); }], { signal });
``` ```
### Kind Ranges ### Kind Ranges
@@ -270,104 +283,6 @@ The file `NIP.md` is used by this project to define a custom Nostr protocol docu
Whenever new kinds are generated, the `NIP.md` file in the project must be created or updated to document the custom event schema. Whenever the schema of one of these custom events changes, `NIP.md` must also be updated accordingly. Whenever new kinds are generated, the `NIP.md` file in the project must be created or updated to document the custom event schema. Whenever the schema of one of these custom events changes, `NIP.md` must also be updated accordingly.
### Nostr Security Model
**CRITICAL**: Nostr is permissionless - **anyone can publish any event**. When implementing admin/moderation systems or any feature that should only trust specific users, you MUST filter queries by the `authors` field. Without author filtering, anyone can publish events claiming to be admin actions, moderator decisions, or trusted content.
#### Using the `authors` Filter
**Always filter by authors when querying:**
- **Admin/moderator actions** - MUST filter by trusted admin pubkeys
- **Addressable events (kinds 30000-39999)** - MUST include author to prevent anyone from publishing events with the same d-tag
- **Any privileged operations** - Filter by trusted pubkeys only
**✅ Secure - Filtering by trusted authors:**
```typescript
import { ADMIN_PUBKEYS } from '@/lib/admins';
// Query organizer appointments - ONLY accept events from admins
const events = await nostr.query([{
kinds: [30078],
authors: ADMIN_PUBKEYS, // CRITICAL: Only trust admin authors
'#d': ['pathos-organizers'],
limit: 1
}]);
```
**❌ INSECURE - No author filtering:**
```typescript
// DANGER: This accepts events from ANYONE who publishes kind 30078
// An attacker could appoint themselves as an organizer
const events = await nostr.query([{
kinds: [30078],
'#d': ['pathos-organizers'],
limit: 1
}]);
```
**Addressable Events Example:**
```typescript
// For addressable events, ALWAYS include the author in your filter
// This prevents attackers from publishing events with the same d-tag
const article = await nostr.query([{
kinds: [30023], // Long-form article
authors: [authorPubkey], // CRITICAL: Verify the author
'#d': ['my-article-slug'],
limit: 1
}]);
```
**URL Routing for Addressable/Replaceable Events:**
When creating URL paths for addressable or replaceable events, always include the author in the URL structure:
```typescript
// ❌ INSECURE: Missing author - anyone could publish an event with this d-tag
<Route path="/article/:slug" element={<Article />} />
// URL: /article/hello-world
// ✅ SECURE: Includes author - can safely filter by both author and d-tag
<Route path="/article/:npub/:slug" element={<Article />} />
// URL: /article/npub1abc.../hello-world
```
This ensures your route parameters provide both the author pubkey and the d-tag identifier needed to create a secure query filter.
**NIP-72 Community Moderation Example:**
When implementing moderated communities (NIP-72), you must query the community definition to get the moderator list, then filter approval events by those moderators:
```typescript
// Step 1: Query the community definition to get moderators
const communityEvents = await nostr.query([{
kinds: [34550],
authors: [communityOwnerPubkey], // CRITICAL: Only trust the community owner
'#d': [communityId],
limit: 1,
}]);
if (communityEvents.length === 0) return [];
// Step 2: Extract moderator pubkeys from p tags
const moderatorPubkeys = communityEvents[0].tags
.filter(([name, _, __, role]) => name === 'p' && role === 'moderator')
.map(([_, pubkey]) => pubkey);
// Step 3: Query approval events - ONLY from trusted moderators
const approvals = await nostr.query([{
kinds: [4550],
authors: moderatorPubkeys, // CRITICAL: Only accept approvals from moderators
'#a': [`34550:${communityOwnerPubkey}:${communityId}`],
limit: 100,
}]);
```
Without filtering approvals by the moderator list, anyone could publish kind 4550 events claiming to approve posts for the community.
#### When Author Filtering Is NOT Required
Author filtering is not needed for public user-generated content where anyone should be able to post (kind 1 notes, reactions, discovery queries, public feeds, etc.).
### The `useNostr` Hook ### The `useNostr` Hook
The `useNostr` hook returns an object containing a `nostr` property, with `.query()` and `.event()` methods for querying and publishing Nostr events respectively. The `useNostr` hook returns an object containing a `nostr` property, with `.query()` and `.event()` methods for querying and publishing Nostr events respectively.
@@ -400,7 +315,7 @@ function useSpecificRelay() {
const relay = nostr.relay('wss://relay.damus.io'); const relay = nostr.relay('wss://relay.damus.io');
// Query from this specific relay only // Query from this specific relay only
const events = await relay.query([{ kinds: [1], limit: 20 }]); const events = await relay.query([{ kinds: [1], limit: 20 }], { signal });
// Publish to this specific relay only // Publish to this specific relay only
await relay.event({ kind: 1, content: 'Hello from specific relay!' }); await relay.event({ kind: 1, content: 'Hello from specific relay!' });
@@ -425,7 +340,7 @@ function useRelayGroup() {
]); ]);
// Query from all relays in the group // Query from all relays in the group
const events = await relayGroup.query([{ kinds: [1], limit: 20 }]); const events = await relayGroup.query([{ kinds: [1], limit: 20 }], { signal });
// Publish to all relays in the group // Publish to all relays in the group
await relayGroup.event({ kind: 1, content: 'Hello from relay group!' }); await relayGroup.event({ kind: 1, content: 'Hello from relay group!' });
@@ -475,7 +390,8 @@ function usePosts() {
return useQuery({ return useQuery({
queryKey: ['posts'], queryKey: ['posts'],
queryFn: async (c) => { queryFn: async (c) => {
const events = await nostr.query([{ kinds: [1], limit: 20 }]); const signal = AbortSignal.any([c.signal, AbortSignal.timeout(1500)]);
const events = await nostr.query([{ kinds: [1], limit: 20 }], { signal });
return events; // these events could be transformed into another format return events; // these events could be transformed into another format
}, },
}); });
@@ -495,7 +411,7 @@ const events = await nostr.query([
'#e': [eventId], '#e': [eventId],
limit: 150, limit: 150,
} }
]); ], { signal });
// Separate by type in JavaScript // Separate by type in JavaScript
const notes = events.filter((e) => e.kind === 1); const notes = events.filter((e) => e.kind === 1);
@@ -507,9 +423,9 @@ const genericReposts = events.filter((e) => e.kind === 16);
```typescript ```typescript
// This creates unnecessary load and can trigger rate limiting // This creates unnecessary load and can trigger rate limiting
const [notes, reposts, genericReposts] = await Promise.all([ const [notes, reposts, genericReposts] = await Promise.all([
nostr.query([{ kinds: [1], '#e': [eventId] }]), nostr.query([{ kinds: [1], '#e': [eventId] }], { signal }),
nostr.query([{ kinds: [6], '#e': [eventId] }]), nostr.query([{ kinds: [6], '#e': [eventId] }], { signal }),
nostr.query([{ kinds: [16], '#e': [eventId] }]), nostr.query([{ kinds: [16], '#e': [eventId] }], { signal }),
]); ]);
``` ```
@@ -563,7 +479,8 @@ function useCalendarEvents() {
return useQuery({ return useQuery({
queryKey: ['calendar-events'], queryKey: ['calendar-events'],
queryFn: async (c) => { queryFn: async (c) => {
const events = await nostr.query([{ kinds: [31922, 31923], limit: 20 }]); const signal = AbortSignal.any([c.signal, AbortSignal.timeout(1500)]);
const events = await nostr.query([{ kinds: [31922, 31923], limit: 20 }], { signal });
// Filter events through validator to ensure they meet NIP-52 requirements // Filter events through validator to ensure they meet NIP-52 requirements
return events.filter(validateCalendarEvent); return events.filter(validateCalendarEvent);
@@ -764,6 +681,7 @@ The base Nostr protocol uses hex string identifiers when filtering by event IDs
// ❌ Wrong: naddr is not decoded // ❌ Wrong: naddr is not decoded
const events = await nostr.query( const events = await nostr.query(
[{ ids: [naddr] }], [{ ids: [naddr] }],
{ signal }
); );
``` ```
@@ -791,6 +709,7 @@ const events = await nostr.query(
authors: [naddr.pubkey], authors: [naddr.pubkey],
'#d': [naddr.identifier], '#d': [naddr.identifier],
}], }],
{ signal }
); );
``` ```
@@ -829,6 +748,20 @@ function EditProfilePage() {
The `EditProfileForm` component displays just the form. It requires no props, and will "just work" automatically. The `EditProfileForm` component displays just the form. It requires no props, and will "just work" automatically.
### Direct Messaging (NIP-04 & NIP-17)
The project includes a complete direct messaging system with real-time updates, encrypted storage, and support for both NIP-04 (legacy) and NIP-17 (modern private messaging) protocols. **The system is disabled by default** - enable it by passing `enabled: true` in the `DMProvider` config.
For complete implementation guide including:
- Setup and configuration
- Sending messages and file attachments
- Using the `DMMessagingInterface` component
- Building custom messaging UIs
- Protocol comparison (NIP-04 vs NIP-17)
- Advanced features and architecture
See **`docs/NOSTR_DIRECT_MESSAGES.md`**
### Uploading Files on Nostr ### Uploading Files on Nostr
Use the `useUploadFile` hook to upload files. This hook uses Blossom servers for file storage and returns NIP-94 compatible tags. Use the `useUploadFile` hook to upload files. This hook uses Blossom servers for file storage and returns NIP-94 compatible tags.
@@ -905,7 +838,7 @@ const defaultConfig: AppConfig = {
relayMetadata: { relayMetadata: {
relays: [ relays: [
{ url: 'wss://relay.ditto.pub', read: true, write: true }, { url: 'wss://relay.ditto.pub', read: true, write: true },
{ url: 'wss://relay.primal.net', read: true, write: true }, { url: 'wss://relay.nostr.band', read: true, write: true },
{ url: 'wss://relay.damus.io', read: true, write: true }, { url: 'wss://relay.damus.io', read: true, write: true },
], ],
updatedAt: 0, updatedAt: 0,
@@ -1120,7 +1053,6 @@ When users specify color schemes:
- Follow shadcn/ui patterns for component variants - Follow shadcn/ui patterns for component variants
- Implement responsive design with Tailwind breakpoints - Implement responsive design with Tailwind breakpoints
- Add hover and focus states for interactive elements - Add hover and focus states for interactive elements
- When using negative z-index (e.g., `-z-10`) for background images or decorative elements, **always add `isolate` to the parent container** to create a local stacking context. Without `isolate`, negative z-index pushes elements behind the page's background color, making them invisible.
## Writing Tests vs Running Tests ## Writing Tests vs Running Tests
@@ -1,9 +1,4 @@
--- ### AI Integration with Shakespeare API
name: ai-chat
description: Build AI-powered chat interfaces, implement streaming responses, or integrate with Shakespeare AI.
---
# AI Integration with Shakespeare API
Use the `useShakespeare` hook for AI chat completions with Nostr authentication. The API dynamically provides available models, so you should query them at runtime rather than hardcoding model names. Use the `useShakespeare` hook for AI chat completions with Nostr authentication. The API dynamically provides available models, so you should query them at runtime rather than hardcoding model names.
@@ -1,8 +1,3 @@
---
name: nostr-comments
description: Implement Nostr comment systems, add discussion features to posts/articles, or build community interaction features.
---
# Adding Nostr Comments Sections # Adding Nostr Comments Sections
The project includes a complete commenting system using NIP-22 (kind 1111) comments that can be added to any Nostr event or URL. The `CommentsSection` component provides a full-featured commenting interface with threaded replies, user authentication, and real-time updates. The project includes a complete commenting system using NIP-22 (kind 1111) comments that can be added to any Nostr event or URL. The `CommentsSection` component provides a full-featured commenting interface with threaded replies, user authentication, and real-time updates.
@@ -1,9 +1,4 @@
--- ### Direct Messaging on Nostr
name: nostr-direct-messages
description: Implement Nostr direct messaging features, build chat interfaces, or work with encrypted peer-to-peer communication (NIP-04 and NIP-17).
---
# 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.
@@ -1,9 +1,4 @@
--- ### Infinite Scroll for Nostr Feeds
name: nostr-infinite-scroll
description: Build feed interfaces, implement pagination for Nostr events, or create social media-style infinite scroll experiences.
---
# Infinite Scroll for Nostr Feeds
For feed-like interfaces, implement infinite scroll using TanStack Query's `useInfiniteQuery` with Nostr's timestamp-based pagination: For feed-like interfaces, implement infinite scroll using TanStack Query's `useInfiniteQuery` with Nostr's timestamp-based pagination:
-9
View File
@@ -1,9 +0,0 @@
{
"$schema": "https://opencode.ai/config.json",
"mcp": {
"nostr": {
"type": "local",
"command": ["npx", "-y", "@nostrbook/mcp@latest"]
}
}
}
+70 -49
View File
@@ -10,9 +10,9 @@
"dependencies": { "dependencies": {
"@fontsource-variable/inter": "^5.2.6", "@fontsource-variable/inter": "^5.2.6",
"@getalby/sdk": "^5.1.1", "@getalby/sdk": "^5.1.1",
"@hookform/resolvers": "^5.2.2", "@hookform/resolvers": "^3.9.0",
"@nostrify/nostrify": "^0.49.2", "@nostrify/nostrify": "^0.48.2",
"@nostrify/react": "^0.2.24", "@nostrify/react": "^0.2.20",
"@radix-ui/react-accordion": "^1.2.0", "@radix-ui/react-accordion": "^1.2.0",
"@radix-ui/react-alert-dialog": "^1.1.1", "@radix-ui/react-alert-dialog": "^1.1.1",
"@radix-ui/react-aspect-ratio": "^1.1.0", "@radix-ui/react-aspect-ratio": "^1.1.0",
@@ -54,10 +54,11 @@
"lucide-react": "^0.462.0", "lucide-react": "^0.462.0",
"nostr-tools": "^2.13.0", "nostr-tools": "^2.13.0",
"qrcode": "^1.5.4", "qrcode": "^1.5.4",
"qrcode.react": "^4.2.0",
"react": "^18.3.1", "react": "^18.3.1",
"react-day-picker": "^8.10.1", "react-day-picker": "^8.10.1",
"react-dom": "^18.3.1", "react-dom": "^18.3.1",
"react-hook-form": "^7.71.1", "react-hook-form": "^7.53.0",
"react-intersection-observer": "^9.16.0", "react-intersection-observer": "^9.16.0",
"react-resizable-panels": "^2.1.3", "react-resizable-panels": "^2.1.3",
"react-router-dom": "^6.26.2", "react-router-dom": "^6.26.2",
@@ -65,7 +66,7 @@
"tailwind-merge": "^2.5.2", "tailwind-merge": "^2.5.2",
"tailwindcss-animate": "^1.0.7", "tailwindcss-animate": "^1.0.7",
"vaul": "^0.9.3", "vaul": "^0.9.3",
"zod": "^4.3.6" "zod": "^3.25.71"
}, },
"devDependencies": { "devDependencies": {
"@eslint/js": "^9.9.0", "@eslint/js": "^9.9.0",
@@ -986,15 +987,12 @@
} }
}, },
"node_modules/@hookform/resolvers": { "node_modules/@hookform/resolvers": {
"version": "5.2.2", "version": "3.10.0",
"resolved": "https://registry.npmjs.org/@hookform/resolvers/-/resolvers-5.2.2.tgz", "resolved": "https://registry.npmjs.org/@hookform/resolvers/-/resolvers-3.10.0.tgz",
"integrity": "sha512-A/IxlMLShx3KjV/HeTcTfaMxdwy690+L/ZADoeaTltLx+CVuzkeVIPuybK3jrRfw7YZnmdKsVVHAlEPIAEUNlA==", "integrity": "sha512-79Dv+3mDF7i+2ajj7SkypSKHhl1cbln1OGavqrsF7p6mbUv11xpqpacPsGDCTRvCSjEEIez2ef1NveSVL3b0Ag==",
"license": "MIT", "license": "MIT",
"dependencies": {
"@standard-schema/utils": "^0.3.0"
},
"peerDependencies": { "peerDependencies": {
"react-hook-form": "^7.55.0" "react-hook-form": "^7.0.0"
} }
}, },
"node_modules/@html-eslint/eslint-plugin": { "node_modules/@html-eslint/eslint-plugin": {
@@ -1256,11 +1254,11 @@
} }
}, },
"node_modules/@nostrify/nostrify": { "node_modules/@nostrify/nostrify": {
"version": "0.49.2", "version": "0.48.2",
"resolved": "https://registry.npmjs.org/@nostrify/nostrify/-/nostrify-0.49.2.tgz", "resolved": "https://registry.npmjs.org/@nostrify/nostrify/-/nostrify-0.48.2.tgz",
"integrity": "sha512-JMiGifc/XX4QhzFnmJVw00UjcOS295w/NYth9mJH0cbS0EqPQ/4HBn33P0DGW3iE5EAkk+n98cnwzYeIPtn9pQ==", "integrity": "sha512-Zze3RASsgn4MLQCuC5I4XR0WJi9G3J8qZpVjVIPvkw6vbZRct++JgavcZSxwKjJH1hHq+8d90IrHMOrskNQ8NQ==",
"dependencies": { "dependencies": {
"@nostrify/types": "0.36.9", "@nostrify/types": "0.36.8",
"@scure/base": "^2.0.0", "@scure/base": "^2.0.0",
"@smithy/util-base64": "^4.3.0", "@smithy/util-base64": "^4.3.0",
"@smithy/util-hex-encoding": "^4.2.0", "@smithy/util-hex-encoding": "^4.2.0",
@@ -1269,7 +1267,7 @@
"nostr-tools": "^2.13.0", "nostr-tools": "^2.13.0",
"websocket-ts": "^2.2.1", "websocket-ts": "^2.2.1",
"ws": "^8.18.3", "ws": "^8.18.3",
"zod": "^4.3.6" "zod": "^3.23.8"
} }
}, },
"node_modules/@nostrify/nostrify/node_modules/@scure/base": { "node_modules/@nostrify/nostrify/node_modules/@scure/base": {
@@ -1297,12 +1295,12 @@
"license": "MIT" "license": "MIT"
}, },
"node_modules/@nostrify/react": { "node_modules/@nostrify/react": {
"version": "0.2.24", "version": "0.2.20",
"resolved": "https://registry.npmjs.org/@nostrify/react/-/react-0.2.24.tgz", "resolved": "https://registry.npmjs.org/@nostrify/react/-/react-0.2.20.tgz",
"integrity": "sha512-LdB6UjNKZ/Xhz+jj8CRCcudHt4WNNVZMgJsiO+XAloqWE8oPRf1G2i1k6I/eF6buCJokKE1PFUTMlyieOpIXNQ==", "integrity": "sha512-Tvkdr5X+MQxh6CKKthk9Idch3vFp5nPcm57uJZJWrIqBtuj9jxMamM6uEo2lQAr0ugK52xDlyD50lRDRe0RMbQ==",
"dependencies": { "dependencies": {
"@nostrify/nostrify": "0.49.2", "@nostrify/nostrify": "0.48.2",
"@nostrify/types": "0.36.9", "@nostrify/types": "0.36.8",
"@tanstack/react-query": "^5.69.0", "@tanstack/react-query": "^5.69.0",
"nostr-tools": "^2.13.0", "nostr-tools": "^2.13.0",
"react": "^18.0.0", "react": "^18.0.0",
@@ -1310,9 +1308,9 @@
} }
}, },
"node_modules/@nostrify/types": { "node_modules/@nostrify/types": {
"version": "0.36.9", "version": "0.36.8",
"resolved": "https://registry.npmjs.org/@nostrify/types/-/types-0.36.9.tgz", "resolved": "https://registry.npmjs.org/@nostrify/types/-/types-0.36.8.tgz",
"integrity": "sha512-tMx/r0W+QoVRRgs8d6ltaSgrftasOXuFsi33kW8WirswCy2b3UR1tqRgc0iBU9zRa9XR0nlej/wJZW+6wUFi+Q==" "integrity": "sha512-tmpz5pkU8oXu7+V1qxvAzuoo8s5x4Gvo7h+JRm+JAW6x/2VZ8aQoA54yhn89qZ9agciMJhVdhqCm1PlK55w17A=="
}, },
"node_modules/@pkgjs/parseargs": { "node_modules/@pkgjs/parseargs": {
"version": "0.11.0", "version": "0.11.0",
@@ -2679,9 +2677,9 @@
"license": "MIT" "license": "MIT"
}, },
"node_modules/@remix-run/router": { "node_modules/@remix-run/router": {
"version": "1.23.2", "version": "1.23.0",
"resolved": "https://registry.npmjs.org/@remix-run/router/-/router-1.23.2.tgz", "resolved": "https://registry.npmjs.org/@remix-run/router/-/router-1.23.0.tgz",
"integrity": "sha512-Ic6m2U/rMjTkhERIa/0ZtXJP17QUi2CbWE7cqx4J58M8aA3QTfW+2UlQ4psvTX9IO1RfNVhK3pcpdjej7L+t2w==", "integrity": "sha512-O3rHJzAQKamUz1fvE0Qaw0xSFqsA/yafi2iqeE0pvdFtCO1viYx8QL6f3Ln/aCCTLxs68SLf0KPM9eSeM8yBnA==",
"license": "MIT", "license": "MIT",
"engines": { "engines": {
"node": ">=14.0.0" "node": ">=14.0.0"
@@ -2734,6 +2732,7 @@
"cpu": [ "cpu": [
"arm" "arm"
], ],
"dev": true,
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
@@ -2747,6 +2746,7 @@
"cpu": [ "cpu": [
"arm64" "arm64"
], ],
"dev": true,
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
@@ -2760,6 +2760,7 @@
"cpu": [ "cpu": [
"arm64" "arm64"
], ],
"dev": true,
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
@@ -2773,6 +2774,7 @@
"cpu": [ "cpu": [
"x64" "x64"
], ],
"dev": true,
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
@@ -2786,6 +2788,7 @@
"cpu": [ "cpu": [
"arm64" "arm64"
], ],
"dev": true,
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
@@ -2799,6 +2802,7 @@
"cpu": [ "cpu": [
"x64" "x64"
], ],
"dev": true,
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
@@ -2812,6 +2816,7 @@
"cpu": [ "cpu": [
"arm" "arm"
], ],
"dev": true,
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
@@ -2825,6 +2830,7 @@
"cpu": [ "cpu": [
"arm" "arm"
], ],
"dev": true,
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
@@ -2838,6 +2844,7 @@
"cpu": [ "cpu": [
"arm64" "arm64"
], ],
"dev": true,
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
@@ -2851,6 +2858,7 @@
"cpu": [ "cpu": [
"arm64" "arm64"
], ],
"dev": true,
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
@@ -2864,6 +2872,7 @@
"cpu": [ "cpu": [
"loong64" "loong64"
], ],
"dev": true,
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
@@ -2877,6 +2886,7 @@
"cpu": [ "cpu": [
"ppc64" "ppc64"
], ],
"dev": true,
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
@@ -2890,6 +2900,7 @@
"cpu": [ "cpu": [
"riscv64" "riscv64"
], ],
"dev": true,
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
@@ -2903,6 +2914,7 @@
"cpu": [ "cpu": [
"riscv64" "riscv64"
], ],
"dev": true,
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
@@ -2916,6 +2928,7 @@
"cpu": [ "cpu": [
"s390x" "s390x"
], ],
"dev": true,
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
@@ -2929,6 +2942,7 @@
"cpu": [ "cpu": [
"x64" "x64"
], ],
"dev": true,
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
@@ -2942,6 +2956,7 @@
"cpu": [ "cpu": [
"x64" "x64"
], ],
"dev": true,
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
@@ -2955,6 +2970,7 @@
"cpu": [ "cpu": [
"arm64" "arm64"
], ],
"dev": true,
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
@@ -2968,6 +2984,7 @@
"cpu": [ "cpu": [
"ia32" "ia32"
], ],
"dev": true,
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
@@ -2981,6 +2998,7 @@
"cpu": [ "cpu": [
"x64" "x64"
], ],
"dev": true,
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
@@ -3102,12 +3120,6 @@
"node": ">=18.0.0" "node": ">=18.0.0"
} }
}, },
"node_modules/@standard-schema/utils": {
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/@standard-schema/utils/-/utils-0.3.0.tgz",
"integrity": "sha512-e7Mew686owMaPJVNNLs55PUvgz371nKgwsc4vxE49zsODpJEnxgxRo2y/OKrqueavXgZNMDVj3DdHFlaSAeU8g==",
"license": "MIT"
},
"node_modules/@swc/core": { "node_modules/@swc/core": {
"version": "1.11.24", "version": "1.11.24",
"resolved": "https://registry.npmjs.org/@swc/core/-/core-1.11.24.tgz", "resolved": "https://registry.npmjs.org/@swc/core/-/core-1.11.24.tgz",
@@ -6669,6 +6681,15 @@
"node": ">=10.13.0" "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": { "node_modules/queue-microtask": {
"version": "1.2.3", "version": "1.2.3",
"resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz", "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz",
@@ -6729,9 +6750,9 @@
} }
}, },
"node_modules/react-hook-form": { "node_modules/react-hook-form": {
"version": "7.71.1", "version": "7.56.1",
"resolved": "https://registry.npmjs.org/react-hook-form/-/react-hook-form-7.71.1.tgz", "resolved": "https://registry.npmjs.org/react-hook-form/-/react-hook-form-7.56.1.tgz",
"integrity": "sha512-9SUJKCGKo8HUSsCO+y0CtqkqI5nNuaDqTxyqPsZPqIwudpj4rCrAz/jZV+jn57bx5gtZKOh3neQu94DXMc+w5w==", "integrity": "sha512-qWAVokhSpshhcEuQDSANHx3jiAEFzu2HAaaQIzi/r9FNPm1ioAvuJSD4EuZzWd7Al7nTRKcKPnBKO7sRn+zavQ==",
"license": "MIT", "license": "MIT",
"engines": { "engines": {
"node": ">=18.0.0" "node": ">=18.0.0"
@@ -6823,12 +6844,12 @@
} }
}, },
"node_modules/react-router": { "node_modules/react-router": {
"version": "6.30.3", "version": "6.30.0",
"resolved": "https://registry.npmjs.org/react-router/-/react-router-6.30.3.tgz", "resolved": "https://registry.npmjs.org/react-router/-/react-router-6.30.0.tgz",
"integrity": "sha512-XRnlbKMTmktBkjCLE8/XcZFlnHvr2Ltdr1eJX4idL55/9BbORzyZEaIkBFDhFGCEWBBItsVrDxwx3gnisMitdw==", "integrity": "sha512-D3X8FyH9nBcTSHGdEKurK7r8OYE1kKFn3d/CF+CoxbSHkxU7o37+Uh7eAHRXr6k2tSExXYO++07PeXJtA/dEhQ==",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@remix-run/router": "1.23.2" "@remix-run/router": "1.23.0"
}, },
"engines": { "engines": {
"node": ">=14.0.0" "node": ">=14.0.0"
@@ -6838,13 +6859,13 @@
} }
}, },
"node_modules/react-router-dom": { "node_modules/react-router-dom": {
"version": "6.30.3", "version": "6.30.0",
"resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-6.30.3.tgz", "resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-6.30.0.tgz",
"integrity": "sha512-pxPcv1AczD4vso7G4Z3TKcvlxK7g7TNt3/FNGMhfqyntocvYKj+GCatfigGDjbLozC4baguJ0ReCigoDJXb0ag==", "integrity": "sha512-x30B78HV5tFk8ex0ITwzC9TTZMua4jGyA9IUlH1JLQYQTFyxr/ZxwOJq7evg1JX1qGVUcvhsmQSKdPncQrjTgA==",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@remix-run/router": "1.23.2", "@remix-run/router": "1.23.0",
"react-router": "6.30.3" "react-router": "6.30.0"
}, },
"engines": { "engines": {
"node": ">=14.0.0" "node": ">=14.0.0"
@@ -8510,9 +8531,9 @@
} }
}, },
"node_modules/zod": { "node_modules/zod": {
"version": "4.3.6", "version": "3.25.71",
"resolved": "https://registry.npmjs.org/zod/-/zod-4.3.6.tgz", "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.71.tgz",
"integrity": "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==", "integrity": "sha512-BsBc/NPk7h8WsUWYWYL+BajcJPY8YhjelaWu2NMLuzgraKAz4Lb4/6K11g9jpuDetjMiqhZ6YaexFLOC0Ogi3Q==",
"license": "MIT", "license": "MIT",
"funding": { "funding": {
"url": "https://github.com/sponsors/colinhacks" "url": "https://github.com/sponsors/colinhacks"
+10 -8
View File
@@ -6,14 +6,15 @@
"scripts": { "scripts": {
"dev": "npm i --silent && vite", "dev": "npm i --silent && vite",
"build": "npm i --silent && vite build -l error && cp dist/index.html dist/404.html && echo 'Project built successfully!'", "build": "npm i --silent && vite build -l error && cp dist/index.html dist/404.html && echo 'Project built successfully!'",
"test": "npm i --silent && tsc --noEmit && eslint && vitest run --reporter=dot --silent && vite build -l error && cp dist/index.html dist/404.html && echo 'All tests passed!'" "test": "npm i --silent && tsc --noEmit && eslint && vitest run --reporter=dot --silent && vite build -l error && cp dist/index.html dist/404.html && echo 'All tests passed!'",
"deploy": "npm run build && npx -y nostr-deploy-cli deploy --skip-setup"
}, },
"dependencies": { "dependencies": {
"@fontsource-variable/inter": "^5.2.6", "@fontsource-variable/inter": "^5.2.6",
"@getalby/sdk": "^7.0.0", "@getalby/sdk": "^5.1.1",
"@hookform/resolvers": "^5.2.2", "@hookform/resolvers": "^3.9.0",
"@nostrify/nostrify": "^0.49.2", "@nostrify/nostrify": "^0.48.2",
"@nostrify/react": "^0.2.24", "@nostrify/react": "^0.2.20",
"@radix-ui/react-accordion": "^1.2.0", "@radix-ui/react-accordion": "^1.2.0",
"@radix-ui/react-alert-dialog": "^1.1.1", "@radix-ui/react-alert-dialog": "^1.1.1",
"@radix-ui/react-aspect-ratio": "^1.1.0", "@radix-ui/react-aspect-ratio": "^1.1.0",
@@ -53,12 +54,13 @@
"idb": "^8.0.3", "idb": "^8.0.3",
"input-otp": "^1.2.4", "input-otp": "^1.2.4",
"lucide-react": "^0.462.0", "lucide-react": "^0.462.0",
"nostr-tools": "^2.21.0", "nostr-tools": "^2.13.0",
"qrcode": "^1.5.4", "qrcode": "^1.5.4",
"qrcode.react": "^4.2.0",
"react": "^18.3.1", "react": "^18.3.1",
"react-day-picker": "^8.10.1", "react-day-picker": "^8.10.1",
"react-dom": "^18.3.1", "react-dom": "^18.3.1",
"react-hook-form": "^7.71.1", "react-hook-form": "^7.53.0",
"react-intersection-observer": "^9.16.0", "react-intersection-observer": "^9.16.0",
"react-resizable-panels": "^2.1.3", "react-resizable-panels": "^2.1.3",
"react-router-dom": "^6.26.2", "react-router-dom": "^6.26.2",
@@ -66,7 +68,7 @@
"tailwind-merge": "^2.5.2", "tailwind-merge": "^2.5.2",
"tailwindcss-animate": "^1.0.7", "tailwindcss-animate": "^1.0.7",
"vaul": "^0.9.3", "vaul": "^0.9.3",
"zod": "^4.3.6" "zod": "^3.25.71"
}, },
"devDependencies": { "devDependencies": {
"@eslint/js": "^9.9.0", "@eslint/js": "^9.9.0",
+2
View File
@@ -3,6 +3,7 @@ import { ScrollToTop } from "./components/ScrollToTop";
import Index from "./pages/Index"; import Index from "./pages/Index";
import { NIP19Page } from "./pages/NIP19Page"; import { NIP19Page } from "./pages/NIP19Page";
import { RemoteLoginSuccess } from "./pages/RemoteLoginSuccess";
import NotFound from "./pages/NotFound"; import NotFound from "./pages/NotFound";
export function AppRouter() { export function AppRouter() {
@@ -11,6 +12,7 @@ export function AppRouter() {
<ScrollToTop /> <ScrollToTop />
<Routes> <Routes>
<Route path="/" element={<Index />} /> <Route path="/" element={<Index />} />
<Route path="/remoteloginsuccess" element={<RemoteLoginSuccess />} />
{/* NIP-19 route for npub1, note1, naddr1, nevent1, nprofile1 */} {/* NIP-19 route for npub1, note1, naddr1, nevent1, nprofile1 */}
<Route path="/:nip19" element={<NIP19Page />} /> <Route path="/:nip19" element={<NIP19Page />} />
{/* ADD ALL CUSTOM ROUTES ABOVE THE CATCH-ALL "*" ROUTE */} {/* ADD ALL CUSTOM ROUTES ABOVE THE CATCH-ALL "*" ROUTE */}
+1 -1
View File
@@ -14,7 +14,7 @@ interface AppProviderProps {
// Zod schema for RelayMetadata validation // Zod schema for RelayMetadata validation
const RelayMetadataSchema = z.object({ const RelayMetadataSchema = z.object({
relays: z.array(z.object({ relays: z.array(z.object({
url: z.url(), url: z.string().url(),
read: z.boolean(), read: z.boolean(),
write: z.boolean(), write: z.boolean(),
})), })),
+2 -7
View File
@@ -45,7 +45,7 @@ export function NoteContent({
href={url} href={url}
target="_blank" target="_blank"
rel="noopener noreferrer" rel="noopener noreferrer"
className="text-blue-500 hover:underline break-all" className="text-blue-500 hover:underline"
> >
{url} {url}
</a> </a>
@@ -61,18 +61,13 @@ export function NoteContent({
parts.push( parts.push(
<NostrMention key={`mention-${keyCounter++}`} pubkey={pubkey} /> <NostrMention key={`mention-${keyCounter++}`} pubkey={pubkey} />
); );
} else if (decoded.type === 'nprofile') {
const pubkey = decoded.data.pubkey;
parts.push(
<NostrMention key={`mention-${keyCounter++}`} pubkey={pubkey} />
);
} else { } else {
// For other types, just show as a link // For other types, just show as a link
parts.push( parts.push(
<Link <Link
key={`nostr-${keyCounter++}`} key={`nostr-${keyCounter++}`}
to={`/${nostrId}`} to={`/${nostrId}`}
className="text-blue-500 hover:underline break-all" className="text-blue-500 hover:underline"
> >
{fullMatch} {fullMatch}
</Link> </Link>
+11 -1
View File
@@ -1,7 +1,7 @@
// NOTE: This file is stable and usually should not be modified. // NOTE: This file is stable and usually should not be modified.
// It is important that all functionality in this file is preserved, and should only be modified if explicitly requested. // It is important that all functionality in this file is preserved, and should only be modified if explicitly requested.
import { ChevronDown, LogOut, UserIcon, UserPlus } from 'lucide-react'; import { ChevronDown, LogOut, UserIcon, UserPlus, Wallet } from 'lucide-react';
import { import {
DropdownMenu, DropdownMenu,
DropdownMenuContent, DropdownMenuContent,
@@ -10,6 +10,7 @@ import {
DropdownMenuTrigger, DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu.tsx'; } from '@/components/ui/dropdown-menu.tsx';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar.tsx'; import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar.tsx';
import { WalletModal } from '@/components/WalletModal';
import { useLoggedInAccounts, type Account } from '@/hooks/useLoggedInAccounts'; import { useLoggedInAccounts, type Account } from '@/hooks/useLoggedInAccounts';
import { genUserName } from '@/lib/genUserName'; import { genUserName } from '@/lib/genUserName';
@@ -59,6 +60,15 @@ export function AccountSwitcher({ onAddAccountClick }: AccountSwitcherProps) {
</DropdownMenuItem> </DropdownMenuItem>
))} ))}
<DropdownMenuSeparator /> <DropdownMenuSeparator />
<WalletModal>
<DropdownMenuItem
className='flex items-center gap-2 cursor-pointer p-2 rounded-md'
onSelect={(e) => e.preventDefault()}
>
<Wallet className='w-4 h-4' />
<span>Wallet Settings</span>
</DropdownMenuItem>
</WalletModal>
<DropdownMenuItem <DropdownMenuItem
onClick={onAddAccountClick} onClick={onAddAccountClick}
className='flex items-center gap-2 cursor-pointer p-2 rounded-md' className='flex items-center gap-2 cursor-pointer p-2 rounded-md'
+5 -1
View File
@@ -2,6 +2,7 @@
// It is important that all functionality in this file is preserved, and should only be modified if explicitly requested. // It is important that all functionality in this file is preserved, and should only be modified if explicitly requested.
import { useState } from 'react'; import { useState } from 'react';
import { User, UserPlus } from 'lucide-react';
import { Button } from '@/components/ui/button.tsx'; import { Button } from '@/components/ui/button.tsx';
import LoginDialog from './LoginDialog'; import LoginDialog from './LoginDialog';
import SignupDialog from './SignupDialog'; import SignupDialog from './SignupDialog';
@@ -33,13 +34,15 @@ export function LoginArea({ className }: LoginAreaProps) {
onClick={() => setLoginDialogOpen(true)} onClick={() => setLoginDialogOpen(true)}
className='flex items-center gap-2 px-4 py-2 rounded-full bg-primary text-primary-foreground w-full font-medium transition-all hover:bg-primary/90 animate-scale-in' className='flex items-center gap-2 px-4 py-2 rounded-full bg-primary text-primary-foreground w-full font-medium transition-all hover:bg-primary/90 animate-scale-in'
> >
<User className='w-4 h-4' />
<span className='truncate'>Log in</span> <span className='truncate'>Log in</span>
</Button><Button </Button><Button
onClick={() => setSignupDialogOpen(true)} onClick={() => setSignupDialogOpen(true)}
variant="outline" variant="outline"
className="flex items-center gap-2 px-4 py-2 rounded-full font-medium transition-all" className="flex items-center gap-2 px-4 py-2 rounded-full font-medium transition-all"
> >
<span>Sign up</span> <UserPlus className="w-4 h-4" />
<span>Sign Up</span>
</Button> </Button>
</div> </div>
)} )}
@@ -48,6 +51,7 @@ export function LoginArea({ className }: LoginAreaProps) {
isOpen={loginDialogOpen} isOpen={loginDialogOpen}
onClose={() => setLoginDialogOpen(false)} onClose={() => setLoginDialogOpen(false)}
onLogin={handleLogin} onLogin={handleLogin}
onSignup={() => setSignupDialogOpen(true)}
/> />
<SignupDialog <SignupDialog
+339 -130
View File
@@ -1,21 +1,28 @@
// NOTE: This file is stable and usually should not be modified. // NOTE: This file is stable and usually should not be modified.
// It is important that all functionality in this file is preserved, and should only be modified if explicitly requested. // It is important that all functionality in this file is preserved, and should only be modified if explicitly requested.
import React, { useRef, useState, useEffect } from 'react'; import React, { useCallback, useEffect, useRef, useState } from 'react';
import { Upload, AlertTriangle, ChevronDown } from 'lucide-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 { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input'; import { Input } from '@/components/ui/input';
import { Dialog, DialogContent, DialogHeader } from "@/components/ui/dialog"; import { Dialog, DialogContent, DialogHeader, DialogDescription } from "@/components/ui/dialog";
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'; import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Alert, AlertDescription } from '@/components/ui/alert'; import { Alert, AlertDescription } from '@/components/ui/alert';
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible'; import {
import { useLoginActions } from '@/hooks/useLoginActions'; useLoginActions,
import { DialogTitle } from '@radix-ui/react-dialog'; generateNostrConnectParams,
generateNostrConnectURI,
type NostrConnectParams,
} from '@/hooks/useLoginActions';
import { useIsMobile } from '@/hooks/useIsMobile';
import { cn } from '@/lib/utils';
interface LoginDialogProps { interface LoginDialogProps {
isOpen: boolean; isOpen: boolean;
onClose: () => void; onClose: () => void;
onLogin: () => void; onLogin: () => void;
onSignup?: () => void;
} }
const validateNsec = (nsec: string) => { const validateNsec = (nsec: string) => {
@@ -23,14 +30,20 @@ const validateNsec = (nsec: string) => {
}; };
const validateBunkerUri = (uri: string) => { const validateBunkerUri = (uri: string) => {
return uri.startsWith('bunker://'); return uri.startsWith('bunker://') || uri.startsWith('nostrconnect://');
}; };
const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin }) => { const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onSignup }) => {
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
const [isFileLoading, setIsFileLoading] = useState(false); const [isFileLoading, setIsFileLoading] = useState(false);
const [nsec, setNsec] = useState(''); const [nsec, setNsec] = useState('');
const [bunkerUri, setBunkerUri] = 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<{ const [errors, setErrors] = useState<{
nsec?: string; nsec?: string;
bunker?: string; bunker?: string;
@@ -38,17 +51,63 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin }) =
extension?: string; extension?: string;
}>({}); }>({});
const fileInputRef = useRef<HTMLInputElement>(null); const fileInputRef = useRef<HTMLInputElement>(null);
const abortControllerRef = useRef<AbortController | null>(null);
const login = useLoginActions(); 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 // Reset all state when dialog opens/closes
useEffect(() => { useEffect(() => {
if (isOpen) { if (!isOpen) {
// Reset state when dialog opens // Reset state when dialog closes
setIsLoading(false); setIsLoading(false);
setIsFileLoading(false); setIsFileLoading(false);
setNsec(''); setNsec('');
setBunkerUri(''); setBunkerUri('');
setNostrConnectParams(null);
setNostrConnectUri('');
setIsWaitingForConnect(false);
setConnectError(null);
setShowBunkerInput(false);
setErrors({}); setErrors({});
if (abortControllerRef.current) {
abortControllerRef.current.abort();
}
// Reset file input // Reset file input
if (fileInputRef.current) { if (fileInputRef.current) {
fileInputRef.current.value = ''; fileInputRef.current.value = '';
@@ -56,6 +115,29 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin }) =
} }
}, [isOpen]); }, [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 () => { const handleExtensionLogin = async () => {
setIsLoading(true); setIsLoading(true);
setErrors(prev => ({ ...prev, extension: undefined })); setErrors(prev => ({ ...prev, extension: undefined }));
@@ -69,8 +151,6 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin }) =
onClose(); onClose();
} catch (e: unknown) { } catch (e: unknown) {
const error = e as Error; const error = e as Error;
console.error('Bunker login failed:', error);
console.error('Nsec login failed:', error);
console.error('Extension login failed:', error); console.error('Extension login failed:', error);
setErrors(prev => ({ setErrors(prev => ({
...prev, ...prev,
@@ -118,7 +198,7 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin }) =
} }
if (!validateBunkerUri(bunkerUri)) { 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; return;
} }
@@ -170,26 +250,233 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin }) =
reader.readAsText(file); reader.readAsText(file);
}; };
const hasExtension = 'nostr' in window; const handleSignupClick = () => {
const [isMoreOptionsOpen, setIsMoreOptionsOpen] = useState(false); onClose();
if (onSignup) {
onSignup();
}
};
const renderTabs = () => ( const defaultTab = hasExtension ? 'extension' : 'connect';
<Tabs defaultValue="key" className="w-full">
<TabsList className="grid w-full grid-cols-2 bg-muted/80 rounded-lg mb-4"> return (
<TabsTrigger value="key" className="flex items-center gap-2"> <Dialog open={isOpen} onOpenChange={onClose}>
<span>Secret Key</span> <DialogContent
className={cn("max-w-[95vw] sm:max-w-md max-h-[90vh] max-h-[90dvh] p-0 overflow-hidden rounded-2xl overflow-y-scroll")}
>
<DialogHeader className={cn('px-6 pt-6 pb-1 relative')}>
<DialogDescription className="text-center">
Sign up or log in to continue
</DialogDescription>
</DialogHeader>
<div className='px-6 pt-2 pb-4 space-y-4 overflow-y-auto flex-1'>
{/* Prominent Sign Up Section */}
<div className='relative p-4 rounded-2xl bg-gradient-to-br from-blue-50 to-indigo-100 dark:from-blue-950/50 dark:to-indigo-950/50 border border-blue-200 dark:border-blue-800 overflow-hidden'>
<div className='relative z-10 text-center space-y-3'>
<div className='flex justify-center items-center gap-2 mb-2'>
<Sparkles className='w-5 h-5 text-blue-600' />
<span className='font-semibold text-blue-800 dark:text-blue-200'>
New to Nostr?
</span>
</div>
<p className='text-sm text-blue-700 dark:text-blue-300'>
Create a new account to get started. It's free and open.
</p>
<Button
onClick={handleSignupClick}
className='w-full rounded-full py-3 text-base font-semibold bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 transform transition-all duration-200 hover:scale-105 shadow-lg border-0'
>
<UserPlus className='w-4 h-4 mr-2' />
<span>Sign Up</span>
</Button>
</div>
</div>
{/* Divider */}
<div className='relative'>
<div className='absolute inset-0 flex items-center'>
<div className='w-full border-t border-gray-300 dark:border-gray-600'></div>
</div>
<div className='relative flex justify-center text-sm'>
<span className='px-3 bg-background text-muted-foreground'>
<span>Or log in</span>
</span>
</div>
</div>
{/* Login Methods */}
<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>
<TabsTrigger value="bunker" className="flex items-center gap-2"> <TabsTrigger value="connect" className="flex items-center gap-2">
<span>Remote Signer</span> <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>
</TabsList> </TabsList>
<TabsContent value='key' className='space-y-4'> <TabsContent value='extension' className='space-y-3 bg-muted'>
<form onSubmit={(e) => { {errors.extension && (
e.preventDefault(); <Alert variant="destructive">
handleKeyLogin(); <AlertTriangle className="h-4 w-4" />
}} className='space-y-4'> <AlertDescription>{errors.extension}</AlertDescription>
</Alert>
)}
<div className='text-center p-4 rounded-lg bg-gray-50 dark:bg-gray-800'>
<Shield className='w-12 h-12 mx-auto mb-3 text-primary' />
<p className='text-sm text-gray-600 dark:text-gray-300 mb-4'>
Login with one click using the browser extension
</p>
<div className="flex justify-center">
<Button
className='w-full rounded-full py-4'
onClick={handleExtensionLogin}
disabled={isLoading}
>
{isLoading ? 'Logging in...' : 'Login with Extension'}
</Button>
</div>
</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'> <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'>
<label htmlFor='nsec' className='text-sm font-medium'>
Secret Key (nsec)
</label>
<Input <Input
id='nsec' id='nsec'
type="password" type="password"
@@ -209,128 +496,50 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin }) =
)} )}
</div> </div>
<div className="flex space-x-2">
<Button <Button
type="submit" className='w-full rounded-full py-3'
size="lg" onClick={handleKeyLogin}
disabled={isLoading || !nsec.trim()} disabled={isLoading || !nsec.trim()}
className="flex-1"
> >
{isLoading ? 'Verifying...' : 'Log in'} {isLoading ? 'Verifying...' : 'Log In'}
</Button> </Button>
<div className='relative'>
<div className='absolute inset-0 flex items-center'>
<div className='w-full border-t border-muted'></div>
</div>
<div className='relative flex justify-center text-xs'>
<span className='px-2 bg-background text-muted-foreground'>
or
</span>
</div>
</div>
<div className='text-center'>
<input <input
type="file" type='file'
accept=".txt" accept='.txt'
className="hidden" className='hidden'
ref={fileInputRef} ref={fileInputRef}
onChange={handleFileUpload} onChange={handleFileUpload}
/> />
<Button <Button
type="button" variant='outline'
variant="outline" className='w-full'
size="lg"
onClick={() => fileInputRef.current?.click()} onClick={() => fileInputRef.current?.click()}
disabled={isLoading || isFileLoading} disabled={isLoading || isFileLoading}
className="px-3"
> >
<Upload className="w-4 h-4" /> <Upload className='w-4 h-4 mr-2' />
{isFileLoading ? 'Reading File...' : 'Upload Your Key File'}
</Button> </Button>
</div>
{errors.file && ( {errors.file && (
<p className="text-sm text-red-500 text-center">{errors.file}</p> <p className="text-sm text-red-500 mt-2">{errors.file}</p>
)}
</form>
</TabsContent>
<TabsContent value='bunker' className='space-y-4'>
<form onSubmit={(e) => {
e.preventDefault();
handleBunkerLogin();
}} className='space-y-4'>
<div className='space-y-2'>
<Input
id='bunkerUri'
value={bunkerUri}
onChange={(e) => {
setBunkerUri(e.target.value);
if (errors.bunker) setErrors(prev => ({ ...prev, bunker: undefined }));
}}
className={`rounded-lg border-gray-300 dark:border-gray-700 focus-visible:ring-primary ${
errors.bunker ? 'border-red-500' : ''
}`}
placeholder='bunker://'
autoComplete="off"
/>
{errors.bunker && (
<p className="text-sm text-red-500">{errors.bunker}</p>
)} )}
</div> </div>
</div>
<Button
type="submit"
size="lg"
className='w-full'
disabled={isLoading || !bunkerUri.trim()}
>
{isLoading ? 'Connecting...' : 'Log in'}
</Button>
</form>
</TabsContent> </TabsContent>
</Tabs> </Tabs>
);
return (
<Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent className="max-w-[95vw] sm:max-w-sm max-h-[90dvh] p-0 gap-6 overflow-hidden rounded-2xl overflow-y-auto">
<DialogHeader className="px-6 pt-6">
<DialogTitle className="text-lg font-semibold leading-none tracking-tight text-center">
Log in
</DialogTitle>
</DialogHeader>
<div className="flex size-40 text-8xl bg-primary/10 rounded-full items-center justify-center justify-self-center">
🔑
</div>
<div className='px-6 pb-6 space-y-4 overflow-y-auto'>
{/* Extension Login Button - shown if extension is available */}
{hasExtension && (
<div className="space-y-4">
{errors.extension && (
<Alert variant="destructive">
<AlertTriangle className="h-4 w-4" />
<AlertDescription>{errors.extension}</AlertDescription>
</Alert>
)}
<Button
className="w-full h-12 px-9"
onClick={handleExtensionLogin}
disabled={isLoading}
>
{isLoading ? 'Logging in...' : 'Log in with Extension'}
</Button>
</div>
)}
{/* Tabs - wrapped in collapsible if extension is available, otherwise shown directly */}
{hasExtension ? (
<Collapsible className="space-y-4" open={isMoreOptionsOpen} onOpenChange={setIsMoreOptionsOpen}>
<CollapsibleTrigger asChild>
<button className="w-full flex items-center justify-center gap-1 text-sm text-muted-foreground hover:text-foreground transition-colors">
<span>More Options</span>
<ChevronDown className={`w-4 h-4 transition-transform ${isMoreOptionsOpen ? 'rotate-180' : ''}`} />
</button>
</CollapsibleTrigger>
<CollapsibleContent>
{renderTabs()}
</CollapsibleContent>
</Collapsible>
) : (
renderTabs()
)}
</div> </div>
</DialogContent> </DialogContent>
</Dialog> </Dialog>
+429 -82
View File
@@ -2,26 +2,35 @@
// It is important that all functionality in this file is preserved, and should only be modified if explicitly requested. // It is important that all functionality in this file is preserved, and should only be modified if explicitly requested.
import React, { useState, useEffect, useRef } from 'react'; import React, { useState, useEffect, useRef } from 'react';
import { Download, Upload, Eye, EyeOff } from 'lucide-react'; import { Download, Key, UserPlus, FileText, Shield, User, Sparkles, LogIn, CheckCircle, Upload, Globe } from 'lucide-react';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input'; import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea'; import { Textarea } from '@/components/ui/textarea';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog"; import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Card, CardContent } from '@/components/ui/card';
import { toast } from '@/hooks/useToast'; import { toast } from '@/hooks/useToast';
import { useLoginActions } from '@/hooks/useLoginActions'; import { useLoginActions } from '@/hooks/useLoginActions';
import { useNostrPublish } from '@/hooks/useNostrPublish'; import { useNostrPublish } from '@/hooks/useNostrPublish';
import { useUploadFile } from '@/hooks/useUploadFile'; import { useUploadFile } from '@/hooks/useUploadFile';
import { generateSecretKey, getPublicKey, nip19 } from 'nostr-tools'; import { generateSecretKey, nip19 } from 'nostr-tools';
import { cn } from '@/lib/utils';
interface SignupDialogProps { interface SignupDialogProps {
isOpen: boolean; isOpen: boolean;
onClose: () => void; onClose: () => void;
onComplete?: () => void;
} }
const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose }) => { const sanitizeFilename = (filename: string) => {
const [step, setStep] = useState<'generate' | 'download' | 'profile'>('generate'); return filename.replace(/[^a-z0-9_.-]/gi, '_');
}
const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete }) => {
const [step, setStep] = useState<'welcome' | 'generate' | 'download' | 'profile' | 'done'>('welcome');
const [isLoading, setIsLoading] = useState(false);
const [nsec, setNsec] = useState(''); const [nsec, setNsec] = useState('');
const [showKey, setShowKey] = useState(false); const [showSparkles, setShowSparkles] = useState(false);
const [keySecured, setKeySecured] = useState<'none' | 'downloaded'>('none');
const [profileData, setProfileData] = useState({ const [profileData, setProfileData] = useState({
name: '', name: '',
about: '', about: '',
@@ -34,9 +43,34 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose }) => {
// Generate a proper nsec key using nostr-tools // Generate a proper nsec key using nostr-tools
const generateKey = () => { const generateKey = () => {
setIsLoading(true);
setShowSparkles(true);
// Add a dramatic pause for the key generation effect
setTimeout(() => {
try {
// Generate a new secret key
const sk = generateSecretKey(); const sk = generateSecretKey();
// Convert to nsec format
setNsec(nip19.nsecEncode(sk)); setNsec(nip19.nsecEncode(sk));
setStep('download'); setStep('download');
toast({
title: 'Your Secret Key is Ready!',
description: 'A new secret key has been generated for you.',
});
} catch {
toast({
title: 'Error',
description: 'Failed to generate key. Please try again.',
variant: 'destructive',
});
} finally {
setIsLoading(false);
setShowSparkles(false);
}
}, 2000);
}; };
const downloadKey = () => { const downloadKey = () => {
@@ -45,14 +79,8 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose }) => {
const blob = new Blob([nsec], { type: 'text/plain; charset=utf-8' }); const blob = new Blob([nsec], { type: 'text/plain; charset=utf-8' });
const url = globalThis.URL.createObjectURL(blob); const url = globalThis.URL.createObjectURL(blob);
const decoded = nip19.decode(nsec); // Sanitize filename
if (decoded.type !== 'nsec') { const filename = sanitizeFilename('nostr-nsec-key.txt');
throw new Error('Invalid nsec key');
}
const pubkey = getPublicKey(decoded.data);
const npub = nip19.npubEncode(pubkey);
const filename = `nostr-${location.hostname.replaceAll(/\./g, '-')}-${npub.slice(5, 9)}.nsec.txt`;
// Create a temporary link element and trigger download // Create a temporary link element and trigger download
const a = document.createElement('a'); const a = document.createElement('a');
@@ -66,9 +94,13 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose }) => {
globalThis.URL.revokeObjectURL(url); globalThis.URL.revokeObjectURL(url);
document.body.removeChild(a); document.body.removeChild(a);
// Continue to profile step // Mark as secured
login.nsec(nsec); setKeySecured('downloaded');
setStep('profile');
toast({
title: 'Secret Key Saved!',
description: 'Your key has been safely stored.',
});
} catch { } catch {
toast({ toast({
title: 'Download failed', title: 'Download failed',
@@ -78,6 +110,21 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose }) => {
} }
}; };
const finishKeySetup = () => {
try {
login.nsec(nsec);
setStep('profile');
} catch {
toast({
title: 'Login Failed',
description: 'Failed to login with the generated key. Please try again.',
variant: 'destructive',
});
}
};
const handleAvatarUpload = async (e: React.ChangeEvent<HTMLInputElement>) => { const handleAvatarUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0]; const file = e.target.files?.[0];
if (!file) return; if (!file) return;
@@ -111,6 +158,10 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose }) => {
const url = tags[0]?.[1]; const url = tags[0]?.[1];
if (url) { if (url) {
setProfileData(prev => ({ ...prev, picture: url })); setProfileData(prev => ({ ...prev, picture: url }));
toast({
title: 'Avatar uploaded!',
description: 'Your avatar has been uploaded successfully.',
});
} }
} catch { } catch {
toast({ toast({
@@ -122,6 +173,9 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose }) => {
}; };
const finishSignup = async (skipProfile = false) => { const finishSignup = async (skipProfile = false) => {
// Mark signup completion time for fallback welcome modal
localStorage.setItem('signup_completed', Date.now().toString());
try { try {
// Publish profile if user provided information // Publish profile if user provided information
if (!skipProfile && (profileData.name || profileData.about || profileData.picture)) { if (!skipProfile && (profileData.name || profileData.about || profileData.picture)) {
@@ -134,6 +188,30 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose }) => {
kind: 0, kind: 0,
content: JSON.stringify(metadata), content: JSON.stringify(metadata),
}); });
toast({
title: 'Profile Created!',
description: 'Your profile has been set up.',
});
}
// Close signup and show welcome modal
onClose();
if (onComplete) {
// Add a longer delay to ensure login state has fully propagated
setTimeout(() => {
onComplete();
}, 600);
} else {
// Fallback for when used without onComplete
setStep('done');
setTimeout(() => {
onClose();
toast({
title: 'Welcome!',
description: 'Your account is ready.',
});
}, 3000);
} }
} catch { } catch {
toast({ toast({
@@ -141,111 +219,372 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose }) => {
description: 'Your account was created but profile setup failed. You can update it later.', description: 'Your account was created but profile setup failed. You can update it later.',
variant: 'destructive', variant: 'destructive',
}); });
} finally {
// Still proceed to completion even if profile failed
onClose(); onClose();
if (onComplete) {
// Add a longer delay to ensure login state has fully propagated
setTimeout(() => {
onComplete();
}, 600);
} else {
// Fallback for when used without onComplete
setStep('done');
setTimeout(() => {
onClose();
toast({
title: 'Welcome!',
description: 'Your account is ready.',
});
}, 3000);
}
} }
}; };
const getTitle = () => { const getTitle = () => {
if (step === 'generate') return 'Sign up'; if (step === 'welcome') return (
if (step === 'download') return 'Secret Key'; <span className="flex items-center justify-center gap-2">
if (step === 'profile') return 'Create Your Profile'; Create Your Account
</span>
);
if (step === 'generate') return (
<span className="flex items-center justify-center gap-2">
Generating Your Key
</span>
);
if (step === 'download') return (
<span className="flex items-center justify-center gap-2">
Secret Key
</span>
);
if (step === 'profile') return (
<span className="flex items-center justify-center gap-2">
Create Your Profile
</span>
);
return (
<span className="flex items-center justify-center gap-2">
Welcome!
</span>
);
}; };
// Reset state when dialog opens // Reset state when dialog opens
useEffect(() => { useEffect(() => {
if (isOpen) { if (isOpen) {
setStep('generate'); setStep('welcome');
setIsLoading(false);
setNsec(''); setNsec('');
setShowKey(false); setShowSparkles(false);
setKeySecured('none');
setProfileData({ name: '', about: '', picture: '' }); setProfileData({ name: '', about: '', picture: '' });
} }
}, [isOpen]); }, [isOpen]);
// Add sparkle animation effect
useEffect(() => {
if (showSparkles) {
const interval = setInterval(() => {
// This will trigger re-renders for sparkle animation
}, 100);
return () => clearInterval(interval);
}
}, [showSparkles]);
return ( return (
<Dialog open={isOpen} onOpenChange={onClose}> <Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent className="max-w-[95vw] sm:max-w-sm max-h-[90dvh] p-0 gap-6 overflow-hidden rounded-2xl overflow-y-auto"> <DialogContent
<DialogHeader className="px-6 pt-6"> className={cn("max-w-[95vw] sm:max-w-md max-h-[90vh] max-h-[90dvh] p-0 overflow-hidden rounded-2xl flex flex-col")}
<DialogTitle className="text-lg font-semibold leading-none tracking-tight text-center"> >
<DialogHeader className={cn('px-6 pt-6 pb-1 relative flex-shrink-0')}>
<DialogTitle className={cn('font-semibold text-center text-lg')}>
{getTitle()} {getTitle()}
</DialogTitle> </DialogTitle>
</DialogHeader> </DialogHeader>
<div className='px-6 pt-2 pb-4 space-y-4 overflow-y-scroll flex-1'>
{/* Welcome Step - New engaging introduction */}
{step === 'welcome' && (
<div className='text-center space-y-4'>
{/* Hero illustration */}
<div className='relative p-6 rounded-2xl bg-gradient-to-br from-blue-50 to-indigo-100 dark:from-blue-950/50 dark:to-indigo-950/50'>
<div className='flex justify-center items-center space-x-4 mb-3'>
<div className='relative'>
<UserPlus className='w-12 h-12 text-blue-600' />
<Sparkles className='w-4 h-4 text-yellow-500 absolute -top-1 -right-1 animate-pulse' />
</div>
<Globe className='w-16 h-16 text-blue-700 animate-spin-slow' />
<div className='relative'>
<FileText className='w-12 h-12 text-blue-600' />
<Sparkles className='w-4 h-4 text-yellow-500 absolute -top-1 -left-1 animate-pulse' style={{animationDelay: '0.3s'}} />
</div>
</div>
<div className='px-6 pb-6 space-y-4 overflow-y-auto flex-1'> {/* Benefits */}
{/* Generate Step */} <div className='grid grid-cols-1 gap-2 text-sm'>
<div className='flex items-center justify-center gap-2 text-blue-700 dark:text-blue-300'>
<Shield className='w-4 h-4' />
Decentralized and censorship-resistant
</div>
<div className='flex items-center justify-center gap-2 text-blue-700 dark:text-blue-300'>
<User className='w-4 h-4' />
You are in control of your data
</div>
<div className='flex items-center justify-center gap-2 text-blue-700 dark:text-blue-300'>
<Globe className='w-4 h-4' />
Join a global network
</div>
</div>
</div>
<div className='space-y-3'>
<Button
className='w-full rounded-full py-6 text-lg font-semibold bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 transform transition-all duration-200 hover:scale-105 shadow-lg'
onClick={() => setStep('generate')}
>
<LogIn className='w-5 h-5 mr-2' />
Get Started
</Button>
</div>
</div>
)}
{/* Generate Step - Enhanced with animations */}
{step === 'generate' && ( {step === 'generate' && (
<div className='text-center space-y-6'> <div className='text-center space-y-4'>
<div className="flex size-40 text-8xl bg-primary/10 rounded-full items-center justify-center justify-self-center"> <div className='relative p-6 rounded-2xl bg-gradient-to-br from-blue-50 to-purple-100 dark:from-blue-950/50 dark:to-purple-950/50 overflow-hidden'>
🔑 {/* Animated background elements */}
</div> {showSparkles && (
<div className='absolute inset-0'>
<Button className="w-full h-12 px-9" onClick={generateKey}> {[...Array(12)].map((_, i) => (
Generate key <Sparkles
</Button> key={i}
</div> className={`absolute w-4 h-4 text-yellow-400 animate-ping`}
)} style={{
left: `${Math.random() * 80 + 10}%`,
{/* Download Step */} top: `${Math.random() * 80 + 10}%`,
{step === 'download' && ( animationDelay: `${Math.random() * 2}s`
<div className='space-y-4'> }}
<div className="flex size-16 text-4xl bg-primary/10 rounded-full items-center justify-center justify-self-center">
🔑
</div>
<div className="relative">
<Input
type={showKey ? "text" : "password"}
value={nsec}
readOnly
className="pr-10 font-mono text-sm"
/> />
<Button ))}
type="button" </div>
variant="ghost"
size="icon"
className="absolute right-0 top-0 h-full px-3 hover:bg-transparent"
onClick={() => setShowKey(!showKey)}
>
{showKey ? (
<EyeOff className="h-4 w-4 text-muted-foreground" />
) : (
<Eye className="h-4 w-4 text-muted-foreground" />
)} )}
</Button>
<div className='relative z-10'>
{isLoading ? (
<div className='space-y-3'>
<div className='relative'>
<Key className='w-20 h-20 text-primary mx-auto animate-pulse' />
<div className='absolute inset-0 flex items-center justify-center'>
<div className='w-24 h-24 border-4 border-yellow-400 border-t-transparent rounded-full animate-spin'></div>
</div>
</div>
<div className='space-y-2'>
<p className='text-lg font-semibold text-primary flex items-center justify-center gap-2'>
<Sparkles className='w-5 h-5' />
Generating your secret key...
</p>
<p className='text-sm text-muted-foreground'>
Creating your secure key
</p>
</div>
</div>
) : (
<div className='space-y-3'>
<Key className='w-20 h-20 text-primary mx-auto' />
<div className='space-y-2'>
<p className='text-lg font-semibold'>
Ready to generate your secret key?
</p>
<p className='text-sm text-muted-foreground px-5'>
This key will be your password to access applications within the Nostr network.
</p>
</div>
</div>
)}
</div>
</div> </div>
{!isLoading && (
<Button <Button
className="w-full h-12 px-9" className='w-full rounded-full py-6 text-lg font-semibold bg-gradient-to-r from-purple-600 to-blue-600 hover:from-purple-700 hover:to-blue-700 transform transition-all duration-200 hover:scale-105 shadow-lg'
onClick={downloadKey} onClick={generateKey}
disabled={isLoading}
> >
<Download className="size-4" /> <Sparkles className='w-5 h-5 mr-2' />
Download key Generate My Secret Key
</Button> </Button>
)}
</div>
)}
<div className='mx-auto max-w-sm'> {/* Download Step - Whimsical and magical */}
<div className='p-3 bg-amber-50 dark:bg-amber-950/20 rounded-lg border border-amber-200 dark:border-amber-800'> {step === 'download' && (
<div className='text-center space-y-4'>
{/* Key reveal */}
<div className='relative p-6 rounded-2xl bg-gradient-to-br from-blue-50 to-indigo-100 dark:from-blue-950/50 dark:to-indigo-950/50 overflow-hidden'>
{/* Sparkles */}
<div className='absolute inset-0 pointer-events-none'>
<Sparkles className='absolute top-3 left-4 w-3 h-3 text-yellow-400 animate-pulse' style={{animationDelay: '0s'}} />
<Sparkles className='absolute top-6 right-6 w-3 h-3 text-yellow-500 animate-pulse' style={{animationDelay: '0.5s'}} />
<Sparkles className='absolute bottom-4 left-6 w-3 h-3 text-yellow-400 animate-pulse' style={{animationDelay: '1s'}} />
<Sparkles className='absolute bottom-3 right-4 w-3 h-3 text-yellow-500 animate-pulse' style={{animationDelay: '1.5s'}} />
</div>
<div className='relative z-10 flex justify-center items-center mb-3'>
<div className='relative'>
<div className='w-16 h-16 bg-gradient-to-br from-blue-200 to-indigo-300 rounded-full flex items-center justify-center shadow-lg animate-pulse'>
<Key className='w-8 h-8 text-indigo-800' />
</div>
<div className='absolute -top-1 -right-1 w-5 h-5 bg-blue-500 rounded-full flex items-center justify-center animate-bounce'>
<Sparkles className='w-3 h-3 text-white' />
</div>
</div>
</div>
<div className='relative z-10 space-y-2'>
<p className='text-base font-semibold'>
Your secret key has been generated!
</p>
{/* Warning */}
<div className='relative mx-auto max-w-sm'>
<div className='p-3 bg-gradient-to-r from-amber-100 via-yellow-50 to-amber-100 dark:from-amber-950/40 dark:via-yellow-950/20 dark:to-amber-950/40 rounded-lg border-2 border-amber-300 dark:border-amber-700 shadow-md'>
<div className='flex items-center gap-2 mb-1'> <div className='flex items-center gap-2 mb-1'>
<span className='text-xs font-semibold text-amber-800 dark:text-amber-200'> <FileText className='w-3 h-3 text-amber-700' />
<span className='text-xs font-bold text-amber-800 dark:text-amber-200'>
Important Warning Important Warning
</span> </span>
</div> </div>
<p className='text-xs text-amber-900 dark:text-amber-300'> <p className='text-xs text-red-700 dark:text-amber-300 italic'>
This key is your primary and only means of accessing your account. Store it safely and securely. Please download your key to continue. This key is your primary and only means of accessing your account. Store it safely and securely.
</p> </p>
</div> </div>
</div> </div>
</div> </div>
</div>
{/* Key vault */}
{/* Security options */}
<div className='space-y-3'>
<div className='grid grid-cols-1 gap-2'>
{/* Download Option */}
<Card className={`cursor-pointer transition-all duration-200 ${
keySecured === 'downloaded'
? 'ring-2 ring-green-500 bg-green-50 dark:bg-green-950/20'
: 'hover:bg-primary/5 hover:border-primary/20'
}`}>
<CardContent className='p-3'>
<Button
variant="ghost"
className='w-full h-auto p-0 justify-start hover:bg-transparent'
onClick={downloadKey}
>
<div className='flex items-center gap-3 w-full'>
<div className={`p-1.5 rounded-lg ${
keySecured === 'downloaded'
? 'bg-green-100 dark:bg-green-900'
: 'bg-primary/10'
}`}>
{keySecured === 'downloaded' ? (
<CheckCircle className='w-4 h-4 text-green-600' />
) : (
<Download className='w-4 h-4 text-primary' />
)}
</div>
<div className='flex-1 text-left'>
<div className='font-medium text-sm'>
Download as File
</div>
<div className='text-xs text-muted-foreground'>
Save as nostr-nsec-key.txt file
</div>
</div>
{keySecured === 'downloaded' && (
<div className='text-xs font-medium text-green-600'>
✓ Downloaded
</div>
)}
</div>
</Button>
</CardContent>
</Card>
</div>
{/* Continue button */}
<Button
className={`w-full rounded-full py-4 text-base font-semibold transform transition-all duration-200 shadow-lg ${
keySecured === 'downloaded'
? 'bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 dark:from-blue-950/50 dark:to-purple-950/50 hover:scale-105'
: 'bg-gradient-to-r from-blue-600/60 to-indigo-600/60 text-muted cursor-not-allowed'
}`}
onClick={finishKeySetup}
disabled={keySecured !== 'downloaded'}
>
<LogIn className='w-4 h-4 mr-2 flex-shrink-0' />
<span className="text-center leading-tight">
{keySecured === 'none' ? (
<>
Please download your key first
</>
) : (
<>
<span className="hidden sm:inline">My Key is Safe - Continue</span>
<span className="sm:hidden">Key Secured - Continue</span>
</>
)}
</span>
</Button>
</div>
</div>
)} )}
{/* Profile Step */} {/* Profile Step - Optional profile setup */}
{step === 'profile' && ( {step === 'profile' && (
<div className='text-center space-y-4'> <div className='text-center space-y-4'>
{/* Profile setup illustration */}
<div className='relative p-6 rounded-2xl bg-gradient-to-br from-blue-50 to-indigo-100 dark:from-blue-950/50 dark:to-indigo-950/50 overflow-hidden'>
{/* Sparkles */}
<div className='absolute inset-0 pointer-events-none'>
<Sparkles className='absolute top-3 left-4 w-3 h-3 text-yellow-400 animate-pulse' style={{animationDelay: '0s'}} />
<Sparkles className='absolute top-6 right-6 w-3 h-3 text-yellow-500 animate-pulse' style={{animationDelay: '0.5s'}} />
<Sparkles className='absolute bottom-4 left-6 w-3 h-3 text-yellow-400 animate-pulse' style={{animationDelay: '1s'}} />
</div>
<div className='relative z-10 flex justify-center items-center mb-3'>
<div className='relative'>
<div className='w-16 h-16 bg-gradient-to-br from-blue-200 to-indigo-300 rounded-full flex items-center justify-center shadow-lg'>
<User className='w-8 h-8 text-blue-800' />
</div>
<div className='absolute -top-1 -right-1 w-5 h-5 bg-blue-500 rounded-full flex items-center justify-center animate-bounce'>
<Sparkles className='w-3 h-3 text-white' />
</div>
</div>
</div>
<div className='relative z-10 space-y-2'>
<p className='text-base font-semibold'>
Almost there! Let's set up your profile
</p>
<p className='text-sm text-muted-foreground'>
Your profile is your identity on Nostr.
</p>
</div>
</div>
{/* Publishing status indicator */} {/* Publishing status indicator */}
{isPublishing && ( {isPublishing && (
<div className='p-4 rounded-lg bg-muted border'> <div className='relative p-4 rounded-xl bg-gradient-to-r from-blue-50 to-indigo-50 dark:from-blue-950/30 dark:to-indigo-950/30 border border-blue-200 dark:border-blue-800'>
<div className='flex items-center justify-center gap-3'> <div className='flex items-center justify-center gap-3'>
<div className='w-5 h-5 border-2 border-primary border-t-transparent rounded-full animate-spin' /> <div className='w-5 h-5 border-2 border-blue-600 border-t-transparent rounded-full animate-spin' />
<span className='text-sm font-medium'> <span className='text-sm font-medium text-blue-700 dark:text-blue-300'>
Publishing your profile... Publishing your profile...
</span> </span>
</div> </div>
@@ -263,6 +602,7 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose }) => {
value={profileData.name} value={profileData.name}
onChange={(e) => setProfileData(prev => ({ ...prev, name: e.target.value }))} onChange={(e) => setProfileData(prev => ({ ...prev, name: e.target.value }))}
placeholder='Your name' placeholder='Your name'
className='rounded-lg'
disabled={isPublishing} disabled={isPublishing}
/> />
</div> </div>
@@ -276,7 +616,7 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose }) => {
value={profileData.about} value={profileData.about}
onChange={(e) => setProfileData(prev => ({ ...prev, about: e.target.value }))} onChange={(e) => setProfileData(prev => ({ ...prev, about: e.target.value }))}
placeholder='Tell others about yourself...' placeholder='Tell others about yourself...'
className='resize-none' className='rounded-lg resize-none'
rows={3} rows={3}
disabled={isPublishing} disabled={isPublishing}
/> />
@@ -292,7 +632,7 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose }) => {
value={profileData.picture} value={profileData.picture}
onChange={(e) => setProfileData(prev => ({ ...prev, picture: e.target.value }))} onChange={(e) => setProfileData(prev => ({ ...prev, picture: e.target.value }))}
placeholder='https://example.com/your-avatar.jpg' placeholder='https://example.com/your-avatar.jpg'
className='flex-1' className='rounded-lg flex-1'
disabled={isPublishing} disabled={isPublishing}
/> />
<input <input
@@ -308,6 +648,7 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose }) => {
size='icon' size='icon'
onClick={() => avatarFileInputRef.current?.click()} onClick={() => avatarFileInputRef.current?.click()}
disabled={isUploading || isPublishing} disabled={isUploading || isPublishing}
className='rounded-lg shrink-0'
title='Upload avatar image' title='Upload avatar image'
> >
{isUploading ? ( {isUploading ? (
@@ -323,7 +664,7 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose }) => {
{/* Action buttons */} {/* Action buttons */}
<div className='space-y-3'> <div className='space-y-3'>
<Button <Button
className='w-full' className='w-full rounded-full py-4 text-base font-semibold bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 transform transition-all duration-200 hover:scale-105 shadow-lg disabled:opacity-50 disabled:cursor-not-allowed disabled:transform-none'
onClick={() => finishSignup(false)} onClick={() => finishSignup(false)}
disabled={isPublishing || isUploading} disabled={isPublishing || isUploading}
> >
@@ -333,18 +674,24 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose }) => {
Creating Profile... Creating Profile...
</> </>
) : ( ) : (
'Create profile' <>
<User className='w-4 h-4 mr-2' />
Create Profile & Finish
</>
)} )}
</Button> </Button>
<Button <Button
variant='outline' variant='outline'
className='w-full' className='w-full rounded-full py-3 disabled:opacity-50 disabled:cursor-not-allowed'
onClick={() => finishSignup(true)} onClick={() => finishSignup(true)}
disabled={isPublishing || isUploading} disabled={isPublishing || isUploading}
> >
{isPublishing ? ( {isPublishing ? (
'Setting up account...' <>
<div className='w-4 h-4 mr-2 border-2 border-current border-t-transparent rounded-full animate-spin' />
Setting up account...
</>
) : ( ) : (
'Skip for now' 'Skip for now'
)} )}
+1 -1
View File
@@ -43,7 +43,7 @@ const DialogContent = React.forwardRef<
> >
{children} {children}
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground"> <DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
<X className="size-5" /> <X className="h-4 w-4" />
<span className="sr-only">Close</span> <span className="sr-only">Close</span>
</DialogPrimitive.Close> </DialogPrimitive.Close>
</DialogPrimitive.Content> </DialogPrimitive.Content>
+124
View File
@@ -1,11 +1,67 @@
import { NConnectSigner, NSecSigner } from '@nostrify/nostrify';
import { useNostr } from '@nostrify/react'; import { useNostr } from '@nostrify/react';
import { NLogin, useNostrLogin } from '@nostrify/react/login'; 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. // 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() { export function useLoginActions() {
const { nostr } = useNostr(); const { nostr } = useNostr();
const { logins, addLogin, removeLogin } = useNostrLogin(); const { logins, addLogin, removeLogin } = useNostrLogin();
const { config } = useAppContext();
return { return {
// Login with a Nostr secret key // Login with a Nostr secret key
@@ -23,6 +79,74 @@ export function useLoginActions() {
const login = await NLogin.fromExtension(); const login = await NLogin.fromExtension();
addLogin(login); 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 // Log out the current user
async logout(): Promise<void> { async logout(): Promise<void> {
const login = logins[0]; const login = logins[0];
+1 -1
View File
@@ -32,7 +32,7 @@
--input: 214.3 31.8% 91.4%; --input: 214.3 31.8% 91.4%;
--ring: 222.2 84% 4.9%; --ring: 222.2 84% 4.9%;
--radius: 0.75rem; --radius: 0.5rem;
--sidebar-background: 0 0% 98%; --sidebar-background: 0 0% 98%;
+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>
);
}
+19
View File
@@ -0,0 +1,19 @@
{
"name": "mkstack",
"title": "MKStack",
"description": "Build Nostr apps in minutes with this React framework",
"uri": "git+https://gitlab.com/soapbox-pub/mkstack.git",
"image": "https://gitlab.com/-/project/69048882/uploads/0a9e3a19f2901d5c772952c1de10ce4f/image.png",
"commands": [
"npm",
"npx"
],
"tech": [
"react",
"typescript",
"tailwind",
"shadcn-ui",
"nostrify",
"vite"
]
}