64 Commits
Author SHA1 Message Date
Chad Curtis c0dca78709 Admin Dashboard init 2025-09-02 00:09:46 +00:00
Chad Curtis d1744b7d71 Merge branch 'infiniteScroll' into 'main'
Add context for pagination (i.e., infinite feed scroll)

See merge request soapbox-pub/mkstack!16
2025-09-01 22:02:49 +00:00
Chad Curtis 6458b24305 Add react-intersection-observer per AGENTS.md 2025-09-01 21:26:23 +00:00
Chad CurtisandAlex Gleason 9114c7db86 Apply 1 suggestion(s) to 1 file(s)
Co-authored-by: Alex Gleason <[email protected]>
2025-09-01 21:25:34 +00:00
Chad CurtisandAlex Gleason b2cc0aef79 Apply 1 suggestion(s) to 1 file(s)
Co-authored-by: Alex Gleason <[email protected]>
2025-09-01 21:25:16 +00:00
Chad CurtisandAlex Gleason 363b2e3ebb Apply 1 suggestion(s) to 1 file(s)
Co-authored-by: Alex Gleason <[email protected]>
2025-09-01 21:25:10 +00:00
Chad CurtisandAlex Gleason 37ff1d6957 Apply 1 suggestion(s) to 1 file(s)
Co-authored-by: Alex Gleason <[email protected]>
2025-09-01 21:24:11 +00:00
Chad CurtisandAlex Gleason 2baccf1ea0 Apply 1 suggestion(s) to 1 file(s)
Co-authored-by: Alex Gleason <[email protected]>
2025-09-01 21:23:55 +00:00
Chad CurtisandAlex Gleason dddeb7fc61 Apply 1 suggestion(s) to 1 file(s)
Co-authored-by: Alex Gleason <[email protected]>
2025-09-01 21:23:33 +00:00
Chad Curtis cf64f2ca83 Update context for pagination duplication potential. 2025-09-01 21:01:19 +00:00
Chad Curtis 0d327372fe Add infinite scroll to AGENTS.md 2025-09-01 20:48:35 +00:00
Alex Gleason b4a1a46430 Remove .github/copilot-instructions.md
https://docs.github.com/en/enterprise-cloud@latest/copilot/tutorials/coding-agent/get-the-best-results#adding-custom-instructions-to-your-repository
2025-09-01 15:28:13 -05:00
Chad Curtis d5c37a13c7 Merge branch 'signupImprovements' into 'main'
Signup flow - simplify text + remove copy button

See merge request soapbox-pub/mkstack!15
2025-09-01 20:11:14 +00:00
Chad Curtis 1879cd18f5 rename key file 2025-09-01 20:00:56 +00:00
Chad Curtis 8ff4046308 Further simplify signup 2025-09-01 19:47:39 +00:00
Chad Curtis be0f74543c Remove copy button from signup flow. npm i 2025-09-01 19:43:53 +00:00
Alex Gleason c0f822a4f4 Remove agent.json 2025-08-31 20:33:12 -05:00
Alex Gleason 480d5905d7 Remove .cursorrules
https://docs.cursor.com/en/context/rules#agents-md
2025-08-31 20:29:54 -05:00
Alex Gleason 31d2aa4761 Remove .goosehints and .gooseignore 2025-08-31 20:28:50 -05:00
Alex Gleason b52374f0db Remove codex.md 2025-08-31 20:27:17 -05:00
Alex Gleason 5c1cff5618 AGENTS.md in AGENTS.md 2025-08-31 20:17:52 -05:00
Alex Gleason e335e787ff Make AGENTS.md the primary context file that gets loaded 2025-08-31 20:11:43 -05:00
Alex Gleason 241a235ce1 gitignore .ai/ 2025-08-30 17:44:58 -05:00
Alex Gleason df80653a83 Update mcp servers 2025-08-18 21:55:35 -05:00
Alex Gleason a862d30e8e Remove sonner 2025-08-09 19:45:54 -08:00
Alex Gleason 5eeb424d43 Revert "Add .ai-history/ to .gitignore"
This reverts commit b6d31cdd9d.
2025-07-30 00:11:29 -05:00
Alex Gleason b6d31cdd9d Add .ai-history/ to .gitignore 2025-07-28 23:55:20 -05:00
Chad Curtis 7473c794cc Merge branch 'zapSupport' into 'main'
Implement Zap + NWC Wallet support

See merge request soapbox-pub/mkstack!11
2025-07-26 00:12:25 +00:00
Chad Curtis 0c039bfbcf revert gitlab-ci to upstream version for now 2025-07-26 00:09:58 +00:00
Chad Curtis 36237fd5b6 attempt to isolate gitlab logic to mainline mkstack 2025-07-25 23:51:13 +00:00
Chad Curtis 1de668785f CONTEXT update per review feedback 2025-07-25 23:47:46 +00:00
Chad Curtis c231ee40ac Merge branch 'main' of gitlab.com:soapbox-pub/mkstack into zapSupport 2025-07-25 23:45:15 +00:00
Alex Gleason fbbf7f8c39 npm audit fix 2025-07-23 16:30:18 -05:00
Chad Curtis 23508f361b clean up mobile drawer height fix 2025-07-17 23:37:19 +00:00
Chad Curtis 612aacb00b Merge branch 'main' of gitlab.com:soapbox-pub/mkstack into zapSupport 2025-07-17 22:38:39 +00:00
Chad Curtis 21540d251f reduce unused functions, consolidate uri check 2025-07-14 15:20:34 +00:00
Chad Curtis 97a493c218 fix redraw issue for wallet configuration 2025-07-14 14:21:57 +00:00
Chad Curtis 6845e6cf7c Fallback to manual payment if webln fails - might be due to user intentionally closing out of it v2 2025-07-14 13:50:22 +00:00
Chad Curtis 3101532a2b Fallback to manual payment if webln fails - might be due to user intentionally closing out of it 2025-07-14 13:50:02 +00:00
Chad Curtis 7c9f3cb797 functional fix for drawer height bug on mobile 2025-07-14 13:01:49 +00:00
Chad Curtis 4c129251c7 more potential mobile sizing fixes for vh 2025-07-14 07:44:12 +00:00
Chad Curtis 0484b10a96 fix state issue which resulted in text edits causing repeated focus loss 2025-07-14 07:23:33 +00:00
Chad Curtis 230183bd0c more mobile fixes 2025-07-14 07:09:15 +00:00
Chad Curtis a92f80b6e3 small styling fixes + fix potential memory leaks 2025-07-14 06:27:29 +00:00
Chad Curtis a51094e157 update gitlab ci to expect template failures in the default state 2025-07-14 04:04:50 +00:00
Chad Curtis ab54efba47 merge in from upstream and resolve conflicts 2025-07-14 03:58:49 +00:00
Chad Curtis 0a2474d2f5 mobile enhancements 2025-07-14 03:06:17 +00:00
Chad Curtis 661a5e1eac shorten empty state text to one line 2025-07-14 02:23:20 +00:00
Chad Curtis 9d8b5a3f43 another set of context + zap button fixes 2025-07-14 02:11:23 +00:00
Chad Curtis 8f51db5a49 nwc icon change + context fix 2025-07-14 02:01:30 +00:00
Chad Curtis c98a6bbf64 scrollable manual zap, handle undef target 2025-07-14 01:51:48 +00:00
Chad Curtis 9ed8676d17 context updae + app nwccontext 2025-07-14 01:40:04 +00:00
Chad Curtis 8183e3cc5a cleanup + shakespeare-like manual zap modal 2025-07-14 01:16:31 +00:00
Chad Curtis 0bc03017bb further refinement 2025-07-14 01:03:04 +00:00
Chad Curtis 7eecec7506 tidying 2025-07-13 20:12:42 +00:00
Chad Curtis 8c34dbc8d5 further refinement for new app builds 2025-07-13 19:52:58 +00:00
Chad Curtis 45ff37e752 messy, nwc support +_wallet fixes 2025-07-13 17:53:30 +00:00
Chad Curtis 11ac73776c zap in context.md 2025-07-13 06:51:24 +00:00
Chad Curtis 14eccbcb6f wallet configuration settings + nwc baseline support 2025-07-13 06:47:45 +00:00
Chad Curtis 55bf545646 cleanup + icons 2025-07-13 05:59:56 +00:00
Chad Curtis ec1a9777de use event directly 2025-07-13 04:09:32 +00:00
Chad Curtis 7fdcb658b3 use single zaps component 2025-07-12 19:23:50 +00:00
Chad Curtis c37df875b9 user fix 2025-07-12 19:20:34 +00:00
Chad Curtis d68f2d8486 minimal zap support 2025-07-12 19:19:41 +00:00
36 changed files with 4651 additions and 1495 deletions

No files matched your search

-1
View File
@@ -1 +0,0 @@
CONTEXT.md
+7
View File
@@ -0,0 +1,7 @@
# Admin Configuration
# Set this to the npub of the site administrator
# Only this user will have access to the admin dashboard at /admin
VITE_ADMIN_NPUB=npub1abc123def456ghi789...
# Example:
# VITE_ADMIN_NPUB=npub1sg6plzptd64u62a878hep2kev88swjh3tw00gjsfl8f237lmu63q0uf63m
-1
View File
@@ -1 +0,0 @@
../CONTEXT.md
+1
View File
@@ -11,6 +11,7 @@ node_modules
dist
dist-ssr
*.local
.ai/
# Editor directories and files
.idea
-1
View File
@@ -1 +0,0 @@
CONTEXT.md
-16
View File
@@ -1,16 +0,0 @@
# jsr registry should not be edited or removed
.npmrc
# vite client types are needed
src/vite-env.d.ts
# tsconfig is stable and working correctly, so should not be edited
tsconfig.json
tsconfig.app.json
tsconfig.node.json
# postcss config for Tailwind is stable and working correctly, so should not be edited unless upgrading Tailwind to v4
postcss.config.js
# vite config is stable and usually should not need to be edited
vite.config.ts
+6 -1
View File
@@ -1,9 +1,14 @@
{
"mcpServers": {
"js-dev": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@soapbox.pub/js-dev-mcp@latest"]
},
"nostr": {
"type": "stdio",
"command": "npx",
"args": ["-y", "xjsr", "@nostrbook/mcp"]
"args": ["-y", "@nostrbook/mcp@latest"]
}
}
}
+6 -1
View File
@@ -1,9 +1,14 @@
{
"servers": {
"js-dev": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@soapbox.pub/js-dev-mcp@latest"]
},
"nostr": {
"type": "stdio",
"command": "npx",
"args": ["-y", "xjsr", "@nostrbook/mcp"]
"args": ["-y", "@nostrbook/mcp@latest"]
}
}
}
+170
View File
@@ -0,0 +1,170 @@
# Site Administration Dashboard
The MKStack template includes a comprehensive site administration dashboard for content moderation and site management.
## Access
The admin dashboard is accessible at `/admin` and requires environment variable configuration.
**Authentication Required**: Only the site administrator (configured via `VITE_ADMIN_NPUB` environment variable) can access the admin dashboard. Other users will see an access denied message with a login prompt.
## Configuration
Set the `VITE_ADMIN_NPUB` environment variable to the npub of the site administrator:
```bash
VITE_ADMIN_NPUB=npub1abc123def456ghi789...
```
See `.env.example` for configuration details.
## Features
### Content Moderation Tab
- **Recent Content Review**: View and moderate recent posts and articles
- **Hide/Show Content**: Quickly hide inappropriate content or restore hidden content
- **Content Types**: Distinguishes between notes, articles, and other event kinds
- **Author Information**: Shows poster details with avatars and names
- **Timestamps**: Recent activity tracking for moderation decisions
### User Management Tab
- **Allow List**: Explicitly allowed users who can post content
- **Deny List**: Blocked users who cannot post content
- **Add Users**: Add users to allow/deny lists by npub
- **User Profiles**: View user avatars, names, and npub identifiers
- **Cross-List Management**: Adding to one list removes from the other
### Blocked Words Tab
- **Word Filtering**: Add words and phrases to automatically filter content
- **Case Sensitivity**: Toggle case-sensitive matching
- **Whole Words**: Option to match whole words only vs partial matches
- **Bulk Management**: Add/remove multiple blocked terms
- **Real-time Filtering**: Immediate effect on content display
### Site Analytics Tab
- **Content Statistics**: Total events, notes, articles on the site
- **User Activity**: Unique authors and active users
- **Time-based Metrics**: Activity in last 24 hours and 7 days
- **Content Breakdown**: Distribution of different content types
- **Growth Tracking**: Monitor site activity trends
### Site Settings Tab
- **Site Information**: Configure site name and description
- **Moderation Controls**: Enable/disable content moderation features
- **Auto-hide Settings**: Automatically hide content matching blocked words
- **Approval Workflow**: Require manual approval for all content
- **Environment Status**: View current configuration settings
## Implementation Details
### Route Configuration
The admin route is configured in `AppRouter.tsx` as `/admin` and takes precedence over the generic NIP-19 route.
### Authentication Flow
1. Environment variable `VITE_ADMIN_NPUB` is decoded using `nip19.decode()`
2. Current user's pubkey is compared with the admin pubkey
3. Unauthorized users see an access denied screen with login options
4. Authorized users see the full dashboard interface
### Data Fetching
- Uses TanStack Query for efficient data fetching and caching
- Implements proper loading states with skeleton components
- Includes error handling and timeout management
- Queries recent site content for moderation review
- Fetches site-wide analytics and statistics
### Nostr-Based Storage
- Uses custom event kind `39767` for persistent admin policies
- Stores all settings as addressable Nostr events
- Syncs across devices and browsers automatically
- Provides backup and recovery of admin settings
- Maintains audit trail of policy changes
### Components Used
- **Tabs**: Organized dashboard sections using shadcn/ui tabs
- **Cards**: Statistical displays and content sections
- **Badges**: Event type indicators and verification status
- **Avatars**: User profile images with fallbacks
- **Skeletons**: Loading states that match content structure
## Usage Examples
### Adding Admin Dashboard Link
Use the `AdminDashboardLink` component to add a dashboard link for logged-in users:
```tsx
import { AdminDashboardLink } from '@/components/AdminDashboardLink';
function Header() {
return (
<header className="flex items-center justify-between p-4">
<h1>My App</h1>
<AdminDashboardLink />
</header>
);
}
```
### Direct Access
Site administrators can access the dashboard directly by visiting:
```
/admin
```
### Setting Up Admin Access
To configure admin dashboard access:
1. Set `VITE_ADMIN_NPUB` environment variable to your npub
2. Log in with the corresponding Nostr account
3. Navigate to `/admin`
4. The `AdminDashboardLink` component will automatically appear for admin users
## Security Considerations
- **Environment-based Authentication**: Admin access controlled via environment variable
- **Single Admin Model**: Only one designated admin per site instance
- **Nostr Event Storage**: Admin policies stored as signed Nostr events (kind 39767)
- **Cross-Device Sync**: Settings automatically sync across all admin devices
- **Content Filtering**: Blocked words and user lists affect content display
- **Timeout Protection**: All queries include timeout limits to prevent hanging requests
- **No Private Key Access**: Uses existing authentication without requiring private keys
- **Event Integrity**: All admin policies are cryptographically signed and verifiable
## Customization
The admin dashboard is designed to be easily extensible:
### Adding New Tabs
1. Add a new `TabsTrigger` in the main dashboard component
2. Create a corresponding `TabsContent` section
3. Implement the tab's functionality as a separate component
### Extending Content Moderation
- **Automated Rules**: Add automatic content filtering based on patterns
- **Approval Queues**: Implement content approval workflows
- **Bulk Actions**: Add bulk moderation operations
- **Moderation History**: Track moderation actions and decisions
### Advanced User Management
- **Role-based Access**: Implement different user permission levels
- **Temporary Restrictions**: Time-limited bans or restrictions
- **User Reporting**: Allow community reporting of problematic users
- **Whitelist/Blacklist Import**: Bulk import of user lists
### Enhanced Analytics
- **Engagement Metrics**: Track user interaction patterns
- **Content Performance**: Analyze popular content types
- **Moderation Statistics**: Track moderation actions and effectiveness
- **Growth Trends**: Monitor site growth and user retention
## Technical Notes
- **React Hooks**: Follows React hooks rules with proper conditional rendering
- **TypeScript**: Fully typed with proper error handling (with type assertions for nostr-tools)
- **Responsive**: Works on mobile and desktop devices
- **Accessible**: Uses semantic HTML and ARIA attributes via Radix UI
- **Performance**: Implements query caching and loading optimization
- **Custom Storage Hook**: `useAdminStorage` for Nostr-based persistence
- **Environment Variables**: Requires Vite environment variable configuration
- **Icon Library**: Uses Lucide React icons throughout the interface
- **Custom NIP**: Implements event kind 39767 for admin storage (see `NIP.md`)
- **Content Filtering**: `useContentFilter` hook for policy enforcement
+1061
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -1 +1 @@
CONTEXT.md
AGENTS.md
-1025
View File
File diff suppressed because it is too large. Load diff
Symlink
+1
View File
@@ -0,0 +1 @@
AGENTS.md
+1 -1
View File
@@ -1 +1 @@
CONTEXT.md
AGENTS.md
+179
View File
@@ -0,0 +1,179 @@
# NIP-XX: Site Administration Events
## Abstract
This NIP defines a custom event kind for storing site administration policies and configurations in Nostr applications. It allows site administrators to persist content moderation settings, user access controls, and site configuration across devices and sessions.
## Specification
### Event Kind
This NIP introduces event kind `39767` for site administration data.
### Event Structure
Site administration events are **addressable events** that use the `d` tag to identify different configuration categories.
```json
{
"kind": 39767,
"content": "<JSON-encoded administration data>",
"tags": [
["d", "admin-config"],
["alt", "Site administration configuration and policies"]
],
"created_at": <unix timestamp>,
"pubkey": "<site administrator's pubkey>"
}
```
### Content Schema
The `content` field contains a JSON object with the following structure:
```json
{
"hiddenEvents": ["<event_id>", "..."],
"allowList": ["<pubkey>", "..."],
"denyList": ["<pubkey>", "..."],
"blockedWords": ["word1", "phrase2", "..."],
"caseSensitive": false,
"wholeWordsOnly": true,
"enableModeration": true,
"autoHideBlocked": true,
"requireApproval": false,
"siteName": "My Nostr Site",
"siteDescription": "A description of the site"
}
```
#### Field Descriptions
- **`hiddenEvents`**: Array of event IDs that have been manually hidden by the administrator
- **`allowList`**: Array of pubkeys explicitly allowed to post content (if not empty, only these users can post)
- **`denyList`**: Array of pubkeys blocked from posting content
- **`blockedWords`**: Array of words or phrases that trigger content filtering
- **`caseSensitive`**: Boolean indicating whether word filtering is case-sensitive
- **`wholeWordsOnly`**: Boolean indicating whether to match whole words only (vs partial matches)
- **`enableModeration`**: Boolean to enable/disable all moderation features
- **`autoHideBlocked`**: Boolean to automatically hide content matching blocked words
- **`requireApproval`**: Boolean to require manual approval for all content
- **`siteName`**: String containing the site's display name
- **`siteDescription`**: String containing the site's description
### Usage
#### Publishing Administration Events
Site administrators publish these events to store their moderation policies:
```javascript
const adminEvent = {
kind: 39767,
content: JSON.stringify({
hiddenEvents: [],
allowList: [],
denyList: ["banned_user_pubkey"],
blockedWords: ["spam", "inappropriate"],
caseSensitive: false,
wholeWordsOnly: true,
enableModeration: true,
autoHideBlocked: true,
requireApproval: false,
siteName: "My Community",
siteDescription: "A moderated Nostr community"
}),
tags: [
["d", "admin-config"],
["alt", "Site administration configuration and policies"]
]
};
```
#### Querying Administration Events
Clients query for the latest administration configuration:
```javascript
const adminConfig = await relay.query([{
kinds: [39767],
authors: [adminPubkey],
"#d": ["admin-config"],
limit: 1
}]);
```
### Implementation Guidelines
#### Authentication
- Only events signed by the designated site administrator's private key are valid
- The administrator's pubkey should be configured in the application (e.g., environment variable)
- Clients should verify the event signature before applying policies
#### Content Filtering
- **Allow List**: If not empty, only users on this list can post content
- **Deny List**: Users on this list are blocked regardless of allow list status
- **Blocked Words**: Content containing these words/phrases is filtered according to settings
- **Case Sensitivity**: Controls whether word matching is case-sensitive
- **Whole Words**: Controls whether to match complete words vs partial strings
#### Precedence Rules
1. Deny list takes precedence over allow list
2. Manual hiding (hiddenEvents) takes precedence over automatic filtering
3. If moderation is disabled, no filtering is applied
#### Client Behavior
- Clients should cache the latest administration event for performance
- Updates to administration policies should be reflected immediately in the UI
- Clients may choose to implement additional local filtering beyond these policies
### Security Considerations
- Administration events contain sensitive moderation data and should only be published by authorized administrators
- The `alt` tag provides human-readable context for the event purpose
- Clients should validate the JSON content structure before applying policies
- Consider implementing rate limiting for administration event updates
### Rationale
This NIP addresses the need for persistent, cross-device site administration in decentralized Nostr applications. By storing policies as Nostr events, administrators can:
- Maintain consistent moderation across multiple devices
- Backup and restore moderation settings
- Share administrative responsibilities (with proper key management)
- Maintain audit trails of policy changes
The addressable event structure allows for future expansion with additional configuration categories using different `d` tag values.
## Examples
### Basic Moderation Setup
```json
{
"kind": 39767,
"content": "{\"hiddenEvents\":[],\"allowList\":[],\"denyList\":[\"spam_user_pubkey\"],\"blockedWords\":[\"spam\",\"scam\"],\"caseSensitive\":false,\"wholeWordsOnly\":true,\"enableModeration\":true,\"autoHideBlocked\":true,\"requireApproval\":false,\"siteName\":\"Family-Friendly Community\",\"siteDescription\":\"A safe space for family discussions\"}",
"tags": [
["d", "admin-config"],
["alt", "Site administration configuration and policies"]
]
}
```
### Allowlist-Only Community
```json
{
"kind": 39767,
"content": "{\"hiddenEvents\":[],\"allowList\":[\"trusted_user1\",\"trusted_user2\"],\"denyList\":[],\"blockedWords\":[],\"caseSensitive\":false,\"wholeWordsOnly\":true,\"enableModeration\":true,\"autoHideBlocked\":false,\"requireApproval\":true,\"siteName\":\"Private Community\",\"siteDescription\":\"Invitation-only community\"}",
"tags": [
["d", "admin-config"],
["alt", "Site administration configuration and policies"]
]
}
```
## References
- [NIP-01: Basic protocol flow description](https://github.com/nostr-protocol/nips/blob/master/01.md)
- [NIP-31: Dealing with Unknown Events](https://github.com/nostr-protocol/nips/blob/master/31.md)
+10 -1
View File
@@ -1,3 +1,12 @@
# MKStack
Template for building Nostr client application with React 18.x, TailwindCSS 3.x, Vite, shadcn/ui, and Nostrify.
Template for building Nostr client application with React 18.x, TailwindCSS 3.x, Vite, shadcn/ui, and Nostrify.
## Features
- **Site Administration**: Content moderation and site management dashboard at `/admin` (see [ADMIN_DASHBOARD.md](ADMIN_DASHBOARD.md))
- **Nostr Protocol Integration**: Full NIP support with custom hooks for querying and publishing
- **Authentication**: Secure login with NIP-07 browser extensions, bunker connections, and secret keys
- **UI Components**: 48+ accessible components from shadcn/ui
- **Responsive Design**: Mobile-first approach with Tailwind CSS
- **Type Safety**: Full TypeScript support with proper error handling
-16
View File
@@ -1,16 +0,0 @@
{
"model": "claude-sonnet-4",
"temperature": 0.2,
"mcpServers": {
"js-dev": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@soapbox.pub/js-dev-mcp@latest"]
},
"nostr": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@nostrbook/mcp@latest"]
}
}
}
-1
View File
@@ -1 +0,0 @@
CONTEXT.md
+461 -301
View File
File diff suppressed because it is too large. Load diff
+7 -3
View File
@@ -10,6 +10,8 @@
"deploy": "npm run build && npx -y nostr-deploy-cli deploy --skip-setup"
},
"dependencies": {
"@fontsource-variable/inter": "^5.2.6",
"@getalby/sdk": "^5.1.1",
"@hookform/resolvers": "^3.9.0",
"@nostrify/nostrify": "npm:@jsr/nostrify__nostrify@^0.46.4",
"@nostrify/react": "npm:@jsr/nostrify__react@^0.2.8",
@@ -49,20 +51,21 @@
"date-fns": "^3.6.0",
"embla-carousel-react": "^8.3.0",
"input-otp": "^1.2.4",
"lucide-react": "^0.462.0",
"next-themes": "^0.3.0",
"lucide-react": "^0.542.0",
"nostr-tools": "^2.13.0",
"qrcode": "^1.5.4",
"react": "^18.3.1",
"react-day-picker": "^8.10.1",
"react-dom": "^18.3.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",
"recharts": "^2.12.7",
"sonner": "^1.5.0",
"tailwind-merge": "^2.5.2",
"tailwindcss-animate": "^1.0.7",
"vaul": "^0.9.3",
"webln": "^0.3.2",
"zod": "^3.25.71"
},
"devDependencies": {
@@ -73,6 +76,7 @@
"@testing-library/jest-dom": "^6.6.3",
"@testing-library/react": "^16.3.0",
"@types/node": "^22.5.5",
"@types/qrcode": "^1.5.5",
"@types/react": "^18.3.1",
"@types/react-dom": "^18.3.1",
"@vitejs/plugin-react-swc": "^3.5.0",
+9 -8
View File
@@ -7,10 +7,10 @@ import { InferSeoMetaPlugin } from '@unhead/addons';
import { Suspense } from 'react';
import NostrProvider from '@/components/NostrProvider';
import { Toaster } from "@/components/ui/toaster";
import { Toaster as Sonner } from "@/components/ui/sonner";
import { TooltipProvider } from "@/components/ui/tooltip";
import { NostrLoginProvider } from '@nostrify/react/login';
import { AppProvider } from '@/components/AppProvider';
import { NWCProvider } from '@/contexts/NWCContext';
import { AppConfig } from '@/contexts/AppContext';
import AppRouter from './AppRouter';
@@ -49,13 +49,14 @@ export function App() {
<QueryClientProvider client={queryClient}>
<NostrLoginProvider storageKey='nostr:login'>
<NostrProvider>
<TooltipProvider>
<Toaster />
<Sonner />
<Suspense>
<AppRouter />
</Suspense>
</TooltipProvider>
<NWCProvider>
<TooltipProvider>
<Toaster />
<Suspense>
<AppRouter />
</Suspense>
</TooltipProvider>
</NWCProvider>
</NostrProvider>
</NostrLoginProvider>
</QueryClientProvider>
+3
View File
@@ -3,6 +3,7 @@ import { ScrollToTop } from "./components/ScrollToTop";
import Index from "./pages/Index";
import { NIP19Page } from "./pages/NIP19Page";
import { AdminDashboard } from "./pages/AdminDashboard";
import NotFound from "./pages/NotFound";
export function AppRouter() {
@@ -11,6 +12,8 @@ export function AppRouter() {
<ScrollToTop />
<Routes>
<Route path="/" element={<Index />} />
{/* Admin dashboard route - must come before NIP-19 route */}
<Route path="/admin" element={<AdminDashboard />} />
{/* NIP-19 route for npub1, note1, naddr1, nevent1, nprofile1 */}
<Route path="/:nip19" element={<NIP19Page />} />
{/* ADD ALL CUSTOM ROUTES ABOVE THE CATCH-ALL "*" ROUTE */}
+41
View File
@@ -0,0 +1,41 @@
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { Button } from '@/components/ui/button';
import { nip19 } from 'nostr-tools';
import { Shield } from 'lucide-react';
// Get admin npub from environment variable
const ADMIN_NPUB = import.meta.env.VITE_ADMIN_NPUB;
export function AdminDashboardLink() {
const { user } = useCurrentUser();
// Only show admin link if user is the configured admin
if (!user || !ADMIN_NPUB) {
return null;
}
let adminPubkey: string = '';
try {
const decoded = nip19.decode(ADMIN_NPUB);
// @ts-expect-error - TypeScript has issues with nostr-tools type inference
if (decoded.type === 'npub') {
adminPubkey = decoded.data as unknown as string;
}
} catch {
return null;
}
// Only show if current user is the admin
if (user.pubkey !== adminPubkey) {
return null;
}
return (
<Button variant="outline" size="sm" asChild>
<a href="/admin" className="flex items-center gap-2">
<Shield className="h-4 w-4" />
Site Admin
</a>
</Button>
);
}
+395
View File
@@ -0,0 +1,395 @@
import { useState, forwardRef } from 'react';
import { Wallet, Plus, Trash2, Zap, Globe, WalletMinimal, CheckCircle, X } from 'lucide-react';
import { Button } from '@/components/ui/button';
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from '@/components/ui/dialog';
import {
Drawer,
DrawerContent,
DrawerDescription,
DrawerHeader,
DrawerTitle,
DrawerTrigger,
DrawerClose,
} from '@/components/ui/drawer';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Badge } from '@/components/ui/badge';
import { Separator } from '@/components/ui/separator';
import { useNWC } from '@/hooks/useNWCContext';
import { useWallet } from '@/hooks/useWallet';
import { useToast } from '@/hooks/useToast';
import { useIsMobile } from '@/hooks/useIsMobile';
import type { NWCConnection, NWCInfo } from '@/hooks/useNWC';
interface WalletModalProps {
children?: React.ReactNode;
className?: string;
}
// Extracted AddWalletContent to prevent re-renders
const AddWalletContent = forwardRef<HTMLDivElement, {
alias: string;
setAlias: (value: string) => void;
connectionUri: string;
setConnectionUri: (value: string) => void;
}>(({ alias, setAlias, connectionUri, setConnectionUri }, ref) => (
<div className="space-y-4 px-4" ref={ref}>
<div>
<Label htmlFor="alias">Wallet Name (optional)</Label>
<Input
id="alias"
placeholder="My Lightning Wallet"
value={alias}
onChange={(e) => setAlias(e.target.value)}
/>
</div>
<div>
<Label htmlFor="connection-uri">Connection URI</Label>
<Textarea
id="connection-uri"
placeholder="nostr+walletconnect://..."
value={connectionUri}
onChange={(e) => setConnectionUri(e.target.value)}
rows={3}
/>
</div>
</div>
));
AddWalletContent.displayName = 'AddWalletContent';
// Extracted WalletContent to prevent re-renders
const WalletContent = forwardRef<HTMLDivElement, {
hasWebLN: boolean;
isDetecting: boolean;
hasNWC: boolean;
connections: NWCConnection[];
connectionInfo: Record<string, NWCInfo>;
activeConnection: string | null;
handleSetActive: (cs: string) => void;
handleRemoveConnection: (cs: string) => void;
setAddDialogOpen: (open: boolean) => void;
}>(({
hasWebLN,
isDetecting,
hasNWC,
connections,
connectionInfo,
activeConnection,
handleSetActive,
handleRemoveConnection,
setAddDialogOpen
}, ref) => (
<div className="space-y-6 px-4 pb-4" ref={ref}>
{/* Current Status */}
<div className="space-y-3">
<h3 className="font-medium">Current Status</h3>
<div className="grid gap-3">
{/* WebLN */}
<div className="flex items-center justify-between p-3 border rounded-lg">
<div className="flex items-center gap-3">
<Globe className="h-4 w-4 text-muted-foreground" />
<div>
<p className="text-sm font-medium">WebLN</p>
<p className="text-xs text-muted-foreground">Browser extension</p>
</div>
</div>
<div className="flex items-center gap-2">
{hasWebLN && <CheckCircle className="h-4 w-4 text-green-600" />}
<Badge variant={hasWebLN ? "default" : "secondary"} className="text-xs">
{isDetecting ? "..." : hasWebLN ? "Ready" : "Not Found"}
</Badge>
</div>
</div>
{/* NWC */}
<div className="flex items-center justify-between p-3 border rounded-lg">
<div className="flex items-center gap-3">
<WalletMinimal className="h-4 w-4 text-muted-foreground" />
<div>
<p className="text-sm font-medium">Nostr Wallet Connect</p>
<p className="text-xs text-muted-foreground">
{connections.length > 0
? `${connections.length} wallet${connections.length !== 1 ? 's' : ''} connected`
: "Remote wallet connection"
}
</p>
</div>
</div>
<div className="flex items-center gap-2">
{hasNWC && <CheckCircle className="h-4 w-4 text-green-600" />}
<Badge variant={hasNWC ? "default" : "secondary"} className="text-xs">
{hasNWC ? "Ready" : "None"}
</Badge>
</div>
</div>
</div>
</div>
<Separator />
{/* NWC Management */}
<div className="space-y-4">
<div className="flex items-center justify-between">
<h3 className="font-medium">Nostr Wallet Connect</h3>
<Button size="sm" variant="outline" onClick={() => setAddDialogOpen(true)}>
<Plus className="h-4 w-4 mr-1" />
Add
</Button>
</div>
{/* Connected Wallets List */}
{connections.length === 0 ? (
<div className="text-center py-6 text-muted-foreground">
<p className="text-sm">No wallets connected</p>
</div>
) : (
<div className="space-y-2">
{connections.map((connection) => {
const info = connectionInfo[connection.connectionString];
const isActive = activeConnection === connection.connectionString;
return (
<div key={connection.connectionString} className={`flex items-center justify-between p-3 border rounded-lg ${isActive ? 'ring-2 ring-primary' : ''}`}>
<div className="flex items-center gap-3">
<WalletMinimal className="h-4 w-4 text-muted-foreground" />
<div>
<p className="text-sm font-medium">
{connection.alias || info?.alias || 'Lightning Wallet'}
</p>
<p className="text-xs text-muted-foreground">
NWC Connection
</p>
</div>
</div>
<div className="flex items-center gap-2">
{isActive && <CheckCircle className="h-4 w-4 text-green-600" />}
{!isActive && (
<Button
size="sm"
variant="ghost"
onClick={() => handleSetActive(connection.connectionString)}
>
<Zap className="h-3 w-3" />
</Button>
)}
<Button
size="sm"
variant="ghost"
onClick={() => handleRemoveConnection(connection.connectionString)}
>
<Trash2 className="h-3 w-3" />
</Button>
</div>
</div>
);
})}
</div>
)}
</div>
{/* Help */}
{!hasWebLN && connections.length === 0 && (
<>
<Separator />
<div className="text-center py-4 space-y-2">
<p className="text-sm text-muted-foreground">
Install a WebLN extension or connect a NWC wallet for zaps.
</p>
</div>
</>
)}
</div>
));
WalletContent.displayName = 'WalletContent';
export function WalletModal({ children, className }: WalletModalProps) {
const [open, setOpen] = useState(false);
const [addDialogOpen, setAddDialogOpen] = useState(false);
const [connectionUri, setConnectionUri] = useState('');
const [alias, setAlias] = useState('');
const [isConnecting, setIsConnecting] = useState(false);
const isMobile = useIsMobile();
const {
connections,
activeConnection,
connectionInfo,
addConnection,
removeConnection,
setActiveConnection
} = useNWC();
const { hasWebLN, isDetecting } = useWallet();
const hasNWC = connections.length > 0 && connections.some(c => c.isConnected);
const { toast } = useToast();
const handleAddConnection = async () => {
if (!connectionUri.trim()) {
toast({
title: 'Connection URI required',
description: 'Please enter a valid NWC connection URI.',
variant: 'destructive',
});
return;
}
setIsConnecting(true);
try {
const success = await addConnection(connectionUri.trim(), alias.trim() || undefined);
if (success) {
setConnectionUri('');
setAlias('');
setAddDialogOpen(false);
}
} finally {
setIsConnecting(false);
}
};
const handleRemoveConnection = (connectionString: string) => {
removeConnection(connectionString);
};
const handleSetActive = (connectionString: string) => {
setActiveConnection(connectionString);
toast({
title: 'Active wallet changed',
description: 'The selected wallet is now active for zaps.',
});
};
const walletContentProps = {
hasWebLN,
isDetecting,
hasNWC,
connections,
connectionInfo,
activeConnection,
handleSetActive,
handleRemoveConnection,
setAddDialogOpen,
};
const addWalletDialog = (
<Dialog open={addDialogOpen} onOpenChange={setAddDialogOpen}>
<DialogContent className="sm:max-w-[425px]">
<DialogHeader>
<DialogTitle>Connect NWC Wallet</DialogTitle>
<DialogDescription>
Enter your connection string from a compatible wallet.
</DialogDescription>
</DialogHeader>
<AddWalletContent
alias={alias}
setAlias={setAlias}
connectionUri={connectionUri}
setConnectionUri={setConnectionUri}
/>
<DialogFooter className="px-4">
<Button
onClick={handleAddConnection}
disabled={isConnecting || !connectionUri.trim()}
className="w-full"
>
{isConnecting ? 'Connecting...' : 'Connect'}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
if (isMobile) {
return (
<>
<Drawer open={open} onOpenChange={setOpen}>
<DrawerTrigger asChild>
{children || (
<Button variant="outline" size="sm" className={className}>
<Wallet className="h-4 w-4 mr-2" />
Wallet Settings
</Button>
)}
</DrawerTrigger>
<DrawerContent className="h-full">
<DrawerHeader className="text-center relative">
<DrawerClose asChild>
<Button variant="ghost" size="sm" className="absolute right-4 top-4">
<X className="h-4 w-4" />
<span className="sr-only">Close</span>
</Button>
</DrawerClose>
<DrawerTitle className="flex items-center justify-center gap-2 pt-2">
<Wallet className="h-5 w-5" />
Lightning Wallet
</DrawerTitle>
<DrawerDescription>
Connect your lightning wallet to send zaps instantly.
</DrawerDescription>
</DrawerHeader>
<div className="overflow-y-auto">
<WalletContent {...walletContentProps} />
</div>
</DrawerContent>
</Drawer>
{/* Render Add Wallet as a separate Drawer for mobile */}
<Drawer open={addDialogOpen} onOpenChange={setAddDialogOpen}>
<DrawerContent>
<DrawerHeader>
<DrawerTitle>Connect NWC Wallet</DrawerTitle>
<DrawerDescription>
Enter your connection string from a compatible wallet.
</DrawerDescription>
</DrawerHeader>
<AddWalletContent
alias={alias}
setAlias={setAlias}
connectionUri={connectionUri}
setConnectionUri={setConnectionUri}
/>
<div className="p-4">
<Button
onClick={handleAddConnection}
disabled={isConnecting || !connectionUri.trim()}
className="w-full"
>
{isConnecting ? 'Connecting...' : 'Connect'}
</Button>
</div>
</DrawerContent>
</Drawer>
</>
);
}
return (
<>
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
{children || (
<Button variant="outline" size="sm" className={className}>
<Wallet className="h-4 w-4 mr-2" />
Wallet Settings
</Button>
)}
</DialogTrigger>
<DialogContent className="sm:max-w-[500px] max-h-[80vh] overflow-y-auto">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<Wallet className="h-5 w-5" />
Lightning Wallet
</DialogTitle>
<DialogDescription>
Connect your lightning wallet to send zaps instantly.
</DialogDescription>
</DialogHeader>
<WalletContent {...walletContentProps} />
</DialogContent>
</Dialog>
{addWalletDialog}
</>
);
}
+58
View File
@@ -0,0 +1,58 @@
import { ZapDialog } from '@/components/ZapDialog';
import { useZaps } from '@/hooks/useZaps';
import { useWallet } from '@/hooks/useWallet';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useAuthor } from '@/hooks/useAuthor';
import { Zap } from 'lucide-react';
import type { Event } from 'nostr-tools';
interface ZapButtonProps {
target: Event;
className?: string;
showCount?: boolean;
zapData?: { count: number; totalSats: number; isLoading?: boolean };
}
export function ZapButton({
target,
className = "text-xs ml-1",
showCount = true,
zapData: externalZapData
}: ZapButtonProps) {
const { user } = useCurrentUser();
const { data: author } = useAuthor(target?.pubkey || '');
const { webln, activeNWC } = useWallet();
// Only fetch data if not provided externally
const { totalSats: fetchedTotalSats, isLoading } = useZaps(
externalZapData ? [] : target ?? [], // Empty array prevents fetching if external data provided
webln,
activeNWC
);
// Don't show zap button if user is not logged in, is the author, or author has no lightning address
if (!user || !target || user.pubkey === target.pubkey || (!author?.metadata?.lud16 && !author?.metadata?.lud06)) {
return null;
}
// Use external data if provided, otherwise use fetched data
const totalSats = externalZapData?.totalSats ?? fetchedTotalSats;
const showLoading = externalZapData?.isLoading || isLoading;
return (
<ZapDialog target={target}>
<div className={`flex items-center gap-1 ${className}`}>
<Zap className="h-4 w-4" />
<span className="text-xs">
{showLoading ? (
'...'
) : showCount && totalSats > 0 ? (
`${totalSats.toLocaleString()}`
) : (
'Zap'
)}
</span>
</div>
</ZapDialog>
);
}
+470
View File
@@ -0,0 +1,470 @@
import { useState, useEffect, useRef, forwardRef } from 'react';
import { Zap, Copy, Check, ExternalLink, Sparkle, Sparkles, Star, Rocket, ArrowLeft, X } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { cn } from '@/lib/utils';
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogTrigger,
} from '@/components/ui/dialog';
import {
Drawer,
DrawerContent,
DrawerDescription,
DrawerHeader,
DrawerTitle,
DrawerTrigger,
DrawerClose,
} from '@/components/ui/drawer';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Card, CardContent } from '@/components/ui/card';
import { Separator } from '@/components/ui/separator';
import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useAuthor } from '@/hooks/useAuthor';
import { useToast } from '@/hooks/useToast';
import { useZaps } from '@/hooks/useZaps';
import { useWallet } from '@/hooks/useWallet';
import { useIsMobile } from '@/hooks/useIsMobile';
import type { Event } from 'nostr-tools';
import QRCode from 'qrcode';
interface ZapDialogProps {
target: Event;
children?: React.ReactNode;
className?: string;
}
const presetAmounts = [
{ amount: 1, icon: Sparkle },
{ amount: 50, icon: Sparkles },
{ amount: 100, icon: Zap },
{ amount: 250, icon: Star },
{ amount: 1000, icon: Rocket },
];
interface ZapContentProps {
invoice: string | null;
amount: number | string;
comment: string;
isZapping: boolean;
qrCodeUrl: string;
copied: boolean;
hasWebLN: boolean;
handleZap: () => void;
handleCopy: () => void;
openInWallet: () => void;
setAmount: (amount: number | string) => void;
setComment: (comment: string) => void;
inputRef: React.RefObject<HTMLInputElement>;
zap: (amount: number, comment: string) => void;
}
// Moved ZapContent outside of ZapDialog to prevent re-renders causing focus loss
const ZapContent = forwardRef<HTMLDivElement, ZapContentProps>(({
invoice,
amount,
comment,
isZapping,
qrCodeUrl,
copied,
hasWebLN,
handleZap,
handleCopy,
openInWallet,
setAmount,
setComment,
inputRef,
zap,
}, ref) => (
<div ref={ref}>
{invoice ? (
<div className="flex flex-col h-full min-h-0">
{/* Payment amount display */}
<div className="text-center pt-4">
<div className="text-2xl font-bold">{amount} sats</div>
</div>
<Separator className="my-4" />
<div className="flex flex-col justify-center min-h-0 flex-1 px-2">
{/* QR Code */}
<div className="flex justify-center">
<Card className="p-3 [@media(max-height:680px)]:max-w-[65vw] max-w-[95vw] mx-auto">
<CardContent className="p-0 flex justify-center">
{qrCodeUrl ? (
<img
src={qrCodeUrl}
alt="Lightning Invoice QR Code"
className="w-full h-auto aspect-square max-w-full object-contain"
/>
) : (
<div className="w-full aspect-square bg-muted animate-pulse rounded" />
)}
</CardContent>
</Card>
</div>
{/* Invoice input */}
<div className="space-y-2 mt-4">
<Label htmlFor="invoice">Lightning Invoice</Label>
<div className="flex gap-2 min-w-0">
<Input
id="invoice"
value={invoice}
readOnly
className="font-mono text-xs min-w-0 flex-1 overflow-hidden text-ellipsis"
onClick={(e) => e.currentTarget.select()}
/>
<Button
variant="outline"
size="icon"
onClick={handleCopy}
className="shrink-0"
>
{copied ? (
<Check className="h-4 w-4 text-green-600" />
) : (
<Copy className="h-4 w-4" />
)}
</Button>
</div>
</div>
{/* Payment buttons */}
<div className="space-y-3 mt-4">
{hasWebLN && (
<Button
onClick={() => {
const finalAmount = typeof amount === 'string' ? parseInt(amount, 10) : amount;
zap(finalAmount, comment);
}}
disabled={isZapping}
className="w-full"
size="lg"
>
<Zap className="h-4 w-4 mr-2" />
{isZapping ? "Processing..." : "Pay with WebLN"}
</Button>
)}
<Button
variant="outline"
onClick={openInWallet}
className="w-full"
size="lg"
>
<ExternalLink className="h-4 w-4 mr-2" />
Open in Lightning Wallet
</Button>
<div className="text-xs sm:text-[.65rem] text-muted-foreground text-center">
Scan the QR code or copy the invoice to pay with any Lightning wallet.
</div>
</div>
</div>
</div>
) : (
<>
<div className="grid gap-3 px-4 py-4 w-full overflow-hidden">
<ToggleGroup
type="single"
value={String(amount)}
onValueChange={(value) => {
if (value) {
setAmount(parseInt(value, 10));
}
}}
className="grid grid-cols-5 gap-1 w-full"
>
{presetAmounts.map(({ amount: presetAmount, icon: Icon }) => (
<ToggleGroupItem
key={presetAmount}
value={String(presetAmount)}
className="flex flex-col h-auto min-w-0 text-xs px-1 py-2"
>
<Icon className="h-4 w-4 mb-1" />
<span className="truncate">{presetAmount}</span>
</ToggleGroupItem>
))}
</ToggleGroup>
<div className="flex items-center gap-2">
<div className="h-px flex-1 bg-muted" />
<span className="text-xs text-muted-foreground">OR</span>
<div className="h-px flex-1 bg-muted" />
</div>
<Input
ref={inputRef}
id="custom-amount"
type="number"
placeholder="Custom amount"
value={amount}
onChange={(e) => setAmount(e.target.value)}
className="w-full text-sm"
/>
<Textarea
id="custom-comment"
placeholder="Add a comment (optional)"
value={comment}
onChange={(e) => setComment(e.target.value)}
className="w-full resize-none text-sm"
rows={2}
/>
</div>
<div className="px-4 pb-4">
<Button onClick={handleZap} className="w-full" disabled={isZapping} size="default">
{isZapping ? (
'Creating invoice...'
) : (
<>
<Zap className="h-4 w-4 mr-2" />
Zap {amount} sats
</>
)}
</Button>
</div>
</>
)}
</div>
));
ZapContent.displayName = 'ZapContent';
export function ZapDialog({ target, children, className }: ZapDialogProps) {
const [open, setOpen] = useState(false);
const { user } = useCurrentUser();
const { data: author } = useAuthor(target.pubkey);
const { toast } = useToast();
const { webln, activeNWC, hasWebLN, detectWebLN } = useWallet();
const { zap, isZapping, invoice, setInvoice } = useZaps(target, webln, activeNWC, () => setOpen(false));
const [amount, setAmount] = useState<number | string>(100);
const [comment, setComment] = useState<string>('');
const [copied, setCopied] = useState(false);
const [qrCodeUrl, setQrCodeUrl] = useState<string>('');
const inputRef = useRef<HTMLInputElement>(null);
const isMobile = useIsMobile();
useEffect(() => {
if (target) {
setComment('Zapped with MKStack!');
}
}, [target]);
// Detect WebLN when dialog opens
useEffect(() => {
if (open && !hasWebLN) {
detectWebLN();
}
}, [open, hasWebLN, detectWebLN]);
// Generate QR code
useEffect(() => {
let isCancelled = false;
const generateQR = async () => {
if (!invoice) {
setQrCodeUrl('');
return;
}
try {
const url = await QRCode.toDataURL(invoice.toUpperCase(), {
width: 512,
margin: 2,
color: {
dark: '#000000',
light: '#FFFFFF',
},
});
if (!isCancelled) {
setQrCodeUrl(url);
}
} catch (err) {
if (!isCancelled) {
console.error('Failed to generate QR code:', err);
}
}
};
generateQR();
return () => {
isCancelled = true;
};
}, [invoice]);
const handleCopy = async () => {
if (invoice) {
await navigator.clipboard.writeText(invoice);
setCopied(true);
toast({
title: 'Invoice copied',
description: 'Lightning invoice copied to clipboard',
});
setTimeout(() => setCopied(false), 2000);
}
};
const openInWallet = () => {
if (invoice) {
const lightningUrl = `lightning:${invoice}`;
window.open(lightningUrl, '_blank');
}
};
useEffect(() => {
if (open) {
setAmount(100);
setInvoice(null);
setCopied(false);
setQrCodeUrl('');
} else {
// Clean up state when dialog closes
setAmount(100);
setInvoice(null);
setCopied(false);
setQrCodeUrl('');
}
}, [open, setInvoice]);
const handleZap = () => {
const finalAmount = typeof amount === 'string' ? parseInt(amount, 10) : amount;
zap(finalAmount, comment);
};
const contentProps = {
invoice,
amount,
comment,
isZapping,
qrCodeUrl,
copied,
hasWebLN,
handleZap,
handleCopy,
openInWallet,
setAmount,
setComment,
inputRef,
zap,
};
if (!user || user.pubkey === target.pubkey || !author?.metadata?.lud06 && !author?.metadata?.lud16) {
return null;
}
if (isMobile) {
// Use drawer for entire mobile flow, make it full-screen when showing invoice
return (
<Drawer
open={open}
onOpenChange={(newOpen) => {
// Reset invoice when closing
if (!newOpen) {
setInvoice(null);
setQrCodeUrl('');
}
setOpen(newOpen);
}}
dismissible={true} // Always allow dismissal via drag
snapPoints={invoice ? [0.5, 0.75, 0.98] : [0.98]}
activeSnapPoint={invoice ? 0.98 : 0.98}
modal={true}
shouldScaleBackground={false}
fadeFromIndex={0}
>
<DrawerTrigger asChild>
<div className={`cursor-pointer ${className || ''}`}>
{children}
</div>
</DrawerTrigger>
<DrawerContent
key={invoice ? 'payment' : 'form'}
className={cn(
"transition-all duration-300",
invoice ? "h-full max-h-screen" : "max-h-[98vh]"
)}
data-testid="zap-modal"
>
<DrawerHeader className="text-center relative">
{/* Back button when showing invoice */}
{invoice && (
<Button
variant="ghost"
size="sm"
onClick={() => {
setInvoice(null);
setQrCodeUrl('');
}}
className="absolute left-4 top-4 flex items-center gap-2"
>
<ArrowLeft className="h-4 w-4" />
</Button>
)}
{/* Close button */}
<DrawerClose asChild>
<Button
variant="ghost"
size="sm"
className="absolute right-4 top-4"
>
<X className="h-4 w-4" />
<span className="sr-only">Close</span>
</Button>
</DrawerClose>
<DrawerTitle className="text-lg break-words pt-2">
{invoice ? 'Lightning Payment' : 'Send a Zap'}
</DrawerTitle>
<DrawerDescription className="text-sm break-words text-center">
{invoice ? (
'Pay with Bitcoin Lightning Network'
) : (
'Zaps are small Bitcoin payments that support the creator of this item. If you enjoyed this, consider sending a zap!'
)}
</DrawerDescription>
</DrawerHeader>
<div className="flex-1 overflow-y-auto px-4 pb-4">
<ZapContent {...contentProps} />
</div>
</DrawerContent>
</Drawer>
);
}
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<div className={`cursor-pointer ${className || ''}`}>
{children}
</div>
</DialogTrigger>
<DialogContent className="sm:max-w-[425px] max-h-[95vh] overflow-hidden" data-testid="zap-modal">
<DialogHeader>
<DialogTitle className="text-lg break-words">
{invoice ? 'Lightning Payment' : 'Send a Zap'}
</DialogTitle>
<DialogDescription className="text-sm text-center break-words">
{invoice ? (
'Pay with Bitcoin Lightning Network'
) : (
<>
Zaps are small Bitcoin payments that support the creator of this item. If you enjoyed this, consider sending a zap!
</>
)}
</DialogDescription>
</DialogHeader>
<div className="overflow-y-auto">
<ZapContent {...contentProps} />
</div>
</DialogContent>
</Dialog>
);
}
+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,
@@ -11,6 +11,7 @@ import {
} from '@/components/ui/dropdown-menu.tsx';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar.tsx';
import { RelaySelector } from '@/components/RelaySelector';
import { WalletModal } from '@/components/WalletModal';
import { useLoggedInAccounts, type Account } from '@/hooks/useLoggedInAccounts';
import { genUserName } from '@/lib/genUserName';
@@ -63,6 +64,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'
+9 -84
View File
@@ -2,7 +2,7 @@
// 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, Key, UserPlus, FileText, Shield, User, Sparkles, LogIn, Lock, CheckCircle, Copy, Upload, Globe, FileSignature, Wand2 } from 'lucide-react';
import { Download, Key, UserPlus, FileText, Shield, User, Sparkles, LogIn, Lock, CheckCircle, Upload, Globe, FileSignature, Wand2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
@@ -30,7 +30,7 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
const [isLoading, setIsLoading] = useState(false);
const [nsec, setNsec] = useState('');
const [showSparkles, setShowSparkles] = useState(false);
const [keySecured, setKeySecured] = useState<'none' | 'copied' | 'downloaded'>('none');
const [keySecured, setKeySecured] = useState<'none' | 'downloaded'>('none');
const [profileData, setProfileData] = useState({
name: '',
about: '',
@@ -80,7 +80,7 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
const url = globalThis.URL.createObjectURL(blob);
// Sanitize filename
const filename = sanitizeFilename('secret-key.txt');
const filename = sanitizeFilename('nostr-nsec-key.txt');
// Create a temporary link element and trigger download
const a = document.createElement('a');
@@ -110,14 +110,7 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
}
};
const copyKey = () => {
navigator.clipboard.writeText(nsec);
setKeySecured('copied');
toast({
title: 'Copied to clipboard!',
description: 'Key copied to clipboard.',
});
};
const finishKeySetup = () => {
try {
@@ -251,44 +244,31 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
const getTitle = () => {
if (step === 'welcome') return (
<span className="flex items-center justify-center gap-2">
<UserPlus className="w-5 h-5 text-primary" />
Create Your Account
</span>
);
if (step === 'generate') return (
<span className="flex items-center justify-center gap-2">
<Wand2 className="w-5 h-5 text-primary" />
Generating Your Key
</span>
);
if (step === 'download') return (
<span className="flex items-center justify-center gap-2">
<Lock className="w-5 h-5 text-primary" />
Secret Key
</span>
);
if (step === 'profile') return (
<span className="flex items-center justify-center gap-2">
<FileSignature className="w-5 h-5 text-primary" />
Create Your Profile
</span>
);
return (
<span className="flex items-center justify-center gap-2">
<User className="w-5 h-5 text-primary" />
Welcome!
</span>
);
};
const getDescription = () => {
if (step === 'welcome') return 'Ready to join the Nostr network?';
if (step === 'generate') return 'Creating your secret key to access Nostr.';
if (step === 'profile') return 'Tell others about yourself.';
return 'Your account is ready!';
};
// Reset state when dialog opens
useEffect(() => {
if (isOpen) {
@@ -320,9 +300,6 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
<DialogTitle className={cn('font-semibold text-center text-lg')}>
{getTitle()}
</DialogTitle>
<DialogDescription className={cn(`text-muted-foreground text-center ${step === 'download' && 'hidden'}`)}>
{getDescription()}
</DialogDescription>
</DialogHeader>
<div className='px-6 pt-2 pb-4 space-y-4 overflow-y-scroll flex-1'>
{/* Welcome Step - New engaging introduction */}
@@ -360,11 +337,6 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
</div>
<div className='space-y-3'>
<p className='text-muted-foreground px-5'>
Join the Nostr network and take control of your social media experience.
Your journey begins by generating a secret key.
</p>
<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')}
@@ -372,10 +344,6 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
<LogIn className='w-5 h-5 mr-2' />
Get Started
</Button>
<p className='text-xs text-muted-foreground'>
Free forever • Decentralized • Your data, your control
</p>
</div>
</div>
)}
@@ -533,7 +501,7 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
Download as File
</div>
<div className='text-xs text-muted-foreground'>
Save as secret-key.txt file
Save as nostr-nsec-key.txt file
</div>
</div>
{keySecured === 'downloaded' && (
@@ -546,67 +514,24 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
</CardContent>
</Card>
{/* Copy Option */}
<Card className={`cursor-pointer transition-all duration-200 ${
keySecured === 'copied'
? '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={copyKey}
>
<div className='flex items-center gap-3 w-full'>
<div className={`p-1.5 rounded-lg ${
keySecured === 'copied'
? 'bg-green-100 dark:bg-green-900'
: 'bg-primary/10'
}`}>
{keySecured === 'copied' ? (
<CheckCircle className='w-4 h-4 text-green-600' />
) : (
<Copy className='w-4 h-4 text-primary' />
)}
</div>
<div className='flex-1 text-left'>
<div className='font-medium text-sm'>
Copy to Clipboard
</div>
<div className='text-xs text-muted-foreground'>
Save to password manager
</div>
<div className='text-[.7rem] text-muted-foreground'>
{nsec.slice(0,16)}...
</div>
</div>
{keySecured === 'copied' && (
<div className='text-xs font-medium text-green-600'>
✓ Copied
</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 !== 'none'
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 === 'none'}
disabled={keySecured !== 'downloaded'}
>
<LogIn className='w-4 h-4 mr-2 flex-shrink-0' />
<span className="text-center leading-tight">
{keySecured === 'none' ? (
<>
Please secure your key first
Please download your key first
</>
) : (
<>
-29
View File
@@ -1,29 +0,0 @@
import { useTheme } from "next-themes"
import { Toaster as Sonner } from "sonner"
type ToasterProps = React.ComponentProps<typeof Sonner>
const Toaster = ({ ...props }: ToasterProps) => {
const { theme = "system" } = useTheme()
return (
<Sonner
theme={theme as ToasterProps["theme"]}
className="toaster group"
toastOptions={{
classNames: {
toast:
"group toast group-[.toaster]:bg-background group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg",
description: "group-[.toast]:text-muted-foreground",
actionButton:
"group-[.toast]:bg-primary group-[.toast]:text-primary-foreground",
cancelButton:
"group-[.toast]:bg-muted group-[.toast]:text-muted-foreground",
},
}}
{...props}
/>
)
}
export { Toaster }
+8
View File
@@ -0,0 +1,8 @@
import { ReactNode } from 'react';
import { useNWCInternal as useNWCHook } from '@/hooks/useNWC';
import { NWCContext } from '@/hooks/useNWCContext';
export function NWCProvider({ children }: { children: ReactNode }) {
const nwc = useNWCHook();
return <NWCContext.Provider value={nwc}>{children}</NWCContext.Provider>;
}
+237
View File
@@ -0,0 +1,237 @@
import { useNostr } from '@nostrify/react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useCurrentUser } from './useCurrentUser';
import { useNostrPublish } from './useNostrPublish';
import { nip19 } from 'nostr-tools';
// Custom kind for admin storage
const ADMIN_STORAGE_KIND = 39767;
// Get admin npub from environment variable
const ADMIN_NPUB = import.meta.env.VITE_ADMIN_NPUB;
export interface AdminStorageData {
hiddenEvents: string[];
allowList: string[];
denyList: string[];
blockedWords: string[];
caseSensitive: boolean;
wholeWordsOnly: boolean;
enableModeration: boolean;
autoHideBlocked: boolean;
requireApproval: boolean;
siteName: string;
siteDescription: string;
}
const defaultAdminData: AdminStorageData = {
hiddenEvents: [],
allowList: [],
denyList: [],
blockedWords: [],
caseSensitive: false,
wholeWordsOnly: true,
enableModeration: true,
autoHideBlocked: true,
requireApproval: false,
siteName: '',
siteDescription: '',
};
export function useAdminStorage() {
const { nostr } = useNostr();
const { user } = useCurrentUser();
const { mutateAsync: publishEvent } = useNostrPublish();
const queryClient = useQueryClient();
// Get admin pubkey
let adminPubkey: string = '';
try {
if (ADMIN_NPUB) {
const decoded = nip19.decode(ADMIN_NPUB);
// @ts-expect-error - TypeScript has issues with nostr-tools type inference
if (decoded.type === 'npub') {
adminPubkey = decoded.data as unknown as string;
}
}
} catch {
// Invalid admin npub
}
// Check if current user is admin
const isAdmin = user?.pubkey === adminPubkey && !!adminPubkey;
// Query for admin storage events
const adminDataQuery = useQuery({
queryKey: ['admin-storage', adminPubkey],
queryFn: async ({ signal }) => {
if (!adminPubkey) return defaultAdminData;
const timeoutSignal = AbortSignal.timeout(1500);
const combinedSignal = AbortSignal.any([signal, timeoutSignal]);
// Query for admin storage events
const events = await nostr.query([{
kinds: [ADMIN_STORAGE_KIND],
authors: [adminPubkey],
'#d': ['admin-config'],
limit: 1
}], { signal: combinedSignal });
if (events.length === 0) {
return defaultAdminData;
}
// Get the most recent event
const latestEvent = events.sort((a, b) => b.created_at - a.created_at)[0];
try {
const data = JSON.parse(latestEvent.content) as AdminStorageData;
// Merge with defaults to handle missing fields
return { ...defaultAdminData, ...data };
} catch {
return defaultAdminData;
}
},
enabled: !!adminPubkey,
});
// Mutation to save admin data
const saveAdminData = useMutation({
mutationFn: async (data: Partial<AdminStorageData>) => {
if (!isAdmin) {
throw new Error('Only admin can save admin data');
}
const currentData = adminDataQuery.data || defaultAdminData;
const updatedData = { ...currentData, ...data };
await publishEvent({
kind: ADMIN_STORAGE_KIND,
content: JSON.stringify(updatedData),
tags: [
['d', 'admin-config'],
['alt', 'Site administration configuration and policies'],
],
});
return updatedData;
},
onSuccess: (updatedData) => {
// Update the cache with new data
queryClient.setQueryData(['admin-storage', adminPubkey], updatedData);
},
});
// Helper functions for specific data updates
const updateHiddenEvents = (hiddenEvents: string[]) =>
saveAdminData.mutateAsync({ hiddenEvents });
const updateAllowList = (allowList: string[]) =>
saveAdminData.mutateAsync({ allowList });
const updateDenyList = (denyList: string[]) =>
saveAdminData.mutateAsync({ denyList });
const updateBlockedWords = (blockedWords: string[]) =>
saveAdminData.mutateAsync({ blockedWords });
const updateModerationSettings = (settings: {
caseSensitive?: boolean;
wholeWordsOnly?: boolean;
enableModeration?: boolean;
autoHideBlocked?: boolean;
requireApproval?: boolean;
}) => saveAdminData.mutateAsync(settings);
const updateSiteSettings = (settings: {
siteName?: string;
siteDescription?: string;
}) => saveAdminData.mutateAsync(settings);
return {
// Data
data: adminDataQuery.data || defaultAdminData,
isLoading: adminDataQuery.isLoading,
error: adminDataQuery.error,
// Auth
isAdmin,
adminPubkey,
// Mutations
saveAdminData: saveAdminData.mutateAsync,
isSaving: saveAdminData.isPending,
// Helper functions
updateHiddenEvents,
updateAllowList,
updateDenyList,
updateBlockedWords,
updateModerationSettings,
updateSiteSettings,
};
}
// Hook for checking if content should be hidden based on admin policies
export function useContentFilter() {
const { data: adminData } = useAdminStorage();
const isContentHidden = (eventId: string): boolean => {
return adminData.hiddenEvents.includes(eventId);
};
const isUserBlocked = (pubkey: string): boolean => {
// If allow list exists and user is not on it, they're blocked
if (adminData.allowList.length > 0 && !adminData.allowList.includes(pubkey)) {
return true;
}
// If user is on deny list, they're blocked
return adminData.denyList.includes(pubkey);
};
const isContentBlocked = (content: string): boolean => {
if (!adminData.enableModeration || adminData.blockedWords.length === 0) {
return false;
}
const text = adminData.caseSensitive ? content : content.toLowerCase();
return adminData.blockedWords.some(word => {
const searchWord = adminData.caseSensitive ? word : word.toLowerCase();
if (adminData.wholeWordsOnly) {
// Match whole words only
const regex = new RegExp(`\\b${searchWord.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\b`);
return regex.test(text);
} else {
// Match partial words
return text.includes(searchWord);
}
});
};
const shouldHideContent = (eventId: string, pubkey: string, content: string): boolean => {
if (!adminData.enableModeration) return false;
// Check if manually hidden
if (isContentHidden(eventId)) return true;
// Check if user is blocked
if (isUserBlocked(pubkey)) return true;
// Check if content contains blocked words and auto-hide is enabled
if (adminData.autoHideBlocked && isContentBlocked(content)) return true;
return false;
};
return {
isContentHidden,
isUserBlocked,
isContentBlocked,
shouldHideContent,
adminData,
};
}
+221
View File
@@ -0,0 +1,221 @@
import { useState, useCallback } from 'react';
import { useLocalStorage } from '@/hooks/useLocalStorage';
import { useToast } from '@/hooks/useToast';
import { LN } from '@getalby/sdk';
export interface NWCConnection {
connectionString: string;
alias?: string;
isConnected: boolean;
client?: LN;
}
export interface NWCInfo {
alias?: string;
color?: string;
pubkey?: string;
network?: string;
methods?: string[];
notifications?: string[];
}
export function useNWCInternal() {
const { toast } = useToast();
const [connections, setConnections] = useLocalStorage<NWCConnection[]>('nwc-connections', []);
const [activeConnection, setActiveConnection] = useLocalStorage<string | null>('nwc-active-connection', null);
const [connectionInfo, setConnectionInfo] = useState<Record<string, NWCInfo>>({});
// Add new connection
const addConnection = async (uri: string, alias?: string): Promise<boolean> => {
const parseNWCUri = (uri: string): { connectionString: string } | null => {
try {
if (!uri.startsWith('nostr+walletconnect://') && !uri.startsWith('nostrwalletconnect://')) {
console.error('Invalid NWC URI protocol:', { protocol: uri.split('://')[0] });
return null;
}
return { connectionString: uri };
} catch (error) {
console.error('Failed to parse NWC URI:', error);
return null;
}
};
const parsed = parseNWCUri(uri);
if (!parsed) {
toast({
title: 'Invalid NWC URI',
description: 'Please check the connection string and try again.',
variant: 'destructive',
});
return false;
}
const existingConnection = connections.find(c => c.connectionString === parsed.connectionString);
if (existingConnection) {
toast({
title: 'Connection already exists',
description: 'This wallet is already connected.',
variant: 'destructive',
});
return false;
}
try {
let timeoutId: NodeJS.Timeout | undefined;
const testPromise = new Promise((resolve, reject) => {
try {
const client = new LN(parsed.connectionString);
resolve(client);
} catch (error) {
reject(error);
}
});
const timeoutPromise = new Promise<never>((_, reject) => {
timeoutId = setTimeout(() => reject(new Error('Connection test timeout')), 10000);
});
try {
await Promise.race([testPromise, timeoutPromise]) as LN;
if (timeoutId) clearTimeout(timeoutId);
} catch (error) {
if (timeoutId) clearTimeout(timeoutId);
throw error;
}
const connection: NWCConnection = {
connectionString: parsed.connectionString,
alias: alias || 'NWC Wallet',
isConnected: true,
};
setConnectionInfo(prev => ({
...prev,
[parsed.connectionString]: {
alias: connection.alias,
methods: ['pay_invoice'],
},
}));
const newConnections = [...connections, connection];
setConnections(newConnections);
if (connections.length === 0 || !activeConnection)
setActiveConnection(parsed.connectionString);
toast({
title: 'Wallet connected',
description: `Successfully connected to ${connection.alias}.`,
});
return true;
} catch (error) {
console.error('NWC connection failed:', error);
const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
toast({
title: 'Connection failed',
description: `Could not connect to the wallet: ${errorMessage}`,
variant: 'destructive',
});
return false;
}
};
// Remove connection
const removeConnection = (connectionString: string) => {
const filtered = connections.filter(c => c.connectionString !== connectionString);
setConnections(filtered);
if (activeConnection === connectionString) {
const newActive = filtered.length > 0 ? filtered[0].connectionString : null;
setActiveConnection(newActive);
}
setConnectionInfo(prev => {
const newInfo = { ...prev };
delete newInfo[connectionString];
return newInfo;
});
toast({
title: 'Wallet disconnected',
description: 'The wallet connection has been removed.',
});
};
// Get active connection
const getActiveConnection = useCallback((): NWCConnection | null => {
if (!activeConnection && connections.length > 0) {
setActiveConnection(connections[0].connectionString);
return connections[0];
}
if (!activeConnection) return null;
const found = connections.find(c => c.connectionString === activeConnection);
return found || null;
}, [activeConnection, connections, setActiveConnection]);
// Send payment using the SDK
const sendPayment = useCallback(async (
connection: NWCConnection,
invoice: string
): Promise<{ preimage: string }> => {
if (!connection.connectionString) {
throw new Error('Invalid connection: missing connection string');
}
let client: LN;
try {
client = new LN(connection.connectionString);
} catch (error) {
console.error('Failed to create NWC client:', error);
throw new Error(`Failed to create NWC client: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
try {
let timeoutId: NodeJS.Timeout | undefined;
const timeoutPromise = new Promise<never>((_, reject) => {
timeoutId = setTimeout(() => reject(new Error('Payment timeout after 15 seconds')), 15000);
});
const paymentPromise = client.pay(invoice);
try {
const response = await Promise.race([paymentPromise, timeoutPromise]) as { preimage: string };
if (timeoutId) clearTimeout(timeoutId);
return response;
} catch (error) {
if (timeoutId) clearTimeout(timeoutId);
throw error;
}
} catch (error) {
console.error('NWC payment failed:', error);
if (error instanceof Error) {
if (error.message.includes('timeout')) {
throw new Error('Payment timed out. Please try again.');
} else if (error.message.includes('insufficient')) {
throw new Error('Insufficient balance in connected wallet.');
} else if (error.message.includes('invalid')) {
throw new Error('Invalid invoice or connection. Please check your wallet.');
} else {
throw new Error(`Payment failed: ${error.message}`);
}
}
throw new Error('Payment failed with unknown error');
}
}, []);
return {
connections,
activeConnection,
connectionInfo,
addConnection,
removeConnection,
setActiveConnection,
getActiveConnection,
sendPayment,
};
}
+15
View File
@@ -0,0 +1,15 @@
import { useContext } from 'react';
import { createContext } from 'react';
import { useNWCInternal } from '@/hooks/useNWC';
type NWCContextType = ReturnType<typeof useNWCInternal>;
export const NWCContext = createContext<NWCContextType | null>(null);
export function useNWC(): NWCContextType {
const context = useContext(NWCContext);
if (!context) {
throw new Error('useNWC must be used within a NWCProvider');
}
return context;
}
+94
View File
@@ -0,0 +1,94 @@
import { useState, useEffect, useCallback, useMemo } from 'react';
import { useNWC } from '@/hooks/useNWCContext';
import type { WebLNProvider } from 'webln';
import { requestProvider } from 'webln';
export interface WalletStatus {
hasWebLN: boolean;
hasNWC: boolean;
webln: WebLNProvider | null;
activeNWC: ReturnType<typeof useNWC>['getActiveConnection'] extends () => infer T ? T : null;
isDetecting: boolean;
preferredMethod: 'nwc' | 'webln' | 'manual';
}
export function useWallet() {
const [webln, setWebln] = useState<WebLNProvider | null>(null);
const [isDetecting, setIsDetecting] = useState(false);
const [hasAttemptedDetection, setHasAttemptedDetection] = useState(false);
const { connections, getActiveConnection } = useNWC();
// Get the active connection directly - no memoization to avoid stale state
const activeNWC = getActiveConnection();
// Detect WebLN
const detectWebLN = useCallback(async () => {
if (webln || isDetecting) return webln;
setIsDetecting(true);
try {
const provider = await requestProvider();
setWebln(provider);
setHasAttemptedDetection(true);
return provider;
} catch (error) {
// Only log the error if it's not the common "no provider" error
if (error instanceof Error && !error.message.includes('no WebLN provider')) {
console.warn('WebLN detection error:', error);
}
setWebln(null);
setHasAttemptedDetection(true);
return null;
} finally {
setIsDetecting(false);
}
}, [webln, isDetecting]);
// Only auto-detect once on mount
useEffect(() => {
if (!hasAttemptedDetection) {
detectWebLN();
}
}, [detectWebLN, hasAttemptedDetection]);
// Test WebLN connection
const testWebLN = useCallback(async (): Promise<boolean> => {
if (!webln) return false;
try {
await webln.enable();
return true;
} catch (error) {
console.error('WebLN test failed:', error);
return false;
}
}, [webln]);
// Calculate status values reactively
const hasNWC = useMemo(() => {
return connections.length > 0 && connections.some(c => c.isConnected);
}, [connections]);
// Determine preferred payment method
const preferredMethod: WalletStatus['preferredMethod'] = activeNWC
? 'nwc'
: webln
? 'webln'
: 'manual';
const status: WalletStatus = {
hasWebLN: !!webln,
hasNWC,
webln,
activeNWC,
isDetecting,
preferredMethod,
};
return {
...status,
hasAttemptedDetection,
detectWebLN,
testWebLN,
};
}
+338
View File
@@ -0,0 +1,338 @@
import { useState, useMemo, useEffect, useCallback } from 'react';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useAuthor } from '@/hooks/useAuthor';
import { useAppContext } from '@/hooks/useAppContext';
import { useToast } from '@/hooks/useToast';
import { useNWC } from '@/hooks/useNWCContext';
import type { NWCConnection } from '@/hooks/useNWC';
import { nip57 } from 'nostr-tools';
import type { Event } from 'nostr-tools';
import type { WebLNProvider } from 'webln';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { useNostr } from '@nostrify/react';
import type { NostrEvent } from '@nostrify/nostrify';
export function useZaps(
target: Event | Event[],
webln: WebLNProvider | null,
_nwcConnection: NWCConnection | null,
onZapSuccess?: () => void
) {
const { nostr } = useNostr();
const { toast } = useToast();
const { user } = useCurrentUser();
const { config } = useAppContext();
const queryClient = useQueryClient();
// Handle the case where an empty array is passed (from ZapButton when external data is provided)
const actualTarget = Array.isArray(target) ? (target.length > 0 ? target[0] : null) : target;
const author = useAuthor(actualTarget?.pubkey);
const { sendPayment, getActiveConnection } = useNWC();
const [isZapping, setIsZapping] = useState(false);
const [invoice, setInvoice] = useState<string | null>(null);
// Cleanup state when component unmounts
useEffect(() => {
return () => {
setIsZapping(false);
setInvoice(null);
};
}, []);
const { data: zapEvents, ...query } = useQuery<NostrEvent[], Error>({
queryKey: ['zaps', actualTarget?.id],
staleTime: 30000, // 30 seconds
refetchInterval: (query) => {
// Only refetch if the query is currently being observed (component is mounted)
return query.getObserversCount() > 0 ? 60000 : false;
},
queryFn: async (c) => {
if (!actualTarget) return [];
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(5000)]);
// Query for zap receipts for this specific event
if (actualTarget.kind >= 30000 && actualTarget.kind < 40000) {
// Addressable event
const identifier = actualTarget.tags.find((t) => t[0] === 'd')?.[1] || '';
const events = await nostr.query([{
kinds: [9735],
'#a': [`${actualTarget.kind}:${actualTarget.pubkey}:${identifier}`],
}], { signal });
return events;
} else {
// Regular event
const events = await nostr.query([{
kinds: [9735],
'#e': [actualTarget.id],
}], { signal });
return events;
}
},
enabled: !!actualTarget?.id,
});
// Process zap events into simple counts and totals
const { zapCount, totalSats, zaps } = useMemo(() => {
if (!zapEvents || !Array.isArray(zapEvents) || !actualTarget) {
return { zapCount: 0, totalSats: 0, zaps: [] };
}
let count = 0;
let sats = 0;
zapEvents.forEach(zap => {
count++;
// Try multiple methods to extract the amount:
// Method 1: amount tag (from zap request, sometimes copied to receipt)
const amountTag = zap.tags.find(([name]) => name === 'amount')?.[1];
if (amountTag) {
const millisats = parseInt(amountTag);
sats += Math.floor(millisats / 1000);
return;
}
// Method 2: Extract from bolt11 invoice
const bolt11Tag = zap.tags.find(([name]) => name === 'bolt11')?.[1];
if (bolt11Tag) {
try {
const invoiceSats = nip57.getSatoshisAmountFromBolt11(bolt11Tag);
sats += invoiceSats;
return;
} catch (error) {
console.warn('Failed to parse bolt11 amount:', error);
}
}
// Method 3: Parse from description (zap request JSON)
const descriptionTag = zap.tags.find(([name]) => name === 'description')?.[1];
if (descriptionTag) {
try {
const zapRequest = JSON.parse(descriptionTag);
const requestAmountTag = zapRequest.tags?.find(([name]: string[]) => name === 'amount')?.[1];
if (requestAmountTag) {
const millisats = parseInt(requestAmountTag);
sats += Math.floor(millisats / 1000);
return;
}
} catch (error) {
console.warn('Failed to parse description JSON:', error);
}
}
console.warn('Could not extract amount from zap receipt:', zap.id);
});
return { zapCount: count, totalSats: sats, zaps: zapEvents };
}, [zapEvents, actualTarget]);
const zap = async (amount: number, comment: string) => {
if (amount <= 0) {
return;
}
setIsZapping(true);
setInvoice(null); // Clear any previous invoice at the start
if (!user) {
toast({
title: 'Login required',
description: 'You must be logged in to send a zap.',
variant: 'destructive',
});
setIsZapping(false);
return;
}
if (!actualTarget) {
toast({
title: 'Event not found',
description: 'Could not find the event to zap.',
variant: 'destructive',
});
setIsZapping(false);
return;
}
try {
if (!author.data || !author.data?.metadata || !author.data?.event ) {
toast({
title: 'Author not found',
description: 'Could not find the author of this item.',
variant: 'destructive',
});
setIsZapping(false);
return;
}
const { lud06, lud16 } = author.data.metadata;
if (!lud06 && !lud16) {
toast({
title: 'Lightning address not found',
description: 'The author does not have a lightning address configured.',
variant: 'destructive',
});
setIsZapping(false);
return;
}
// Get zap endpoint using the old reliable method
const zapEndpoint = await nip57.getZapEndpoint(author.data.event);
if (!zapEndpoint) {
toast({
title: 'Zap endpoint not found',
description: 'Could not find a zap endpoint for the author.',
variant: 'destructive',
});
setIsZapping(false);
return;
}
// Create zap request - use appropriate event format based on kind
// For addressable events (30000-39999), pass the object to get 'a' tag
// For all other events, pass the ID string to get 'e' tag
const event = (actualTarget.kind >= 30000 && actualTarget.kind < 40000)
? actualTarget
: actualTarget.id;
const zapAmount = amount * 1000; // convert to millisats
const zapRequest = nip57.makeZapRequest({
profile: actualTarget.pubkey,
event: event,
amount: zapAmount,
relays: [config.relayUrl],
comment
});
// Sign the zap request (but don't publish to relays - only send to LNURL endpoint)
if (!user.signer) {
throw new Error('No signer available');
}
const signedZapRequest = await user.signer.signEvent(zapRequest);
try {
const res = await fetch(`${zapEndpoint}?amount=${zapAmount}&nostr=${encodeURI(JSON.stringify(signedZapRequest))}`);
const responseData = await res.json();
if (!res.ok) {
throw new Error(`HTTP ${res.status}: ${responseData.reason || 'Unknown error'}`);
}
const newInvoice = responseData.pr;
if (!newInvoice || typeof newInvoice !== 'string') {
throw new Error('Lightning service did not return a valid invoice');
}
// Get the current active NWC connection dynamically
const currentNWCConnection = getActiveConnection();
// Try NWC first if available and properly connected
if (currentNWCConnection && currentNWCConnection.connectionString && currentNWCConnection.isConnected) {
try {
await sendPayment(currentNWCConnection, newInvoice);
// Clear states immediately on success
setIsZapping(false);
setInvoice(null);
toast({
title: 'Zap successful!',
description: `You sent ${amount} sats via NWC to the author.`,
});
// Invalidate zap queries to refresh counts
queryClient.invalidateQueries({ queryKey: ['zaps'] });
// Close dialog last to ensure clean state
onZapSuccess?.();
return;
} catch (nwcError) {
console.error('NWC payment failed, falling back:', nwcError);
// Show specific NWC error to user for debugging
const errorMessage = nwcError instanceof Error ? nwcError.message : 'Unknown NWC error';
toast({
title: 'NWC payment failed',
description: `${errorMessage}. Falling back to other payment methods...`,
variant: 'destructive',
});
}
}
if (webln) { // Try WebLN next
try {
await webln.sendPayment(newInvoice);
// Clear states immediately on success
setIsZapping(false);
setInvoice(null);
toast({
title: 'Zap successful!',
description: `You sent ${amount} sats to the author.`,
});
// Invalidate zap queries to refresh counts
queryClient.invalidateQueries({ queryKey: ['zaps'] });
// Close dialog last to ensure clean state
onZapSuccess?.();
} catch (weblnError) {
console.error('webln payment failed, falling back:', weblnError);
// Show specific WebLN error to user for debugging
const errorMessage = weblnError instanceof Error ? weblnError.message : 'Unknown WebLN error';
toast({
title: 'WebLN payment failed',
description: `${errorMessage}. Falling back to other payment methods...`,
variant: 'destructive',
});
setInvoice(newInvoice);
setIsZapping(false);
}
} else { // Default - show QR code and manual Lightning URI
setInvoice(newInvoice);
setIsZapping(false);
}
} catch (err) {
console.error('Zap error:', err);
toast({
title: 'Zap failed',
description: (err as Error).message,
variant: 'destructive',
});
setIsZapping(false);
}
} catch (err) {
console.error('Zap error:', err);
toast({
title: 'Zap failed',
description: (err as Error).message,
variant: 'destructive',
});
setIsZapping(false);
}
};
const resetInvoice = useCallback(() => {
setInvoice(null);
}, []);
return {
zaps,
zapCount,
totalSats,
...query,
zap,
isZapping,
invoice,
setInvoice,
resetInvoice,
};
}
+825
View File
@@ -0,0 +1,825 @@
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useAuthor } from '@/hooks/useAuthor';
import { useNostr } from '@nostrify/react';
import { useQuery } from '@tanstack/react-query';
import { useState } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { LoginArea } from '@/components/auth/LoginArea';
import { Skeleton } from '@/components/ui/skeleton';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Switch } from '@/components/ui/switch';
import { Separator } from '@/components/ui/separator';
import { AlertCircle, Shield, Ban, UserCheck, MessageSquareX, Trash2, Plus, Eye, EyeOff } from 'lucide-react';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { useAdminStorage } from '@/hooks/useAdminStorage';
import { nip19 } from 'nostr-tools';
import { genUserName } from '@/lib/genUserName';
import NotFound from './NotFound';
// Get admin npub from environment variable
const ADMIN_NPUB = import.meta.env.VITE_ADMIN_NPUB;
export function AdminDashboard() {
const { user } = useCurrentUser();
// Decode admin npub from environment variable
let adminPubkey: string = '';
let isValidAdminNpub = false;
try {
if (ADMIN_NPUB) {
const decoded = nip19.decode(ADMIN_NPUB);
// @ts-expect-error - TypeScript has issues with nostr-tools type inference
if (decoded.type === 'npub') {
adminPubkey = decoded.data as unknown as string;
isValidAdminNpub = true;
}
}
} catch {
// Invalid admin npub format
}
// Always call hooks - use empty string as fallback to avoid conditional calls
const adminAuthor = useAuthor(adminPubkey || '');
// Return NotFound if no valid admin npub is configured
if (!isValidAdminNpub) {
return <NotFound />;
}
// Check if current user is the site admin
const isAuthorized = user?.pubkey === adminPubkey;
if (!isAuthorized) {
return (
<div className="container mx-auto px-4 py-8 max-w-2xl">
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Shield className="h-5 w-5 text-amber-500" />
Site Admin Access Required
</CardTitle>
<CardDescription>
You need to be logged in as the site administrator to access this admin panel.
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
{adminAuthor.data?.metadata && (
<div className="flex items-center gap-3 p-4 bg-muted rounded-lg">
<Avatar>
<AvatarImage src={adminAuthor.data.metadata.picture} />
<AvatarFallback>
{(adminAuthor.data.metadata.name || genUserName(adminPubkey)).slice(0, 2).toUpperCase()}
</AvatarFallback>
</Avatar>
<div>
<p className="font-medium">
{adminAuthor.data.metadata.display_name || adminAuthor.data.metadata.name || genUserName(adminPubkey)}
</p>
<p className="text-sm text-muted-foreground">
Site Administrator
</p>
</div>
</div>
)}
<Alert>
<AlertCircle className="h-4 w-4" />
<AlertDescription>
Only the site administrator can access content moderation and site management features.
</AlertDescription>
</Alert>
<LoginArea className="w-full" />
</CardContent>
</Card>
</div>
);
}
return (
<div className="container mx-auto px-4 py-8 max-w-6xl">
<div className="mb-8">
<h1 className="text-3xl font-bold mb-2 flex items-center gap-2">
<Shield className="h-8 w-8" />
Site Administration
</h1>
<p className="text-muted-foreground">
Manage content moderation, user access controls, and site settings
</p>
</div>
<Tabs defaultValue="moderation" className="space-y-6">
<TabsList className="grid w-full grid-cols-5">
<TabsTrigger value="moderation">Content Moderation</TabsTrigger>
<TabsTrigger value="users">User Management</TabsTrigger>
<TabsTrigger value="blocked-words">Blocked Words</TabsTrigger>
<TabsTrigger value="analytics">Site Analytics</TabsTrigger>
<TabsTrigger value="settings">Site Settings</TabsTrigger>
</TabsList>
<TabsContent value="moderation">
<ContentModeration />
</TabsContent>
<TabsContent value="users">
<UserManagement />
</TabsContent>
<TabsContent value="blocked-words">
<BlockedWordsManagement />
</TabsContent>
<TabsContent value="analytics">
<SiteAnalytics />
</TabsContent>
<TabsContent value="settings">
<SiteSettings />
</TabsContent>
</Tabs>
</div>
);
}
function ContentModeration() {
const { nostr } = useNostr();
const { data: adminData, updateHiddenEvents, isSaving } = useAdminStorage();
const recentContent = useQuery({
queryKey: ['admin-recent-content'],
queryFn: async ({ signal }) => {
const timeoutSignal = AbortSignal.timeout(1500);
const combinedSignal = AbortSignal.any([signal, timeoutSignal]);
const events = await nostr.query([{
kinds: [1, 30023], // Notes and articles
limit: 50
}], { signal: combinedSignal });
return events.sort((a, b) => b.created_at - a.created_at);
},
});
const hideEvent = async (eventId: string) => {
const newHiddenEvents = [...adminData.hiddenEvents, eventId];
await updateHiddenEvents(newHiddenEvents);
};
const unhideEvent = async (eventId: string) => {
const newHiddenEvents = adminData.hiddenEvents.filter(id => id !== eventId);
await updateHiddenEvents(newHiddenEvents);
};
return (
<div className="space-y-6">
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Eye className="h-5 w-5" />
Recent Content Review
</CardTitle>
<CardDescription>
Review and moderate recent content posted to the site
</CardDescription>
</CardHeader>
<CardContent>
{recentContent.isLoading ? (
<div className="space-y-4">
{Array.from({ length: 5 }).map((_, i) => (
<div key={i} className="flex items-start gap-3 p-4 border rounded-lg">
<Skeleton className="h-10 w-10 rounded-full" />
<div className="flex-1 space-y-2">
<Skeleton className="h-4 w-24" />
<Skeleton className="h-4 w-full" />
<Skeleton className="h-4 w-3/4" />
</div>
<Skeleton className="h-8 w-20" />
</div>
))}
</div>
) : recentContent.data?.length ? (
<div className="space-y-4">
{recentContent.data.map((event) => {
const isHidden = adminData.hiddenEvents.includes(event.id);
return (
<div key={event.id} className={`flex items-start gap-3 p-4 border rounded-lg ${isHidden ? 'opacity-50 bg-muted' : ''}`}>
<UserAvatar pubkey={event.pubkey} />
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 mb-2">
<UserName pubkey={event.pubkey} />
<Badge variant={event.kind === 1 ? 'default' : 'secondary'}>
{event.kind === 1 ? 'Note' : 'Article'}
</Badge>
<span className="text-sm text-muted-foreground">
{new Date(event.created_at * 1000).toLocaleString()}
</span>
</div>
<p className="text-sm line-clamp-3">
{event.kind === 30023
? event.tags.find(([tag]) => tag === 'title')?.[1] || 'Untitled Article'
: event.content
}
</p>
</div>
<div className="flex gap-2">
{isHidden ? (
<Button
variant="outline"
size="sm"
onClick={() => unhideEvent(event.id)}
className="text-green-600 hover:text-green-700"
disabled={isSaving}
>
<Eye className="h-4 w-4 mr-1" />
Show
</Button>
) : (
<Button
variant="outline"
size="sm"
onClick={() => hideEvent(event.id)}
className="text-red-600 hover:text-red-700"
disabled={isSaving}
>
<EyeOff className="h-4 w-4 mr-1" />
Hide
</Button>
)}
</div>
</div>
);
})}
</div>
) : (
<p className="text-muted-foreground">No recent content found</p>
)}
</CardContent>
</Card>
</div>
);
}
function UserManagement() {
const { data: adminData, updateAllowList, updateDenyList, isSaving } = useAdminStorage();
const [newNpub, setNewNpub] = useState('');
const addToAllowList = async () => {
try {
const decoded = nip19.decode(newNpub);
if (decoded.type === 'npub') {
const pubkey = decoded.data as unknown as string;
if (!adminData.allowList.includes(pubkey)) {
const newAllowList = [...adminData.allowList, pubkey];
const newDenyList = adminData.denyList.filter(p => p !== pubkey); // Remove from deny list if present
await updateAllowList(newAllowList);
if (newDenyList.length !== adminData.denyList.length) {
await updateDenyList(newDenyList);
}
setNewNpub('');
}
}
} catch {
// Invalid npub format
}
};
const addToDenyList = async () => {
try {
const decoded = nip19.decode(newNpub);
if (decoded.type === 'npub') {
const pubkey = decoded.data as unknown as string;
if (!adminData.denyList.includes(pubkey)) {
const newDenyList = [...adminData.denyList, pubkey];
const newAllowList = adminData.allowList.filter(p => p !== pubkey); // Remove from allow list if present
await updateDenyList(newDenyList);
if (newAllowList.length !== adminData.allowList.length) {
await updateAllowList(newAllowList);
}
setNewNpub('');
}
}
} catch {
// Invalid npub format
}
};
const removeFromAllowList = async (pubkey: string) => {
const newAllowList = adminData.allowList.filter(p => p !== pubkey);
await updateAllowList(newAllowList);
};
const removeFromDenyList = async (pubkey: string) => {
const newDenyList = adminData.denyList.filter(p => p !== pubkey);
await updateDenyList(newDenyList);
};
return (
<div className="space-y-6">
{/* Add User Form */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<UserCheck className="h-5 w-5" />
Add User to Lists
</CardTitle>
<CardDescription>
Add users to allow list or deny list by their npub
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="flex gap-2">
<Input
placeholder="npub1abc123..."
value={newNpub}
onChange={(e) => setNewNpub(e.target.value)}
className="flex-1"
/>
<Button onClick={addToAllowList} variant="outline" className="text-green-600" disabled={isSaving}>
<Plus className="h-4 w-4 mr-1" />
Allow
</Button>
<Button onClick={addToDenyList} variant="outline" className="text-red-600" disabled={isSaving}>
<Ban className="h-4 w-4 mr-1" />
Deny
</Button>
</div>
</CardContent>
</Card>
<div className="grid gap-6 md:grid-cols-2">
{/* Allow List */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2 text-green-600">
<UserCheck className="h-5 w-5" />
Allow List ({adminData.allowList.length})
</CardTitle>
<CardDescription>
Users explicitly allowed to post content
</CardDescription>
</CardHeader>
<CardContent>
{adminData.allowList.length > 0 ? (
<div className="space-y-2">
{adminData.allowList.map((pubkey) => (
<UserListItem
key={pubkey}
pubkey={pubkey}
onRemove={() => removeFromAllowList(pubkey)}
variant="allow"
disabled={isSaving}
/>
))}
</div>
) : (
<p className="text-muted-foreground text-sm">No users in allow list</p>
)}
</CardContent>
</Card>
{/* Deny List */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2 text-red-600">
<Ban className="h-5 w-5" />
Deny List ({adminData.denyList.length})
</CardTitle>
<CardDescription>
Users blocked from posting content
</CardDescription>
</CardHeader>
<CardContent>
{adminData.denyList.length > 0 ? (
<div className="space-y-2">
{adminData.denyList.map((pubkey) => (
<UserListItem
key={pubkey}
pubkey={pubkey}
onRemove={() => removeFromDenyList(pubkey)}
variant="deny"
disabled={isSaving}
/>
))}
</div>
) : (
<p className="text-muted-foreground text-sm">No users in deny list</p>
)}
</CardContent>
</Card>
</div>
</div>
);
}
function BlockedWordsManagement() {
const { data: adminData, updateBlockedWords, updateModerationSettings, isSaving } = useAdminStorage();
const [newWord, setNewWord] = useState('');
const addBlockedWord = async () => {
const word = newWord.trim();
if (word && !adminData.blockedWords.includes(word)) {
const newBlockedWords = [...adminData.blockedWords, word];
await updateBlockedWords(newBlockedWords);
setNewWord('');
}
};
const removeBlockedWord = async (word: string) => {
const newBlockedWords = adminData.blockedWords.filter(w => w !== word);
await updateBlockedWords(newBlockedWords);
};
const handleKeyPress = (e: React.KeyboardEvent) => {
if (e.key === 'Enter') {
addBlockedWord();
}
};
return (
<div className="space-y-6">
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<MessageSquareX className="h-5 w-5" />
Content Filtering Settings
</CardTitle>
<CardDescription>
Configure automatic content filtering options
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="flex items-center space-x-2">
<Switch
id="case-sensitive"
checked={adminData.caseSensitive}
onCheckedChange={(checked) => updateModerationSettings({ caseSensitive: checked })}
disabled={isSaving}
/>
<Label htmlFor="case-sensitive">Case sensitive matching</Label>
</div>
<div className="flex items-center space-x-2">
<Switch
id="whole-words"
checked={adminData.wholeWordsOnly}
onCheckedChange={(checked) => updateModerationSettings({ wholeWordsOnly: checked })}
disabled={isSaving}
/>
<Label htmlFor="whole-words">Match whole words only</Label>
</div>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>Add Blocked Word</CardTitle>
<CardDescription>
Add words or phrases to automatically filter from content
</CardDescription>
</CardHeader>
<CardContent>
<div className="flex gap-2">
<Input
placeholder="Enter word or phrase to block..."
value={newWord}
onChange={(e) => setNewWord(e.target.value)}
onKeyPress={handleKeyPress}
className="flex-1"
/>
<Button onClick={addBlockedWord} disabled={isSaving}>
<Plus className="h-4 w-4 mr-1" />
Add
</Button>
</div>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>Blocked Words ({adminData.blockedWords.length})</CardTitle>
<CardDescription>
Currently blocked words and phrases
</CardDescription>
</CardHeader>
<CardContent>
{adminData.blockedWords.length > 0 ? (
<div className="space-y-2">
{adminData.blockedWords.map((word) => (
<div key={word} className="flex items-center justify-between p-2 border rounded">
<span className="font-mono text-sm">{word}</span>
<Button
variant="ghost"
size="sm"
onClick={() => removeBlockedWord(word)}
className="text-red-600 hover:text-red-700"
disabled={isSaving}
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
))}
</div>
) : (
<p className="text-muted-foreground">No blocked words configured</p>
)}
</CardContent>
</Card>
</div>
);
}
function SiteAnalytics() {
const { nostr } = useNostr();
const siteStats = useQuery({
queryKey: ['site-analytics'],
queryFn: async ({ signal }) => {
const timeoutSignal = AbortSignal.timeout(1500);
const combinedSignal = AbortSignal.any([signal, timeoutSignal]);
// Get recent site activity
const recentEvents = await nostr.query([{
kinds: [1, 30023], // Notes and articles
limit: 100
}], { signal: combinedSignal });
const uniqueAuthors = new Set(recentEvents.map(e => e.pubkey)).size;
const last24h = recentEvents.filter(e => e.created_at > Date.now() / 1000 - 86400).length;
const last7d = recentEvents.filter(e => e.created_at > Date.now() / 1000 - 604800).length;
return {
totalEvents: recentEvents.length,
uniqueAuthors,
last24h,
last7d,
notes: recentEvents.filter(e => e.kind === 1).length,
articles: recentEvents.filter(e => e.kind === 30023).length,
};
},
});
return (
<div className="space-y-6">
<div className="grid gap-6 md:grid-cols-2 lg:grid-cols-4">
<Card>
<CardHeader className="pb-2">
<CardTitle className="text-sm font-medium">Total Content</CardTitle>
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{siteStats.data?.totalEvents || 0}</div>
<p className="text-xs text-muted-foreground">Recent events</p>
</CardContent>
</Card>
<Card>
<CardHeader className="pb-2">
<CardTitle className="text-sm font-medium">Active Users</CardTitle>
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{siteStats.data?.uniqueAuthors || 0}</div>
<p className="text-xs text-muted-foreground">Unique authors</p>
</CardContent>
</Card>
<Card>
<CardHeader className="pb-2">
<CardTitle className="text-sm font-medium">Last 24h</CardTitle>
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{siteStats.data?.last24h || 0}</div>
<p className="text-xs text-muted-foreground">New posts</p>
</CardContent>
</Card>
<Card>
<CardHeader className="pb-2">
<CardTitle className="text-sm font-medium">Last 7 days</CardTitle>
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{siteStats.data?.last7d || 0}</div>
<p className="text-xs text-muted-foreground">New posts</p>
</CardContent>
</Card>
</div>
<Card>
<CardHeader>
<CardTitle>Content Breakdown</CardTitle>
<CardDescription>
Distribution of content types on your site
</CardDescription>
</CardHeader>
<CardContent>
{siteStats.isLoading ? (
<div className="space-y-2">
<Skeleton className="h-4 w-full" />
<Skeleton className="h-4 w-3/4" />
</div>
) : (
<div className="space-y-4">
<div className="flex items-center justify-between">
<span>Notes</span>
<Badge variant="default">{siteStats.data?.notes || 0}</Badge>
</div>
<div className="flex items-center justify-between">
<span>Articles</span>
<Badge variant="secondary">{siteStats.data?.articles || 0}</Badge>
</div>
</div>
)}
</CardContent>
</Card>
</div>
);
}
function SiteSettings() {
const { data: adminData, updateSiteSettings, updateModerationSettings, isSaving } = useAdminStorage();
return (
<div className="space-y-6">
<Card>
<CardHeader>
<CardTitle>Site Information</CardTitle>
<CardDescription>
Basic information about your site
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-2">
<Label htmlFor="site-name">Site Name</Label>
<Input
id="site-name"
value={adminData.siteName}
onChange={(e) => updateSiteSettings({ siteName: e.target.value })}
placeholder="My Nostr Site"
disabled={isSaving}
/>
</div>
<div className="space-y-2">
<Label htmlFor="site-description">Site Description</Label>
<Textarea
id="site-description"
value={adminData.siteDescription}
onChange={(e) => updateSiteSettings({ siteDescription: e.target.value })}
placeholder="A description of your site..."
rows={3}
disabled={isSaving}
/>
</div>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>Content Moderation</CardTitle>
<CardDescription>
Configure how content moderation works on your site
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="flex items-center justify-between">
<div className="space-y-0.5">
<Label>Enable Content Moderation</Label>
<p className="text-sm text-muted-foreground">
Apply blocked words and user lists to filter content
</p>
</div>
<Switch
checked={adminData.enableModeration}
onCheckedChange={(checked) => updateModerationSettings({ enableModeration: checked })}
disabled={isSaving}
/>
</div>
<Separator />
<div className="flex items-center justify-between">
<div className="space-y-0.5">
<Label>Auto-hide Blocked Content</Label>
<p className="text-sm text-muted-foreground">
Automatically hide content that matches blocked words
</p>
</div>
<Switch
checked={adminData.autoHideBlocked}
onCheckedChange={(checked) => updateModerationSettings({ autoHideBlocked: checked })}
disabled={isSaving}
/>
</div>
<Separator />
<div className="flex items-center justify-between">
<div className="space-y-0.5">
<Label>Require Content Approval</Label>
<p className="text-sm text-muted-foreground">
All content must be manually approved before showing
</p>
</div>
<Switch
checked={adminData.requireApproval}
onCheckedChange={(checked) => updateModerationSettings({ requireApproval: checked })}
disabled={isSaving}
/>
</div>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>Environment Configuration</CardTitle>
<CardDescription>
Current environment settings
</CardDescription>
</CardHeader>
<CardContent>
<div className="space-y-2 font-mono text-sm">
<div className="flex justify-between">
<span>VITE_ADMIN_NPUB:</span>
<span className="text-muted-foreground">
{ADMIN_NPUB ? `${ADMIN_NPUB.slice(0, 16)}...` : 'Not configured'}
</span>
</div>
</div>
{!ADMIN_NPUB && (
<Alert className="mt-4">
<AlertCircle className="h-4 w-4" />
<AlertDescription>
Set VITE_ADMIN_NPUB environment variable to configure admin access.
</AlertDescription>
</Alert>
)}
</CardContent>
</Card>
</div>
);
}
// Helper components
function UserAvatar({ pubkey }: { pubkey: string }) {
const author = useAuthor(pubkey);
return (
<Avatar>
<AvatarImage src={author.data?.metadata?.picture} />
<AvatarFallback>
{(author.data?.metadata?.name || genUserName(pubkey)).slice(0, 2).toUpperCase()}
</AvatarFallback>
</Avatar>
);
}
function UserName({ pubkey }: { pubkey: string }) {
const author = useAuthor(pubkey);
return (
<span className="font-medium">
{author.data?.metadata?.display_name || author.data?.metadata?.name || genUserName(pubkey)}
</span>
);
}
function UserListItem({ pubkey, onRemove, variant, disabled }: {
pubkey: string;
onRemove: () => void;
variant: 'allow' | 'deny';
disabled?: boolean;
}) {
const npub = nip19.npubEncode(pubkey);
return (
<div className="flex items-center gap-3 p-2 rounded-lg border">
<UserAvatar pubkey={pubkey} />
<div className="flex-1 min-w-0">
<p className="font-medium text-sm truncate">
<UserName pubkey={pubkey} />
</p>
<p className="text-xs text-muted-foreground truncate">
{npub.slice(0, 20)}...
</p>
</div>
<Button
variant="ghost"
size="sm"
onClick={onRemove}
className={variant === 'allow' ? 'text-green-600 hover:text-green-700' : 'text-red-600 hover:text-red-700'}
disabled={disabled}
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
);
}
+6 -3
View File
@@ -4,6 +4,7 @@ import { BrowserRouter } from 'react-router-dom';
import { NostrLoginProvider } from '@nostrify/react/login';
import NostrProvider from '@/components/NostrProvider';
import { AppProvider } from '@/components/AppProvider';
import { NWCProvider } from '@/contexts/NWCContext';
import { AppConfig } from '@/contexts/AppContext';
interface TestAppProps {
@@ -31,9 +32,11 @@ export function TestApp({ children }: TestAppProps) {
<QueryClientProvider client={queryClient}>
<NostrLoginProvider storageKey='test-login'>
<NostrProvider>
<BrowserRouter>
{children}
</BrowserRouter>
<NWCProvider>
<BrowserRouter>
{children}
</BrowserRouter>
</NWCProvider>
</NostrProvider>
</NostrLoginProvider>
</QueryClientProvider>