20 changed files with 1208 additions and 456 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
- `/docs/`: Specialized documentation for implementation patterns and features
- `/src/components/`: UI components including NostrProvider for Nostr integration
- `/src/components/ui/`: shadcn/ui components (48+ components available)
- `/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.
## 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
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],
'#t': ['farming'],
limit: 20
}]);
}], { signal });
```
### 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.
### 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 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');
// 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
await relay.event({ kind: 1, content: 'Hello from specific relay!' });
@@ -425,7 +340,7 @@ function useRelayGroup() {
]);
// 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
await relayGroup.event({ kind: 1, content: 'Hello from relay group!' });
@@ -475,7 +390,8 @@ function usePosts() {
return useQuery({
queryKey: ['posts'],
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
},
});
@@ -495,7 +411,7 @@ const events = await nostr.query([
'#e': [eventId],
limit: 150,
}
]);
], { signal });
// Separate by type in JavaScript
const notes = events.filter((e) => e.kind === 1);
@@ -507,9 +423,9 @@ const genericReposts = events.filter((e) => e.kind === 16);
```typescript
// This creates unnecessary load and can trigger rate limiting
const [notes, reposts, genericReposts] = await Promise.all([
nostr.query([{ kinds: [1], '#e': [eventId] }]),
nostr.query([{ kinds: [6], '#e': [eventId] }]),
nostr.query([{ kinds: [16], '#e': [eventId] }]),
nostr.query([{ kinds: [1], '#e': [eventId] }], { signal }),
nostr.query([{ kinds: [6], '#e': [eventId] }], { signal }),
nostr.query([{ kinds: [16], '#e': [eventId] }], { signal }),
]);
```
@@ -563,7 +479,8 @@ function useCalendarEvents() {
return useQuery({
queryKey: ['calendar-events'],
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
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
const events = await nostr.query(
[{ ids: [naddr] }],
{ signal }
);
```
@@ -791,6 +709,7 @@ const events = await nostr.query(
authors: [naddr.pubkey],
'#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.
### 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
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: {
relays: [
{ 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 },
],
updatedAt: 0,
@@ -1120,7 +1053,6 @@ When users specify color schemes:
- Follow shadcn/ui patterns for component variants
- Implement responsive design with Tailwind breakpoints
- 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
@@ -1,9 +1,4 @@
---
name: ai-chat
description: Build AI-powered chat interfaces, implement streaming responses, or integrate with Shakespeare AI.
---
# AI Integration with Shakespeare API
### 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.
@@ -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
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 @@
---
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
### 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.
@@ -1,9 +1,4 @@
---
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
### Infinite Scroll for Nostr Feeds
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": {
"@fontsource-variable/inter": "^5.2.6",
"@getalby/sdk": "^5.1.1",
"@hookform/resolvers": "^5.2.2",
"@nostrify/nostrify": "^0.49.2",
"@nostrify/react": "^0.2.24",
"@hookform/resolvers": "^3.9.0",
"@nostrify/nostrify": "^0.48.2",
"@nostrify/react": "^0.2.20",
"@radix-ui/react-accordion": "^1.2.0",
"@radix-ui/react-alert-dialog": "^1.1.1",
"@radix-ui/react-aspect-ratio": "^1.1.0",
@@ -54,10 +54,11 @@
"lucide-react": "^0.462.0",
"nostr-tools": "^2.13.0",
"qrcode": "^1.5.4",
"qrcode.react": "^4.2.0",
"react": "^18.3.1",
"react-day-picker": "^8.10.1",
"react-dom": "^18.3.1",
"react-hook-form": "^7.71.1",
"react-hook-form": "^7.53.0",
"react-intersection-observer": "^9.16.0",
"react-resizable-panels": "^2.1.3",
"react-router-dom": "^6.26.2",
@@ -65,7 +66,7 @@
"tailwind-merge": "^2.5.2",
"tailwindcss-animate": "^1.0.7",
"vaul": "^0.9.3",
"zod": "^4.3.6"
"zod": "^3.25.71"
},
"devDependencies": {
"@eslint/js": "^9.9.0",
@@ -986,15 +987,12 @@
}
},
"node_modules/@hookform/resolvers": {
"version": "5.2.2",
"resolved": "https://registry.npmjs.org/@hookform/resolvers/-/resolvers-5.2.2.tgz",
"integrity": "sha512-A/IxlMLShx3KjV/HeTcTfaMxdwy690+L/ZADoeaTltLx+CVuzkeVIPuybK3jrRfw7YZnmdKsVVHAlEPIAEUNlA==",
"version": "3.10.0",
"resolved": "https://registry.npmjs.org/@hookform/resolvers/-/resolvers-3.10.0.tgz",
"integrity": "sha512-79Dv+3mDF7i+2ajj7SkypSKHhl1cbln1OGavqrsF7p6mbUv11xpqpacPsGDCTRvCSjEEIez2ef1NveSVL3b0Ag==",
"license": "MIT",
"dependencies": {
"@standard-schema/utils": "^0.3.0"
},
"peerDependencies": {
"react-hook-form": "^7.55.0"
"react-hook-form": "^7.0.0"
}
},
"node_modules/@html-eslint/eslint-plugin": {
@@ -1256,11 +1254,11 @@
}
},
"node_modules/@nostrify/nostrify": {
"version": "0.49.2",
"resolved": "https://registry.npmjs.org/@nostrify/nostrify/-/nostrify-0.49.2.tgz",
"integrity": "sha512-JMiGifc/XX4QhzFnmJVw00UjcOS295w/NYth9mJH0cbS0EqPQ/4HBn33P0DGW3iE5EAkk+n98cnwzYeIPtn9pQ==",
"version": "0.48.2",
"resolved": "https://registry.npmjs.org/@nostrify/nostrify/-/nostrify-0.48.2.tgz",
"integrity": "sha512-Zze3RASsgn4MLQCuC5I4XR0WJi9G3J8qZpVjVIPvkw6vbZRct++JgavcZSxwKjJH1hHq+8d90IrHMOrskNQ8NQ==",
"dependencies": {
"@nostrify/types": "0.36.9",
"@nostrify/types": "0.36.8",
"@scure/base": "^2.0.0",
"@smithy/util-base64": "^4.3.0",
"@smithy/util-hex-encoding": "^4.2.0",
@@ -1269,7 +1267,7 @@
"nostr-tools": "^2.13.0",
"websocket-ts": "^2.2.1",
"ws": "^8.18.3",
"zod": "^4.3.6"
"zod": "^3.23.8"
}
},
"node_modules/@nostrify/nostrify/node_modules/@scure/base": {
@@ -1297,12 +1295,12 @@
"license": "MIT"
},
"node_modules/@nostrify/react": {
"version": "0.2.24",
"resolved": "https://registry.npmjs.org/@nostrify/react/-/react-0.2.24.tgz",
"integrity": "sha512-LdB6UjNKZ/Xhz+jj8CRCcudHt4WNNVZMgJsiO+XAloqWE8oPRf1G2i1k6I/eF6buCJokKE1PFUTMlyieOpIXNQ==",
"version": "0.2.20",
"resolved": "https://registry.npmjs.org/@nostrify/react/-/react-0.2.20.tgz",
"integrity": "sha512-Tvkdr5X+MQxh6CKKthk9Idch3vFp5nPcm57uJZJWrIqBtuj9jxMamM6uEo2lQAr0ugK52xDlyD50lRDRe0RMbQ==",
"dependencies": {
"@nostrify/nostrify": "0.49.2",
"@nostrify/types": "0.36.9",
"@nostrify/nostrify": "0.48.2",
"@nostrify/types": "0.36.8",
"@tanstack/react-query": "^5.69.0",
"nostr-tools": "^2.13.0",
"react": "^18.0.0",
@@ -1310,9 +1308,9 @@
}
},
"node_modules/@nostrify/types": {
"version": "0.36.9",
"resolved": "https://registry.npmjs.org/@nostrify/types/-/types-0.36.9.tgz",
"integrity": "sha512-tMx/r0W+QoVRRgs8d6ltaSgrftasOXuFsi33kW8WirswCy2b3UR1tqRgc0iBU9zRa9XR0nlej/wJZW+6wUFi+Q=="
"version": "0.36.8",
"resolved": "https://registry.npmjs.org/@nostrify/types/-/types-0.36.8.tgz",
"integrity": "sha512-tmpz5pkU8oXu7+V1qxvAzuoo8s5x4Gvo7h+JRm+JAW6x/2VZ8aQoA54yhn89qZ9agciMJhVdhqCm1PlK55w17A=="
},
"node_modules/@pkgjs/parseargs": {
"version": "0.11.0",
@@ -2679,9 +2677,9 @@
"license": "MIT"
},
"node_modules/@remix-run/router": {
"version": "1.23.2",
"resolved": "https://registry.npmjs.org/@remix-run/router/-/router-1.23.2.tgz",
"integrity": "sha512-Ic6m2U/rMjTkhERIa/0ZtXJP17QUi2CbWE7cqx4J58M8aA3QTfW+2UlQ4psvTX9IO1RfNVhK3pcpdjej7L+t2w==",
"version": "1.23.0",
"resolved": "https://registry.npmjs.org/@remix-run/router/-/router-1.23.0.tgz",
"integrity": "sha512-O3rHJzAQKamUz1fvE0Qaw0xSFqsA/yafi2iqeE0pvdFtCO1viYx8QL6f3Ln/aCCTLxs68SLf0KPM9eSeM8yBnA==",
"license": "MIT",
"engines": {
"node": ">=14.0.0"
@@ -2734,6 +2732,7 @@
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -2747,6 +2746,7 @@
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -2760,6 +2760,7 @@
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -2773,6 +2774,7 @@
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -2786,6 +2788,7 @@
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -2799,6 +2802,7 @@
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -2812,6 +2816,7 @@
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -2825,6 +2830,7 @@
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -2838,6 +2844,7 @@
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -2851,6 +2858,7 @@
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -2864,6 +2872,7 @@
"cpu": [
"loong64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -2877,6 +2886,7 @@
"cpu": [
"ppc64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -2890,6 +2900,7 @@
"cpu": [
"riscv64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -2903,6 +2914,7 @@
"cpu": [
"riscv64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -2916,6 +2928,7 @@
"cpu": [
"s390x"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -2929,6 +2942,7 @@
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -2942,6 +2956,7 @@
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -2955,6 +2970,7 @@
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -2968,6 +2984,7 @@
"cpu": [
"ia32"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -2981,6 +2998,7 @@
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -3102,12 +3120,6 @@
"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": {
"version": "1.11.24",
"resolved": "https://registry.npmjs.org/@swc/core/-/core-1.11.24.tgz",
@@ -6669,6 +6681,15 @@
"node": ">=10.13.0"
}
},
"node_modules/qrcode.react": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/qrcode.react/-/qrcode.react-4.2.0.tgz",
"integrity": "sha512-QpgqWi8rD9DsS9EP3z7BT+5lY5SFhsqGjpgW5DY/i3mK4M9DTBNz3ErMi8BWYEfI3L0d8GIbGmcdFAS1uIRGjA==",
"license": "ISC",
"peerDependencies": {
"react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
}
},
"node_modules/queue-microtask": {
"version": "1.2.3",
"resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz",
@@ -6729,9 +6750,9 @@
}
},
"node_modules/react-hook-form": {
"version": "7.71.1",
"resolved": "https://registry.npmjs.org/react-hook-form/-/react-hook-form-7.71.1.tgz",
"integrity": "sha512-9SUJKCGKo8HUSsCO+y0CtqkqI5nNuaDqTxyqPsZPqIwudpj4rCrAz/jZV+jn57bx5gtZKOh3neQu94DXMc+w5w==",
"version": "7.56.1",
"resolved": "https://registry.npmjs.org/react-hook-form/-/react-hook-form-7.56.1.tgz",
"integrity": "sha512-qWAVokhSpshhcEuQDSANHx3jiAEFzu2HAaaQIzi/r9FNPm1ioAvuJSD4EuZzWd7Al7nTRKcKPnBKO7sRn+zavQ==",
"license": "MIT",
"engines": {
"node": ">=18.0.0"
@@ -6823,12 +6844,12 @@
}
},
"node_modules/react-router": {
"version": "6.30.3",
"resolved": "https://registry.npmjs.org/react-router/-/react-router-6.30.3.tgz",
"integrity": "sha512-XRnlbKMTmktBkjCLE8/XcZFlnHvr2Ltdr1eJX4idL55/9BbORzyZEaIkBFDhFGCEWBBItsVrDxwx3gnisMitdw==",
"version": "6.30.0",
"resolved": "https://registry.npmjs.org/react-router/-/react-router-6.30.0.tgz",
"integrity": "sha512-D3X8FyH9nBcTSHGdEKurK7r8OYE1kKFn3d/CF+CoxbSHkxU7o37+Uh7eAHRXr6k2tSExXYO++07PeXJtA/dEhQ==",
"license": "MIT",
"dependencies": {
"@remix-run/router": "1.23.2"
"@remix-run/router": "1.23.0"
},
"engines": {
"node": ">=14.0.0"
@@ -6838,13 +6859,13 @@
}
},
"node_modules/react-router-dom": {
"version": "6.30.3",
"resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-6.30.3.tgz",
"integrity": "sha512-pxPcv1AczD4vso7G4Z3TKcvlxK7g7TNt3/FNGMhfqyntocvYKj+GCatfigGDjbLozC4baguJ0ReCigoDJXb0ag==",
"version": "6.30.0",
"resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-6.30.0.tgz",
"integrity": "sha512-x30B78HV5tFk8ex0ITwzC9TTZMua4jGyA9IUlH1JLQYQTFyxr/ZxwOJq7evg1JX1qGVUcvhsmQSKdPncQrjTgA==",
"license": "MIT",
"dependencies": {
"@remix-run/router": "1.23.2",
"react-router": "6.30.3"
"@remix-run/router": "1.23.0",
"react-router": "6.30.0"
},
"engines": {
"node": ">=14.0.0"
@@ -8510,9 +8531,9 @@
}
},
"node_modules/zod": {
"version": "4.3.6",
"resolved": "https://registry.npmjs.org/zod/-/zod-4.3.6.tgz",
"integrity": "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==",
"version": "3.25.71",
"resolved": "https://registry.npmjs.org/zod/-/zod-3.25.71.tgz",
"integrity": "sha512-BsBc/NPk7h8WsUWYWYL+BajcJPY8YhjelaWu2NMLuzgraKAz4Lb4/6K11g9jpuDetjMiqhZ6YaexFLOC0Ogi3Q==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/colinhacks"
+10 -8
View File
@@ -6,14 +6,15 @@
"scripts": {
"dev": "npm i --silent && vite",
"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": {
"@fontsource-variable/inter": "^5.2.6",
"@getalby/sdk": "^7.0.0",
"@hookform/resolvers": "^5.2.2",
"@nostrify/nostrify": "^0.49.2",
"@nostrify/react": "^0.2.24",
"@getalby/sdk": "^5.1.1",
"@hookform/resolvers": "^3.9.0",
"@nostrify/nostrify": "^0.48.2",
"@nostrify/react": "^0.2.20",
"@radix-ui/react-accordion": "^1.2.0",
"@radix-ui/react-alert-dialog": "^1.1.1",
"@radix-ui/react-aspect-ratio": "^1.1.0",
@@ -53,12 +54,13 @@
"idb": "^8.0.3",
"input-otp": "^1.2.4",
"lucide-react": "^0.462.0",
"nostr-tools": "^2.21.0",
"nostr-tools": "^2.13.0",
"qrcode": "^1.5.4",
"qrcode.react": "^4.2.0",
"react": "^18.3.1",
"react-day-picker": "^8.10.1",
"react-dom": "^18.3.1",
"react-hook-form": "^7.71.1",
"react-hook-form": "^7.53.0",
"react-intersection-observer": "^9.16.0",
"react-resizable-panels": "^2.1.3",
"react-router-dom": "^6.26.2",
@@ -66,7 +68,7 @@
"tailwind-merge": "^2.5.2",
"tailwindcss-animate": "^1.0.7",
"vaul": "^0.9.3",
"zod": "^4.3.6"
"zod": "^3.25.71"
},
"devDependencies": {
"@eslint/js": "^9.9.0",
+2
View File
@@ -3,6 +3,7 @@ import { ScrollToTop } from "./components/ScrollToTop";
import Index from "./pages/Index";
import { NIP19Page } from "./pages/NIP19Page";
import { RemoteLoginSuccess } from "./pages/RemoteLoginSuccess";
import NotFound from "./pages/NotFound";
export function AppRouter() {
@@ -11,6 +12,7 @@ export function AppRouter() {
<ScrollToTop />
<Routes>
<Route path="/" element={<Index />} />
<Route path="/remoteloginsuccess" element={<RemoteLoginSuccess />} />
{/* NIP-19 route for npub1, note1, naddr1, nevent1, nprofile1 */}
<Route path="/:nip19" element={<NIP19Page />} />
{/* ADD ALL CUSTOM ROUTES ABOVE THE CATCH-ALL "*" ROUTE */}
+1 -1
View File
@@ -14,7 +14,7 @@ interface AppProviderProps {
// Zod schema for RelayMetadata validation
const RelayMetadataSchema = z.object({
relays: z.array(z.object({
url: z.url(),
url: z.string().url(),
read: z.boolean(),
write: z.boolean(),
})),
+2 -7
View File
@@ -45,7 +45,7 @@ export function NoteContent({
href={url}
target="_blank"
rel="noopener noreferrer"
className="text-blue-500 hover:underline break-all"
className="text-blue-500 hover:underline"
>
{url}
</a>
@@ -61,18 +61,13 @@ export function NoteContent({
parts.push(
<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 {
// For other types, just show as a link
parts.push(
<Link
key={`nostr-${keyCounter++}`}
to={`/${nostrId}`}
className="text-blue-500 hover:underline break-all"
className="text-blue-500 hover:underline"
>
{fullMatch}
</Link>
+11 -1
View File
@@ -1,7 +1,7 @@
// NOTE: This file is stable and usually should not be modified.
// It is important that all functionality in this file is preserved, and should only be modified if explicitly requested.
import { ChevronDown, LogOut, UserIcon, UserPlus } from 'lucide-react';
import { ChevronDown, LogOut, UserIcon, UserPlus, Wallet } from 'lucide-react';
import {
DropdownMenu,
DropdownMenuContent,
@@ -10,6 +10,7 @@ import {
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu.tsx';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar.tsx';
import { WalletModal } from '@/components/WalletModal';
import { useLoggedInAccounts, type Account } from '@/hooks/useLoggedInAccounts';
import { genUserName } from '@/lib/genUserName';
@@ -59,6 +60,15 @@ export function AccountSwitcher({ onAddAccountClick }: AccountSwitcherProps) {
</DropdownMenuItem>
))}
<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
onClick={onAddAccountClick}
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.
import { useState } from 'react';
import { User, UserPlus } from 'lucide-react';
import { Button } from '@/components/ui/button.tsx';
import LoginDialog from './LoginDialog';
import SignupDialog from './SignupDialog';
@@ -33,13 +34,15 @@ export function LoginArea({ className }: LoginAreaProps) {
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'
>
<User className='w-4 h-4' />
<span className='truncate'>Log in</span>
</Button><Button
onClick={() => setSignupDialogOpen(true)}
variant="outline"
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>
</div>
)}
@@ -48,6 +51,7 @@ export function LoginArea({ className }: LoginAreaProps) {
isOpen={loginDialogOpen}
onClose={() => setLoginDialogOpen(false)}
onLogin={handleLogin}
onSignup={() => setSignupDialogOpen(true)}
/>
<SignupDialog
+367 -158
View File
@@ -1,21 +1,28 @@
// NOTE: This file is stable and usually should not be modified.
// It is important that all functionality in this file is preserved, and should only be modified if explicitly requested.
import React, { useRef, useState, useEffect } from 'react';
import { Upload, AlertTriangle, ChevronDown } from 'lucide-react';
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { QRCodeSVG } from 'qrcode.react';
import { Shield, Upload, AlertTriangle, UserPlus, KeyRound, Sparkles, Loader2, Copy, Check, ChevronDown, ChevronUp, Link, ExternalLink } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Dialog, DialogContent, DialogHeader } from "@/components/ui/dialog";
import { Dialog, DialogContent, DialogHeader, DialogDescription } from "@/components/ui/dialog";
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
import { useLoginActions } from '@/hooks/useLoginActions';
import { DialogTitle } from '@radix-ui/react-dialog';
import {
useLoginActions,
generateNostrConnectParams,
generateNostrConnectURI,
type NostrConnectParams,
} from '@/hooks/useLoginActions';
import { useIsMobile } from '@/hooks/useIsMobile';
import { cn } from '@/lib/utils';
interface LoginDialogProps {
isOpen: boolean;
onClose: () => void;
onLogin: () => void;
onSignup?: () => void;
}
const validateNsec = (nsec: string) => {
@@ -23,14 +30,20 @@ const validateNsec = (nsec: string) => {
};
const validateBunkerUri = (uri: string) => {
return uri.startsWith('bunker://');
return uri.startsWith('bunker://') || uri.startsWith('nostrconnect://');
};
const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin }) => {
const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onSignup }) => {
const [isLoading, setIsLoading] = useState(false);
const [isFileLoading, setIsFileLoading] = useState(false);
const [nsec, setNsec] = useState('');
const [bunkerUri, setBunkerUri] = useState('');
const [nostrConnectParams, setNostrConnectParams] = useState<NostrConnectParams | null>(null);
const [nostrConnectUri, setNostrConnectUri] = useState<string>('');
const [isWaitingForConnect, setIsWaitingForConnect] = useState(false);
const [connectError, setConnectError] = useState<string | null>(null);
const [copied, setCopied] = useState(false);
const [showBunkerInput, setShowBunkerInput] = useState(false);
const [errors, setErrors] = useState<{
nsec?: string;
bunker?: string;
@@ -38,17 +51,63 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin }) =
extension?: string;
}>({});
const fileInputRef = useRef<HTMLInputElement>(null);
const abortControllerRef = useRef<AbortController | null>(null);
const login = useLoginActions();
// Check if on mobile device
const isMobile = useIsMobile();
// Check if extension is available
const hasExtension = 'nostr' in window;
// Generate nostrconnect params (sync) - just creates the QR code data
const generateConnectSession = useCallback(() => {
const relayUrl = login.getRelayUrl();
const params = generateNostrConnectParams([relayUrl]);
const uri = generateNostrConnectURI(params, 'MKStack');
setNostrConnectParams(params);
setNostrConnectUri(uri);
setConnectError(null);
}, [login]);
// Start listening for connection (async) - runs after params are set
useEffect(() => {
if (!nostrConnectParams || isWaitingForConnect) return;
const startListening = async () => {
setIsWaitingForConnect(true);
abortControllerRef.current = new AbortController();
try {
await login.nostrconnect(nostrConnectParams);
onLogin();
onClose();
} catch (error) {
console.error('Nostrconnect failed:', error);
setConnectError(error instanceof Error ? error.message : 'Connection failed');
setIsWaitingForConnect(false);
}
};
startListening();
}, [nostrConnectParams, login, onLogin, onClose, isWaitingForConnect]);
// Reset all state when dialog opens/closes
useEffect(() => {
if (isOpen) {
// Reset state when dialog opens
if (!isOpen) {
// Reset state when dialog closes
setIsLoading(false);
setIsFileLoading(false);
setNsec('');
setBunkerUri('');
setNostrConnectParams(null);
setNostrConnectUri('');
setIsWaitingForConnect(false);
setConnectError(null);
setShowBunkerInput(false);
setErrors({});
if (abortControllerRef.current) {
abortControllerRef.current.abort();
}
// Reset file input
if (fileInputRef.current) {
fileInputRef.current.value = '';
@@ -56,6 +115,29 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin }) =
}
}, [isOpen]);
// Retry connection with new params
const handleRetry = useCallback(() => {
setNostrConnectParams(null);
setNostrConnectUri('');
setIsWaitingForConnect(false);
setConnectError(null);
// Generate new session after state clears
setTimeout(() => generateConnectSession(), 0);
}, [generateConnectSession]);
const handleCopyUri = async () => {
await navigator.clipboard.writeText(nostrConnectUri);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
};
// Open the nostrconnect URI in the system - this will launch a signer app like Amber if installed
const handleOpenSignerApp = () => {
if (!nostrConnectUri) return;
// On mobile, this will trigger the system to find an app that handles nostrconnect:// URIs
window.location.href = nostrConnectUri;
};
const handleExtensionLogin = async () => {
setIsLoading(true);
setErrors(prev => ({ ...prev, extension: undefined }));
@@ -69,8 +151,6 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin }) =
onClose();
} catch (e: unknown) {
const error = e as Error;
console.error('Bunker login failed:', error);
console.error('Nsec login failed:', error);
console.error('Extension login failed:', error);
setErrors(prev => ({
...prev,
@@ -118,7 +198,7 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin }) =
}
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;
}
@@ -170,167 +250,296 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin }) =
reader.readAsText(file);
};
const hasExtension = 'nostr' in window;
const [isMoreOptionsOpen, setIsMoreOptionsOpen] = useState(false);
const handleSignupClick = () => {
onClose();
if (onSignup) {
onSignup();
}
};
const renderTabs = () => (
<Tabs defaultValue="key" className="w-full">
<TabsList className="grid w-full grid-cols-2 bg-muted/80 rounded-lg mb-4">
<TabsTrigger value="key" className="flex items-center gap-2">
<span>Secret Key</span>
</TabsTrigger>
<TabsTrigger value="bunker" className="flex items-center gap-2">
<span>Remote Signer</span>
</TabsTrigger>
</TabsList>
<TabsContent value='key' className='space-y-4'>
<form onSubmit={(e) => {
e.preventDefault();
handleKeyLogin();
}} className='space-y-4'>
<div className='space-y-2'>
<Input
id='nsec'
type="password"
value={nsec}
onChange={(e) => {
setNsec(e.target.value);
if (errors.nsec) setErrors(prev => ({ ...prev, nsec: undefined }));
}}
className={`rounded-lg ${
errors.nsec ? 'border-red-500 focus-visible:ring-red-500' : ''
}`}
placeholder='nsec1...'
autoComplete="off"
/>
{errors.nsec && (
<p className="text-sm text-red-500">{errors.nsec}</p>
)}
</div>
<div className="flex space-x-2">
<Button
type="submit"
size="lg"
disabled={isLoading || !nsec.trim()}
className="flex-1"
>
{isLoading ? 'Verifying...' : 'Log in'}
</Button>
<input
type="file"
accept=".txt"
className="hidden"
ref={fileInputRef}
onChange={handleFileUpload}
/>
<Button
type="button"
variant="outline"
size="lg"
onClick={() => fileInputRef.current?.click()}
disabled={isLoading || isFileLoading}
className="px-3"
>
<Upload className="w-4 h-4" />
</Button>
</div>
{errors.file && (
<p className="text-sm text-red-500 text-center">{errors.file}</p>
)}
</form>
</TabsContent>
<TabsContent value='bunker' className='space-y-4'>
<form onSubmit={(e) => {
e.preventDefault();
handleBunkerLogin();
}} className='space-y-4'>
<div className='space-y-2'>
<Input
id='bunkerUri'
value={bunkerUri}
onChange={(e) => {
setBunkerUri(e.target.value);
if (errors.bunker) setErrors(prev => ({ ...prev, bunker: undefined }));
}}
className={`rounded-lg border-gray-300 dark:border-gray-700 focus-visible:ring-primary ${
errors.bunker ? 'border-red-500' : ''
}`}
placeholder='bunker://'
autoComplete="off"
/>
{errors.bunker && (
<p className="text-sm text-red-500">{errors.bunker}</p>
)}
</div>
<Button
type="submit"
size="lg"
className='w-full'
disabled={isLoading || !bunkerUri.trim()}
>
{isLoading ? 'Connecting...' : 'Log in'}
</Button>
</form>
</TabsContent>
</Tabs>
);
const defaultTab = hasExtension ? 'extension' : 'connect';
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>
<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>
<div className="flex size-40 text-8xl bg-primary/10 rounded-full items-center justify-center justify-self-center">
🔑
</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>
<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">
{/* 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 value="connect" className="flex items-center gap-2">
<Link className="w-4 h-4" />
<span>Connect</span>
</TabsTrigger>
<TabsTrigger value="key" className="flex items-center gap-2">
<KeyRound className="w-4 h-4" />
<span>Key</span>
</TabsTrigger>
</TabsList>
<TabsContent value='extension' className='space-y-3 bg-muted'>
{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>
)}
<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>
{/* 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' : ''}`} />
<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>
</CollapsibleTrigger>
<CollapsibleContent>
{renderTabs()}
</CollapsibleContent>
</Collapsible>
) : (
renderTabs()
)}
{showBunkerInput && (
<div className='space-y-3 mt-3'>
<div className='space-y-2'>
<Input
id='connectBunkerUri'
value={bunkerUri}
onChange={(e) => setBunkerUri(e.target.value)}
className='rounded-lg border-gray-300 dark:border-gray-700 focus-visible:ring-primary text-sm'
placeholder='bunker://'
/>
{bunkerUri && !validateBunkerUri(bunkerUri) && (
<p className='text-red-500 text-xs'>URI must start with bunker:// or nostrconnect://</p>
)}
</div>
<Button
className='w-full rounded-full py-4'
variant='outline'
onClick={handleBunkerLogin}
disabled={isLoading || !bunkerUri.trim() || !validateBunkerUri(bunkerUri)}
>
{isLoading ? 'Connecting...' : 'Connect with Bunker'}
</Button>
</div>
)}
</div>
</TabsContent>
<TabsContent value='key' className='space-y-4'>
<div className='space-y-4'>
<div className='space-y-2'>
<label htmlFor='nsec' className='text-sm font-medium'>
Secret Key (nsec)
</label>
<Input
id='nsec'
type="password"
value={nsec}
onChange={(e) => {
setNsec(e.target.value);
if (errors.nsec) setErrors(prev => ({ ...prev, nsec: undefined }));
}}
className={`rounded-lg ${
errors.nsec ? 'border-red-500 focus-visible:ring-red-500' : ''
}`}
placeholder='nsec1...'
autoComplete="off"
/>
{errors.nsec && (
<p className="text-sm text-red-500">{errors.nsec}</p>
)}
</div>
<Button
className='w-full rounded-full py-3'
onClick={handleKeyLogin}
disabled={isLoading || !nsec.trim()}
>
{isLoading ? 'Verifying...' : 'Log In'}
</Button>
<div className='relative'>
<div className='absolute inset-0 flex items-center'>
<div className='w-full border-t border-muted'></div>
</div>
<div className='relative flex justify-center text-xs'>
<span className='px-2 bg-background text-muted-foreground'>
or
</span>
</div>
</div>
<div className='text-center'>
<input
type='file'
accept='.txt'
className='hidden'
ref={fileInputRef}
onChange={handleFileUpload}
/>
<Button
variant='outline'
className='w-full'
onClick={() => fileInputRef.current?.click()}
disabled={isLoading || isFileLoading}
>
<Upload className='w-4 h-4 mr-2' />
{isFileLoading ? 'Reading File...' : 'Upload Your Key File'}
</Button>
{errors.file && (
<p className="text-sm text-red-500 mt-2">{errors.file}</p>
)}
</div>
</div>
</TabsContent>
</Tabs>
</div>
</DialogContent>
</Dialog>
+435 -88
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.
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 { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Card, CardContent } from '@/components/ui/card';
import { toast } from '@/hooks/useToast';
import { useLoginActions } from '@/hooks/useLoginActions';
import { useNostrPublish } from '@/hooks/useNostrPublish';
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 {
isOpen: boolean;
onClose: () => void;
onComplete?: () => void;
}
const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose }) => {
const [step, setStep] = useState<'generate' | 'download' | 'profile'>('generate');
const sanitizeFilename = (filename: string) => {
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 [showKey, setShowKey] = useState(false);
const [showSparkles, setShowSparkles] = useState(false);
const [keySecured, setKeySecured] = useState<'none' | 'downloaded'>('none');
const [profileData, setProfileData] = useState({
name: '',
about: '',
@@ -34,9 +43,34 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose }) => {
// Generate a proper nsec key using nostr-tools
const generateKey = () => {
const sk = generateSecretKey();
setNsec(nip19.nsecEncode(sk));
setStep('download');
setIsLoading(true);
setShowSparkles(true);
// Add a dramatic pause for the key generation effect
setTimeout(() => {
try {
// Generate a new secret key
const sk = generateSecretKey();
// Convert to nsec format
setNsec(nip19.nsecEncode(sk));
setStep('download');
toast({
title: 'Your Secret Key is Ready!',
description: 'A new secret key has been generated for you.',
});
} catch {
toast({
title: 'Error',
description: 'Failed to generate key. Please try again.',
variant: 'destructive',
});
} finally {
setIsLoading(false);
setShowSparkles(false);
}
}, 2000);
};
const downloadKey = () => {
@@ -45,14 +79,8 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose }) => {
const blob = new Blob([nsec], { type: 'text/plain; charset=utf-8' });
const url = globalThis.URL.createObjectURL(blob);
const decoded = nip19.decode(nsec);
if (decoded.type !== 'nsec') {
throw new Error('Invalid nsec key');
}
const pubkey = getPublicKey(decoded.data);
const npub = nip19.npubEncode(pubkey);
const filename = `nostr-${location.hostname.replaceAll(/\./g, '-')}-${npub.slice(5, 9)}.nsec.txt`;
// Sanitize filename
const filename = sanitizeFilename('nostr-nsec-key.txt');
// Create a temporary link element and trigger download
const a = document.createElement('a');
@@ -66,9 +94,13 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose }) => {
globalThis.URL.revokeObjectURL(url);
document.body.removeChild(a);
// Continue to profile step
login.nsec(nsec);
setStep('profile');
// Mark as secured
setKeySecured('downloaded');
toast({
title: 'Secret Key Saved!',
description: 'Your key has been safely stored.',
});
} catch {
toast({
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 file = e.target.files?.[0];
if (!file) return;
@@ -111,6 +158,10 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose }) => {
const url = tags[0]?.[1];
if (url) {
setProfileData(prev => ({ ...prev, picture: url }));
toast({
title: 'Avatar uploaded!',
description: 'Your avatar has been uploaded successfully.',
});
}
} catch {
toast({
@@ -122,6 +173,9 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose }) => {
};
const finishSignup = async (skipProfile = false) => {
// Mark signup completion time for fallback welcome modal
localStorage.setItem('signup_completed', Date.now().toString());
try {
// Publish profile if user provided information
if (!skipProfile && (profileData.name || profileData.about || profileData.picture)) {
@@ -134,6 +188,30 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose }) => {
kind: 0,
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 {
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.',
variant: 'destructive',
});
} finally {
// Still proceed to completion even if profile failed
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 = () => {
if (step === 'generate') return 'Sign up';
if (step === 'download') return 'Secret Key';
if (step === 'profile') return 'Create Your Profile';
if (step === 'welcome') return (
<span className="flex items-center justify-center gap-2">
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
useEffect(() => {
if (isOpen) {
setStep('generate');
setStep('welcome');
setIsLoading(false);
setNsec('');
setShowKey(false);
setShowSparkles(false);
setKeySecured('none');
setProfileData({ name: '', about: '', picture: '' });
}
}, [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 (
<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">
<DialogContent
className={cn("max-w-[95vw] sm:max-w-md max-h-[90vh] max-h-[90dvh] p-0 overflow-hidden rounded-2xl flex flex-col")}
>
<DialogHeader className={cn('px-6 pt-6 pb-1 relative flex-shrink-0')}>
<DialogTitle className={cn('font-semibold text-center text-lg')}>
{getTitle()}
</DialogTitle>
</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'>
{/* Generate Step */}
{step === 'generate' && (
<div className='text-center space-y-6'>
<div className="flex size-40 text-8xl bg-primary/10 rounded-full items-center justify-center justify-self-center">
🔑
{/* Benefits */}
<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>
<Button className="w-full h-12 px-9" onClick={generateKey}>
Generate key
</Button>
<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>
)}
{/* Download Step */}
{step === 'download' && (
<div className='space-y-4'>
<div className="flex size-16 text-4xl bg-primary/10 rounded-full items-center justify-center justify-self-center">
🔑
{/* Generate Step - Enhanced with animations */}
{step === 'generate' && (
<div className='text-center space-y-4'>
<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 */}
{showSparkles && (
<div className='absolute inset-0'>
{[...Array(12)].map((_, i) => (
<Sparkles
key={i}
className={`absolute w-4 h-4 text-yellow-400 animate-ping`}
style={{
left: `${Math.random() * 80 + 10}%`,
top: `${Math.random() * 80 + 10}%`,
animationDelay: `${Math.random() * 2}s`
}}
/>
))}
</div>
)}
<div className='relative z-10'>
{isLoading ? (
<div className='space-y-3'>
<div className='relative'>
<Key className='w-20 h-20 text-primary mx-auto animate-pulse' />
<div className='absolute inset-0 flex items-center justify-center'>
<div className='w-24 h-24 border-4 border-yellow-400 border-t-transparent rounded-full animate-spin'></div>
</div>
</div>
<div className='space-y-2'>
<p className='text-lg font-semibold text-primary flex items-center justify-center gap-2'>
<Sparkles className='w-5 h-5' />
Generating your secret key...
</p>
<p className='text-sm text-muted-foreground'>
Creating your secure key
</p>
</div>
</div>
) : (
<div className='space-y-3'>
<Key className='w-20 h-20 text-primary mx-auto' />
<div className='space-y-2'>
<p className='text-lg font-semibold'>
Ready to generate your secret key?
</p>
<p className='text-sm text-muted-foreground px-5'>
This key will be your password to access applications within the Nostr network.
</p>
</div>
</div>
)}
</div>
</div>
<div className="relative">
<Input
type={showKey ? "text" : "password"}
value={nsec}
readOnly
className="pr-10 font-mono text-sm"
/>
{!isLoading && (
<Button
type="button"
variant="ghost"
size="icon"
className="absolute right-0 top-0 h-full px-3 hover:bg-transparent"
onClick={() => setShowKey(!showKey)}
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={generateKey}
disabled={isLoading}
>
{showKey ? (
<EyeOff className="h-4 w-4 text-muted-foreground" />
) : (
<Eye className="h-4 w-4 text-muted-foreground" />
)}
<Sparkles className='w-5 h-5 mr-2' />
Generate My Secret Key
</Button>
)}
</div>
)}
{/* Download Step - Whimsical and magical */}
{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'>
<FileText className='w-3 h-3 text-amber-700' />
<span className='text-xs font-bold text-amber-800 dark:text-amber-200'>
Important Warning
</span>
</div>
<p className='text-xs text-red-700 dark:text-amber-300 italic'>
This key is your primary and only means of accessing your account. Store it safely and securely.
</p>
</div>
</div>
</div>
</div>
{/* 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>
)}
<Button
className="w-full h-12 px-9"
onClick={downloadKey}
>
<Download className="size-4" />
Download key
</Button>
{/* Profile Step - Optional profile setup */}
{step === 'profile' && (
<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='mx-auto max-w-sm'>
<div className='p-3 bg-amber-50 dark:bg-amber-950/20 rounded-lg border border-amber-200 dark:border-amber-800'>
<div className='flex items-center gap-2 mb-1'>
<span className='text-xs font-semibold text-amber-800 dark:text-amber-200'>
Important Warning
</span>
<div 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>
<p className='text-xs text-amber-900 dark:text-amber-300'>
This key is your primary and only means of accessing your account. Store it safely and securely. Please download your key to continue.
</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>
</div>
)}
{/* Profile Step */}
{step === 'profile' && (
<div className='text-center space-y-4'>
{/* Publishing status indicator */}
{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='w-5 h-5 border-2 border-primary border-t-transparent rounded-full animate-spin' />
<span className='text-sm font-medium'>
<div className='w-5 h-5 border-2 border-blue-600 border-t-transparent rounded-full animate-spin' />
<span className='text-sm font-medium text-blue-700 dark:text-blue-300'>
Publishing your profile...
</span>
</div>
@@ -263,6 +602,7 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose }) => {
value={profileData.name}
onChange={(e) => setProfileData(prev => ({ ...prev, name: e.target.value }))}
placeholder='Your name'
className='rounded-lg'
disabled={isPublishing}
/>
</div>
@@ -276,7 +616,7 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose }) => {
value={profileData.about}
onChange={(e) => setProfileData(prev => ({ ...prev, about: e.target.value }))}
placeholder='Tell others about yourself...'
className='resize-none'
className='rounded-lg resize-none'
rows={3}
disabled={isPublishing}
/>
@@ -292,7 +632,7 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose }) => {
value={profileData.picture}
onChange={(e) => setProfileData(prev => ({ ...prev, picture: e.target.value }))}
placeholder='https://example.com/your-avatar.jpg'
className='flex-1'
className='rounded-lg flex-1'
disabled={isPublishing}
/>
<input
@@ -308,6 +648,7 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose }) => {
size='icon'
onClick={() => avatarFileInputRef.current?.click()}
disabled={isUploading || isPublishing}
className='rounded-lg shrink-0'
title='Upload avatar image'
>
{isUploading ? (
@@ -323,7 +664,7 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose }) => {
{/* Action buttons */}
<div className='space-y-3'>
<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)}
disabled={isPublishing || isUploading}
>
@@ -333,18 +674,24 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose }) => {
Creating Profile...
</>
) : (
'Create profile'
<>
<User className='w-4 h-4 mr-2' />
Create Profile & Finish
</>
)}
</Button>
<Button
variant='outline'
className='w-full'
className='w-full rounded-full py-3 disabled:opacity-50 disabled:cursor-not-allowed'
onClick={() => finishSignup(true)}
disabled={isPublishing || isUploading}
>
{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'
)}
+1 -1
View File
@@ -43,7 +43,7 @@ const DialogContent = React.forwardRef<
>
{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">
<X className="size-5" />
<X className="h-4 w-4" />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
</DialogPrimitive.Content>
+124
View File
@@ -1,11 +1,67 @@
import { NConnectSigner, NSecSigner } from '@nostrify/nostrify';
import { useNostr } from '@nostrify/react';
import { NLogin, useNostrLogin } from '@nostrify/react/login';
import { generateSecretKey, getPublicKey } from 'nostr-tools';
import { nip19 } from 'nostr-tools';
import { useAppContext } from '@/hooks/useAppContext';
// NOTE: This file should not be edited except for adding new login methods.
/** Check if running on actual mobile device (not just small screen) */
function isMobileDevice(): boolean {
if (typeof navigator === 'undefined') return false;
return /Android|iPhone|iPad|iPod/i.test(navigator.userAgent);
}
/** Parameters for initiating a nostrconnect:// session */
export interface NostrConnectParams {
clientSecretKey: Uint8Array;
clientPubkey: string;
secret: string;
relays: string[];
}
/** Generates a nostrconnect:// URI for QR code display */
export function generateNostrConnectURI(params: NostrConnectParams, appName?: string): string {
const searchParams = new URLSearchParams();
for (const relay of params.relays) {
searchParams.append('relay', relay);
}
searchParams.set('secret', params.secret);
if (appName) {
searchParams.set('name', appName);
}
// Add callback URL only on mobile devices (not desktop QR code scanning)
// When scanning QR from desktop, the signer app is on the phone but the session is on desktop
if (typeof window !== 'undefined' && isMobileDevice()) {
searchParams.set('callback', `${window.location.origin}/remoteloginsuccess`);
}
return `nostrconnect://${params.clientPubkey}?${searchParams.toString()}`;
}
/** Generates random parameters for a nostrconnect session */
export function generateNostrConnectParams(relays: string[]): NostrConnectParams {
const clientSecretKey = generateSecretKey();
const clientPubkey = getPublicKey(clientSecretKey);
const secret = crypto.randomUUID().slice(0, 8);
return {
clientSecretKey,
clientPubkey,
secret,
relays,
};
}
export function useLoginActions() {
const { nostr } = useNostr();
const { logins, addLogin, removeLogin } = useNostrLogin();
const { config } = useAppContext();
return {
// Login with a Nostr secret key
@@ -23,6 +79,74 @@ export function useLoginActions() {
const login = await NLogin.fromExtension();
addLogin(login);
},
// Login via nostrconnect:// (client-initiated NIP-46)
// The client displays a QR code and waits for the remote signer to connect
async nostrconnect(params: NostrConnectParams): Promise<void> {
const clientSigner = new NSecSigner(params.clientSecretKey);
const clientPubkey = getPublicKey(params.clientSecretKey);
// Create a relay group for the connection
const relayGroup = nostr.group(params.relays);
// Wait for the connect response from the remote signer
// We subscribe to kind 24133 events p-tagged to our client pubkey
const signal = AbortSignal.timeout(120_000); // 2 minute timeout
const sub = relayGroup.req(
[{ kinds: [24133], '#p': [clientPubkey], limit: 1 }],
{ signal }
);
for await (const msg of sub) {
if (msg[0] === 'CLOSED') {
throw new Error('Connection closed before remote signer responded');
}
if (msg[0] === 'EVENT') {
const event = msg[2];
// Decrypt the response
const decrypted = await clientSigner.nip44!.decrypt(event.pubkey, event.content);
const response = JSON.parse(decrypted);
// Validate the secret matches
if (response.result !== params.secret && response.result !== 'ack') {
continue; // Not our response, keep waiting
}
// Success! The remote signer has connected
// Now create the NConnectSigner for ongoing use
const bunkerPubkey = event.pubkey;
const signer = new NConnectSigner({
relay: relayGroup,
pubkey: bunkerPubkey,
signer: clientSigner,
timeout: 60_000,
});
// Get the actual user pubkey
const userPubkey = await signer.getPublicKey();
// Create and add the login
const login = new NLogin('bunker', userPubkey, {
bunkerPubkey,
clientNsec: nip19.nsecEncode(params.clientSecretKey),
relays: params.relays,
});
addLogin(login);
return;
}
}
throw new Error('Timeout waiting for remote signer');
},
// Get the current relay URL for nostrconnect
getRelayUrl(): string {
// Get the first write-enabled relay, or fallback to a default
const writeRelay = config.relayMetadata?.relays?.find(r => r.write);
return writeRelay?.url ?? 'wss://relay.nostr.band';
},
// Log out the current user
async logout(): Promise<void> {
const login = logins[0];
+1 -1
View File
@@ -32,7 +32,7 @@
--input: 214.3 31.8% 91.4%;
--ring: 222.2 84% 4.9%;
--radius: 0.75rem;
--radius: 0.5rem;
--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"
]
}