Author SHA1 Message Date
Chad Curtis c0dca78709 Admin Dashboard init 2025-09-02 00:09:46 +00:00
25 changed files with 1579 additions and 938 deletions

No files matched your search

+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
+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
+16 -111
View File
@@ -114,9 +114,9 @@ This project comes with custom hooks for querying and publishing events on the N
### Nostr Implementation Guidelines
- Always check the full list of existing NIPs before implementing any Nostr features to see what kinds are currently in use across all NIPs.
- If any existing kind or NIP might offer the required functionality, read the relevant NIPs to investigate thoroughly. Several NIPs may need to be read before making a decision.
- Only generate new kind numbers if no existing suitable kinds are found after comprehensive research.
- Always use the `nostr__read_nips_index` tool before implementing any Nostr features to see what kinds are currently in use across all NIPs.
- If any existing kind or NIP might offer the required functionality, use the `nostr__read_nip` tool to investigate thoroughly. Several NIPs may need to be read before making a decision.
- Only generate new kind numbers with the `nostr__generate_kind` tool if no existing suitable kinds are found after comprehensive research.
Knowing when to create a new kind versus reusing an existing kind requires careful judgement. Introducing new kinds means the project won't be interoperable with existing clients. But deviating too far from the schema of a particular kind can cause different interoperability issues.
@@ -124,7 +124,7 @@ Knowing when to create a new kind versus reusing an existing kind requires caref
When implementing features that could use existing NIPs, follow this decision framework:
1. **Thorough NIP Review**: Before considering a new kind, always perform a comprehensive review of existing NIPs and their associated kinds. Get an overview of all NIPs, and then read specific NIPs and kind documentation to investigate any potentially relevant NIPs or kinds in detail. The goal is to find the closest existing solution.
1. **Thorough NIP Review**: Before considering a new kind, always perform a comprehensive review of existing NIPs and their associated kinds. Use the `nostr__read_nips_index` tool to get an overview, and then `nostr__read_nip` and `nostr__read_kind` to investigate any potentially relevant NIPs or kinds in detail. The goal is to find the closest existing solution.
2. **Prioritize Existing NIPs**: Always prefer extending or using existing NIPs over creating custom kinds, even if they require minor compromises in functionality.
@@ -142,7 +142,7 @@ When implementing features that could use existing NIPs, follow this decision fr
- The data structure is fundamentally different from existing patterns
- The use case requires different storage characteristics (regular vs replaceable vs addressable)
6. **Custom Kind Publishing**: When publishing events with custom generated kinds, always include a NIP-31 "alt" tag with a human-readable description of the event's purpose.
6. **Custom Kind Publishing**: When publishing events with custom kinds generated by `nostr__generate_kind`, always include a NIP-31 "alt" tag with a human-readable description of the event's purpose.
**Example Decision Process**:
```
@@ -281,85 +281,6 @@ function useCustomHook() {
}
```
### Connecting to Multiple Nostr Relays
By default, the `nostr` object from `useNostr` uses a pool configuration that reads data from 1 relay and publishes to all configured relays. However, you can connect to specific relays or groups of relays for more granular control:
#### Single Relay Connection
To read and publish from one specific relay, use `nostr.relay()` with a WebSocket URL:
```typescript
import { useNostr } from '@nostrify/react';
function useSpecificRelay() {
const { nostr } = useNostr();
// Connect to a specific relay
const relay = nostr.relay('wss://relay.damus.io');
// Query from this specific relay only
const events = await relay.query([{ kinds: [1], limit: 20 }], { signal });
// Publish to this specific relay only
await relay.event({ kind: 1, content: 'Hello from specific relay!' });
}
```
#### Multiple Relay Group
To read and publish from a specific set of relays, use `nostr.group()` with an array of relay URLs:
```typescript
import { useNostr } from '@nostrify/react';
function useRelayGroup() {
const { nostr } = useNostr();
// Create a group of specific relays
const relayGroup = nostr.group([
'wss://relay.damus.io',
'wss://relay.nostr.band',
'wss://nos.lol'
]);
// Query from all relays in the group
const events = await relayGroup.query([{ kinds: [1], limit: 20 }], { signal });
// Publish to all relays in the group
await relayGroup.event({ kind: 1, content: 'Hello from relay group!' });
}
```
#### API Consistency
Both `relay` and `group` objects have the same API as the main `nostr` object, including:
- `.query()` - Query events with filters
- `.req()` - Create subscriptions
- `.event()` - Publish events
- All other Nostr protocol methods
#### Use Cases
**Single Relay (`nostr.relay()`):**
- Testing specific relay behavior
- Querying relay-specific content
- Debugging connectivity issues
- Working with specialized relays
**Relay Group (`nostr.group()`):**
- Querying from trusted relay sets
- Publishing to specific communities
- Load balancing across relay subsets
- Geographic relay optimization
**Default Pool (`nostr`):**
- General application queries
- Maximum reach for publishing
- Default user experience
- Simplified relay management
### Query Nostr Data with `useNostr` and Tanstack Query
When querying Nostr, the best practice is to create custom hooks that combine `useNostr` and `useQuery` to get the required data.
@@ -1017,14 +938,14 @@ import { Card, CardContent } from '@/components/ui/card';
To add custom fonts, follow these steps:
1. **Install a font package** using npm:
1. **Install a font package** using the `js-dev__npm_add_package` tool:
**Any Google Font can be installed** using the @fontsource packages. Examples:
- For Inter Variable: `@fontsource-variable/inter`
- For Roboto: `@fontsource/roboto`
- For Outfit Variable: `@fontsource-variable/outfit`
- For Poppins: `@fontsource/poppins`
- For Open Sans: `@fontsource/open-sans`
- For Inter Variable: `js-dev__npm_add_package({ name: "@fontsource-variable/inter" })`
- For Roboto: `js-dev__npm_add_package({ name: "@fontsource/roboto" })`
- For Outfit Variable: `js-dev__npm_add_package({ name: "@fontsource-variable/outfit" })`
- For Poppins: `js-dev__npm_add_package({ name: "@fontsource/poppins" })`
- For Open Sans: `js-dev__npm_add_package({ name: "@fontsource/open-sans" })`
**Format**: `@fontsource/[font-name]` or `@fontsource-variable/[font-name]` (for variable fonts)
@@ -1097,7 +1018,7 @@ There is an important distinction between **writing new tests** and **running ex
### Running Tests (Executing the Test Suite)
**ALWAYS run the test script** after making any code changes. This is mandatory regardless of whether you wrote new tests or not.
- **You must run the test script** to validate your changes
- **You must run the test script** using `js-dev__run_script` tool with the "test" parameter
- **Your task is not complete** until the test script passes without errors
- **This applies to all changes** - bug fixes, new features, refactoring, or any code modifications
- **The test script includes** TypeScript compilation, ESLint checks, and existing test validation
@@ -1131,26 +1052,10 @@ describe('MyComponent', () => {
});
```
## Validating Your Changes
## Testing Your Changes
**CRITICAL**: After making any code changes, you must validate your work by running available validation tools.
**CRITICAL**: Whenever you are finished modifying code, you must run the **test** script using the **js-dev__run_script** tool.
**Your task is not considered finished until the code successfully type-checks and builds without errors.**
**Your task is not considered finished until this test passes without errors.**
### Validation Priority Order
Run available tools in this priority order:
1. **Type Checking** (Required): Ensure TypeScript compilation succeeds
2. **Building/Compilation** (Required): Verify the project builds successfully
3. **Linting** (Recommended): Check code style and catch potential issues
4. **Tests** (If Available): Run existing test suite
5. **Git Commit** (Required): Create a commit with your changes when finished
**Minimum Requirements:**
- Code must type-check without errors
- Code must build/compile successfully
- Fix any critical linting errors that would break functionality
- Create a git commit when your changes are complete
The validation ensures code quality and catches errors before deployment, regardless of the development environment.
**This requirement applies regardless of whether you wrote new tests or not.** The test script validates the entire codebase, including TypeScript compilation, ESLint rules, and existing test suite.
Symlink
+1
View File
@@ -0,0 +1 @@
AGENTS.md
Symlink
+1
View File
@@ -0,0 +1 @@
AGENTS.md
Symlink
+1
View File
@@ -0,0 +1 @@
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)
+8 -234
View File
@@ -1,238 +1,12 @@
# MKStack
**The Complete Framework for Building Nostr Clients with AI**
Template for building Nostr client application with React 18.x, TailwindCSS 3.x, Vite, shadcn/ui, and Nostrify.
MKStack is an AI-powered framework for building Nostr applications with React 18.x, TailwindCSS 3.x, Vite, shadcn/ui, and Nostrify. Build powerful Nostr applications with AI-first development - from social feeds to private messaging, MKStack provides everything you need to create decentralized apps on the Nostr protocol.
## Features
## 🚀 Quick Start
Build your Nostr app in 3 simple steps:
### 1. Install & Create
```bash
npm install -g @getstacks/stacks
stacks mkstack
```
### 2. Build with AI
```bash
stacks agent
# Tell Dork AI what you want: "Build a group chat application"
```
### 3. Deploy Instantly
```bash
npm run deploy
# ✅ App deployed to NostrDeploy.com!
```
## ✨ What Makes MKStack Special
- **🤖 AI-First Development**: Build complete Nostr apps with just one prompt using Dork AI agent
- **⚡ 8 Minutes Average**: From idea to deployed application in minutes, not months
- **🔗 50+ NIPs Supported**: Comprehensive Nostr protocol implementation
- **🎨 Beautiful UI**: 48+ shadcn/ui components with light/dark theme support
- **🔐 Built-in Security**: NIP-07 browser signing, NIP-44 encryption, event validation
- **💰 Payments Ready**: Lightning zaps (NIP-57), Cashu wallets (NIP-60), Wallet Connect (NIP-47)
- **📱 Production Ready**: TypeScript, testing, deployment, and responsive design included
## 🛠 Technology Stack
- **React 18.x**: Stable version with hooks, concurrent rendering, and improved performance
- **TailwindCSS 3.x**: Utility-first CSS framework for styling
- **Vite**: Fast build tool and development server
- **shadcn/ui**: 48+ unstyled, accessible UI components built with Radix UI
- **Nostrify**: Nostr protocol framework for Deno and web
- **React Router**: Client-side routing with BrowserRouter
- **TanStack Query**: Data fetching, caching, and state management
- **TypeScript**: Type-safe JavaScript development
## 🎯 Real-World Examples
### Built with One Prompt
Each of these applications was created with just a single prompt to Dork AI:
- **Group Chat Application**: `"Build me a group chat application"`
- [Live Demo](https://groupchat-74z9j26wq-mks-projects-1f1254c4.vercel.app/)
- **Decentralized Goodreads**: `"Build a decentralized goodreads alternative. Use OpenLibrary API for book data."`
- [Live Demo](https://bookstr123-87phkwjcy-mks-projects-1f1254c4.vercel.app/)
- **Chess Game**: `"Build a chess game with NIP 64"`
- [Live Demo](https://chess-l0d7ms7m3-mks-projects-1f1254c4.vercel.app/chess)
### Production Apps
Real Nostr applications built using MKStack:
- **[Chorus](https://chorus.community/)**: Facebook-style groups on Nostr with built-in eCash wallet
- **[Blobbi](https://www.blobbi.pet/)**: Digital pet companions that live forever on the decentralized web
- **[Treasures](https://treasures.to/)**: Decentralized geocaching adventure powered by Nostr
[Browse more apps made with MKStack →](https://nostrhub.io/apps/t/mkstack/)
## 🔧 Core Features
### Authentication & Users
- `LoginArea` component with account switching
- `useCurrentUser` hook for authentication state
- `useAuthor` hook for fetching user profiles
- NIP-07 browser signing support
- Multi-account management
### Nostr Protocol Support
- **Social Features**: User profiles (NIP-01), follow lists (NIP-02), reactions (NIP-25), reposts (NIP-18)
- **Messaging**: Private DMs (NIP-17), public chat (NIP-28), group chat (NIP-29), encryption (NIP-44)
- **Payments**: Lightning zaps (NIP-57), Cashu wallets (NIP-60), Nutzaps (NIP-61), Wallet Connect (NIP-47)
- **Content**: Long-form articles (NIP-23), file metadata (NIP-94), live events (NIP-53), calendars (NIP-52)
### Data Management
- `useNostr` hook for querying and publishing
- `useNostrPublish` hook with automatic client tagging
- Event validation and filtering
- Infinite scroll with TanStack Query
- Multi-relay support
### UI Components
- 48+ shadcn/ui components (buttons, forms, dialogs, etc.)
- `NoteContent` component for rich text rendering
- `EditProfileForm` for profile management
- `RelaySelector` for relay switching
- `CommentsSection` for threaded discussions
- Light/dark theme system
### Media & Files
- `useUploadFile` hook with Blossom server integration
- NIP-94 compatible file metadata
- Image and video support
- File attachment to events
### Advanced Features
- NIP-19 identifier routing (`npub1`, `note1`, `nevent1`, `naddr1`)
- Cryptographic operations (encryption/decryption)
- Lightning payments and zaps
- Real-time event subscriptions
- Responsive design with mobile support
## 🤖 AI Development with Dork
MKStack includes Dork, a built-in AI agent that understands your codebase and Nostr protocols:
### Supported AI Providers
Configure your AI provider with `stacks configure`:
- **OpenRouter** ([openrouter.ai](https://openrouter.ai/)): Enter your API key from settings
- **Routstr** ([routstr.com](https://www.routstr.com/)): Use Cashu tokens for payment
- **PayPerQ** ([ppq.ai](https://ppq.ai/)): OpenAI-compatible API
### How Dork Works
- **Context-Aware**: Understands your entire codebase and project structure
- **Nostr Expert**: Built-in knowledge of 50+ NIPs and best practices
- **Instant Implementation**: Makes changes directly to your code following React/TypeScript best practices
Example prompts:
```bash
"Add user profiles with avatars and bio"
"Implement NIP-17 private messaging"
"Add a dark mode toggle"
"Create a marketplace with NIP-15"
```
## 📁 Project Structure
```
src/
├── components/ # UI components
│ ├── ui/ # shadcn/ui components (48+ available)
│ ├── auth/ # Authentication components
│ └── comments/ # Comment system components
├── hooks/ # Custom React hooks
│ ├── useNostr # Core Nostr integration
│ ├── useAuthor # User profile data
│ ├── useCurrentUser # Authentication state
│ ├── useNostrPublish # Event publishing
│ ├── useUploadFile # File uploads
│ └── useZaps # Lightning payments
├── pages/ # Page components
├── lib/ # Utility functions
├── contexts/ # React context providers
└── test/ # Testing utilities
```
## 🎨 UI Components
MKStack includes 48+ shadcn/ui components:
**Layout**: Card, Separator, Sheet, Sidebar, ScrollArea, Resizable
**Navigation**: Breadcrumb, NavigationMenu, Menubar, Tabs, Pagination
**Forms**: Button, Input, Textarea, Select, Checkbox, RadioGroup, Switch, Slider
**Feedback**: Alert, AlertDialog, Toast, Progress, Skeleton
**Overlay**: Dialog, Popover, HoverCard, Tooltip, ContextMenu, DropdownMenu
**Data Display**: Table, Avatar, Badge, Calendar, Chart, Carousel
**And many more...
## 🔐 Security & Best Practices
- **Never use `any` type**: Always use proper TypeScript types
- **Event validation**: Filter events through validator functions for custom kinds
- **Efficient queries**: Minimize separate queries to avoid rate limiting
- **Proper error handling**: Graceful handling of invalid NIP-19 identifiers
- **Secure authentication**: Use signer interface, never request private keys directly
## 📱 Responsive Design
- Mobile-first approach with Tailwind breakpoints
- `useIsMobile` hook for responsive behavior
- Touch-friendly interactions
- Optimized for all screen sizes
## 🧪 Testing
- Vitest with jsdom environment
- React Testing Library with jest-dom matchers
- `TestApp` component provides all necessary context providers
- Mocked browser APIs (matchMedia, scrollTo, IntersectionObserver, ResizeObserver)
## 🚀 Deployment
Built-in deployment to NostrDeploy.com:
```bash
npm run deploy
```
Your app goes live instantly with:
- Automatic builds
- CDN distribution
- HTTPS support
- Custom domains available
## 📚 Documentation
For detailed documentation on building Nostr applications with MKStack:
- [Tutorial](https://soapbox.pub/blog/mkstack-tutorial)
- [Nostr Protocol Documentation](https://nostr.com)
- [shadcn/ui Components](https://ui.shadcn.com)
## 🤝 Contributing
MKStack is open source and welcomes contributions. The framework is designed to be:
- **Extensible**: Easy to add new NIPs and features
- **Maintainable**: Clean architecture with TypeScript
- **Testable**: Comprehensive testing setup included
- **Documented**: Clear patterns and examples
## 📄 License
Open source - build amazing Nostr applications and help grow the decentralized web!
---
**"Vibed with MKStack"** - [Learn more about MKStack](https://soapbox.pub/mkstack)
*Build your Nostr app in minutes, not months. Start with AI, deploy instantly.*
- **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
+5 -12
View File
@@ -48,9 +48,8 @@
"cmdk": "^1.0.0",
"date-fns": "^3.6.0",
"embla-carousel-react": "^8.3.0",
"idb": "^8.0.3",
"input-otp": "^1.2.4",
"lucide-react": "^0.462.0",
"lucide-react": "^0.542.0",
"nostr-tools": "^2.13.0",
"qrcode": "^1.5.4",
"react": "^18.3.1",
@@ -5487,12 +5486,6 @@
"node": ">=0.10.0"
}
},
"node_modules/idb": {
"version": "8.0.3",
"resolved": "https://registry.npmjs.org/idb/-/idb-8.0.3.tgz",
"integrity": "sha512-LtwtVyVYO5BqRvcsKuB2iUMnHwPVByPCXFXOpuU96IZPPoPN6xjOGxZQ74pgSVVLQWtUOYgyeL4GE98BY5D3wg==",
"license": "ISC"
},
"node_modules/ignore": {
"version": "5.3.2",
"resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz",
@@ -5865,12 +5858,12 @@
"license": "ISC"
},
"node_modules/lucide-react": {
"version": "0.462.0",
"resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-0.462.0.tgz",
"integrity": "sha512-NTL7EbAao9IFtuSivSZgrAh4fZd09Lr+6MTkqIxuHaH2nnYiYIzXPo06cOxHg9wKLdj6LL8TByG4qpePqwgx/g==",
"version": "0.542.0",
"resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-0.542.0.tgz",
"integrity": "sha512-w3hD8/SQB7+lzU2r4VdFyzzOzKnUjTZIF/MQJGSSvni7Llewni4vuViRppfRAa2guOsY5k4jZyxw/i9DQHv+dw==",
"license": "ISC",
"peerDependencies": {
"react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0-rc"
"react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0"
}
},
"node_modules/lz-string": {
+4 -5
View File
@@ -4,9 +4,9 @@
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "npm i --silent && vite",
"build": "npm i --silent && vite build -l error && cp dist/index.html dist/404.html && echo 'Project built successfully!'",
"test": "npm i --silent && tsc --noEmit && eslint && vitest run --reporter=dot --silent && vite build -l error && cp dist/index.html dist/404.html && echo 'All tests passed!'",
"dev": "npm i && vite",
"build": "npm i && vite build && cp dist/index.html dist/404.html",
"test": "npm i && tsc -p tsconfig.app.json --noEmit && eslint && vitest run && vite build",
"deploy": "npm run build && npx -y nostr-deploy-cli deploy --skip-setup"
},
"dependencies": {
@@ -50,9 +50,8 @@
"cmdk": "^1.0.0",
"date-fns": "^3.6.0",
"embla-carousel-react": "^8.3.0",
"idb": "^8.0.3",
"input-otp": "^1.2.4",
"lucide-react": "^0.462.0",
"lucide-react": "^0.542.0",
"nostr-tools": "^2.13.0",
"qrcode": "^1.5.4",
"react": "^18.3.1",
+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>
);
}
+2 -2
View File
@@ -2,11 +2,11 @@
// 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, CheckCircle, Upload, Globe } 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';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from "@/components/ui/dialog";
import { Card, CardContent } from '@/components/ui/card';
import { toast } from '@/hooks/useToast';
import { useLoginActions } from '@/hooks/useLoginActions';
+1 -1
View File
@@ -9,7 +9,7 @@ export const buttonVariants = cva(
destructive:
"bg-destructive text-destructive-foreground hover:bg-destructive/90",
outline:
"border border-input hover:bg-accent hover:text-accent-foreground",
"border border-input bg-background hover:bg-accent hover:text-accent-foreground",
secondary:
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
ghost: "hover:bg-accent hover:text-accent-foreground",
+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,
};
}
+12 -12
View File
@@ -1,19 +1,19 @@
import { useEffect, useState } from "react"
import * as React from "react"
const MOBILE_BREAKPOINT = 768;
const MOBILE_BREAKPOINT = 768
export function useIsMobile(): boolean {
const [isMobile, setIsMobile] = useState(window.innerWidth < MOBILE_BREAKPOINT);
export function useIsMobile() {
const [isMobile, setIsMobile] = React.useState<boolean | undefined>(undefined)
useEffect(() => {
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`);
React.useEffect(() => {
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`)
const onChange = () => {
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
}
mql.addEventListener("change", onChange);
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
return () => mql.removeEventListener("change", onChange);
}, []);
mql.addEventListener("change", onChange)
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
return () => mql.removeEventListener("change", onChange)
}, [])
return !!isMobile;
return !!isMobile
}
-193
View File
@@ -1,193 +0,0 @@
import { useMutation } from '@tanstack/react-query';
import { useNostrPublish } from '@/hooks/useNostrPublish';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useToast } from '@/hooks/useToast';
interface BaseSendDMParams {
recipientPubkey: string;
content: string;
attachments?: Array<{
url: string;
mimeType: string;
size: number;
name: string;
tags: string[][];
}>;
}
/**
* Hook for sending direct messages using NIP-04 and NIP-17 protocols
*
* @example
* ```tsx
* const { sendNIP4Message, sendNIP17Message } = useSendDM();
*
* // Send NIP-04 message
* await sendNIP4Message.mutateAsync({
* recipientPubkey: 'hex-pubkey',
* content: 'Hello!'
* });
*
* // Send NIP-17 message (more secure, uses NIP-44 + gift wrapping)
* await sendNIP17Message.mutateAsync({
* recipientPubkey: 'hex-pubkey',
* content: 'Hello securely!'
* });
* ```
*/
export function useSendDM() {
const { mutateAsync: createEvent } = useNostrPublish();
const { user } = useCurrentUser();
const { toast } = useToast();
// Helper function to prepare content with attachments
const prepareMessageContent = (content: string, attachments: BaseSendDMParams['attachments'] = []) => {
if (attachments.length === 0) return content;
const fileUrls = attachments.map(file => file.url).join('\n');
return content ? `${content}\n\n${fileUrls}` : fileUrls;
};
// Helper function to create imeta tags for attachments (NIP-92)
const createImetaTags = (attachments: BaseSendDMParams['attachments'] = []) => {
return attachments.map(file => {
const imetaTag = ["imeta"];
imetaTag.push(`url ${file.url}`);
if (file.mimeType) imetaTag.push(`m ${file.mimeType}`);
if (file.size) imetaTag.push(`size ${file.size}`);
if (file.name) imetaTag.push(`alt ${file.name}`);
file.tags.forEach(tag => {
if (tag[0] === 'x') imetaTag.push(`x ${tag[1]}`);
if (tag[0] === 'ox') imetaTag.push(`ox ${tag[1]}`);
});
return imetaTag;
});
};
/**
* Send a NIP-04 encrypted direct message
* Uses legacy NIP-04 encryption (nip04.encrypt)
*/
const sendNIP4Message = useMutation({
mutationFn: async ({ recipientPubkey, content, attachments = [] }: BaseSendDMParams) => {
if (!user?.signer?.nip04) {
console.error('[SendDM] NIP-04 encryption not available');
throw new Error('NIP-04 encryption not available');
}
console.log('[SendDM] Sending NIP-04 message');
const messageContent = prepareMessageContent(content, attachments);
const encryptedContent = await user.signer.nip04.encrypt(recipientPubkey, messageContent);
const tags = [
["p", recipientPubkey],
...createImetaTags(attachments)
];
const event = await createEvent({
kind: 4, // NIP-04 encrypted DM
content: encryptedContent,
tags,
});
console.log('[SendDM] Created NIP-04 message:', event);
return event;
},
onError: (error) => {
console.error('Failed to send NIP-04 DM:', error);
toast({
title: "Error",
description: "Failed to send NIP-04 message. Please try again.",
variant: "destructive",
});
},
});
/**
* Send a NIP-17 encrypted direct message (Gift Wrapped)
* Uses NIP-44 encryption with gift wrapping (NIP-59) for enhanced privacy
*
* Creates:
* 1. Kind 14 Private DM event (signed by sender)
* 2. Kind 13 Seal events (encrypted to recipient and sender)
* 3. Kind 1059 Gift Wrap events (for recipient and sender to find messages)
*/
const sendNIP17Message = useMutation({
mutationFn: async ({ recipientPubkey, content, attachments = [] }: BaseSendDMParams) => {
if (!user?.signer?.nip44) {
console.error('[SendDM] NIP-44 encryption not available for NIP-17');
throw new Error('NIP-44 encryption not available for NIP-17');
}
console.log('[SendDM] Sending NIP-17 Gift Wrap message');
const messageContent = prepareMessageContent(content, attachments);
// Step 1: Create and sign the Kind 14 Private DM event
const privateDMTags = [
["p", recipientPubkey],
...createImetaTags(attachments)
];
const privateDM = await user.signer.signEvent({
kind: 14,
content: messageContent,
tags: privateDMTags,
created_at: Math.floor(Date.now() / 1000),
});
// Step 2: Create TWO Kind 13 Seal events - one for recipient, one for sender
// Seal for recipient (encrypted to them)
const recipientSeal = await user.signer.signEvent({
kind: 13,
content: await user.signer.nip44.encrypt(recipientPubkey, JSON.stringify(privateDM)),
tags: [], // Seal events typically have no tags
created_at: Math.floor(Date.now() / 1000),
});
// Seal for sender (encrypted to us)
const senderSeal = await user.signer.signEvent({
kind: 13,
content: await user.signer.nip44.encrypt(user.pubkey, JSON.stringify(privateDM)),
tags: [], // Seal events typically have no tags
created_at: Math.floor(Date.now() / 1000),
});
// Step 3: Create TWO Kind 1059 Gift Wrap events
// One for the recipient, one for myself (so I can see sent messages)
// Gift Wrap for recipient - they should be able to find it via their pubkey in p tag
const recipientGiftWrap = await createEvent({
kind: 1059, // Gift Wrap
content: await user.signer.nip44.encrypt(recipientPubkey, JSON.stringify(recipientSeal)),
tags: [["p", recipientPubkey]], // Recipient can find this via their pubkey
});
// Gift Wrap for myself - I should be able to find it via my pubkey in p tag
const myGiftWrap = await createEvent({
kind: 1059, // Gift Wrap
content: await user.signer.nip44.encrypt(user.pubkey, JSON.stringify(senderSeal)),
tags: [["p", user.pubkey]], // I can find this via my pubkey
});
return { recipientGiftWrap, myGiftWrap };
},
onError: (error) => {
console.error('Failed to send NIP-17 DM:', error);
toast({
title: "Error",
description: "Failed to send NIP-17 message. Please try again.",
variant: "destructive",
});
},
});
return {
sendNIP4Message,
sendNIP17Message,
};
}
-56
View File
@@ -1,56 +0,0 @@
import { MESSAGE_PROTOCOL, type MessageProtocol } from '@/types/dm';
/**
* Helper function to determine message protocol from event kind
*/
export function getMessageProtocol(kind: number): MessageProtocol {
switch (kind) {
case 4: return MESSAGE_PROTOCOL.NIP04;
case 1059: return MESSAGE_PROTOCOL.NIP17; // Gift Wrap
case 14: return MESSAGE_PROTOCOL.NIP17; // Private DM (decrypted NIP-17)
default: return MESSAGE_PROTOCOL.UNKNOWN;
}
}
/**
* Protocol indicator configuration for UI display
*/
export const PROTOCOL_CONFIG = {
[MESSAGE_PROTOCOL.NIP04]: {
color: 'bg-orange-500',
textColor: 'text-orange-600 dark:text-orange-400',
label: 'NIP-04',
title: 'NIP-04 encrypted message'
},
[MESSAGE_PROTOCOL.NIP17]: {
color: 'bg-purple-500',
textColor: 'text-purple-600 dark:text-purple-400',
label: 'NIP-17',
title: 'NIP-44/NIP-17 encrypted message'
},
[MESSAGE_PROTOCOL.UNKNOWN]: {
color: 'bg-gray-400',
textColor: 'text-gray-600 dark:text-gray-400',
label: 'Unknown',
title: 'Unknown message type'
}
} as const;
/**
* Constants for consistent naming across the app
*/
export const PROTOCOL_CONSTANTS = {
// localStorage keys
NIP17_ENABLED_KEY: 'enableNIP17',
// Logger prefixes
NIP4_LOG_PREFIX: 'DMS: [NIP4]',
NIP17_LOG_PREFIX: 'DMS: [NIP17]',
DMCHAT_LOG_PREFIX: 'DMS: [DMCHAT]',
DIRECT_MESSAGES_LOG_PREFIX: 'DMS: [DirectMessages]',
} as const;
/**
* Message pagination constants
*/
export const MESSAGES_PER_PAGE = 25;
-61
View File
@@ -1,61 +0,0 @@
import type { NostrEvent } from '@nostrify/nostrify';
import type { DecryptedMessage, DMConversation } from '@/types/dm';
/**
* Shared validation function for DM events
* Validates both NIP-04 (kind 4) and NIP-17 (kind 1059) encrypted DMs
*/
export function validateDMEvent(event: NostrEvent): boolean {
// Accept both NIP-04 (kind 4) and NIP-17 (kind 1059) encrypted DMs
if (![4, 1059].includes(event.kind)) return false;
// Must have a 'p' tag for the recipient
const hasP = event.tags.some(([name]) => name === 'p');
if (!hasP) return false;
return true;
}
/**
* Extract the recipient pubkey from a DM event
*/
export function getRecipientPubkey(event: NostrEvent): string | null {
const pTag = event.tags.find(([name]) => name === 'p');
return pTag ? pTag[1] : null;
}
/**
* Determine if a message is from the current user
*/
export function isMessageFromUser(message: DecryptedMessage, userPubkey: string): boolean {
return message.pubkey === userPubkey;
}
/**
* Sort conversations by last activity (most recent first)
*/
export function sortConversationsByActivity(conversations: DMConversation[]): DMConversation[] {
return [...conversations].sort((a, b) => b.lastMessageTime - a.lastMessageTime);
}
/**
* Filter conversations by search query
* Searches in decrypted message content and participant info
*/
export function filterConversationsByQuery(
conversations: DMConversation[],
query: string
): DMConversation[] {
if (!query.trim()) return conversations;
const lowerQuery = query.toLowerCase();
return conversations.filter(conv => {
// Search in pubkey
if (conv.pubkey.toLowerCase().includes(lowerQuery)) return true;
// Search in last message content
if (conv.lastMessage?.decryptedContent?.toLowerCase().includes(lowerQuery)) return true;
return false;
});
}
-167
View File
@@ -1,167 +0,0 @@
import { openDB, IDBPDatabase } from 'idb';
import type { NostrEvent } from '@nostrify/nostrify';
// Match the in-memory structure exactly
interface StoredParticipant {
messages: NostrEvent[]; // Store only basic NostrEvent in IndexedDB
lastActivity: number;
hasNIP4: boolean;
hasNIP17: boolean;
}
// Store structure: Map<participantPubkey, StoredParticipant>
interface MessageStore {
participants: Record<string, StoredParticipant>;
lastSync: {
nip4: number | null;
nip17: number | null;
};
}
// IndexedDB configuration
const DB_NAME = 'nostr-messages';
const DB_VERSION = 1;
/**
* Initialize IndexedDB for a specific user
* Creates a user-specific store if it doesn't exist
*/
async function initDB(userNpub: string): Promise<IDBPDatabase> {
const storeName = `messages-${userNpub}`;
return openDB(DB_NAME, DB_VERSION, {
upgrade(db, _oldVersion, _newVersion) {
// Create store for this user if it doesn't exist
if (!db.objectStoreNames.contains(storeName)) {
db.createObjectStore(storeName, { keyPath: 'id' });
console.log(`DMS: Created store ${storeName} in IndexedDB`);
}
},
blocked() {
console.warn('IndexedDB upgrade blocked - another tab may have the database open');
},
blocking() {
console.warn('IndexedDB upgrade blocking - this tab is preventing another tab from upgrading');
},
});
}
/**
* Read all messages from IndexedDB for a specific user
*
* @example
* ```ts
* const messageStore = await readMessagesFromDB('npub1...');
* if (messageStore) {
* console.log('Loaded messages:', messageStore.participants);
* }
* ```
*/
export async function readMessagesFromDB(userNpub: string): Promise<MessageStore | null> {
try {
const db = await initDB(userNpub);
const storeName = `messages-${userNpub}`;
// Check if the store exists before trying to read from it
if (!db.objectStoreNames.contains(storeName)) {
console.log(`Store ${storeName} does not exist yet for user ${userNpub.slice(0, 8)}...`);
return null;
}
// Read the entire store as one object
const storeData = await db.get(storeName, 'messageStore');
if (storeData) {
console.log(`Read message store from IndexedDB for user ${userNpub.slice(0, 8)}...`);
return storeData as MessageStore;
} else {
console.log(`DMS: No message store found in IndexedDB for user ${userNpub.slice(0, 8)}...`);
return null;
}
} catch (error) {
console.error('Error reading messages from IndexedDB:', error);
return null;
}
}
/**
* Write messages to IndexedDB for a specific user
*
* @example
* ```ts
* await writeMessagesToDB('npub1...', {
* participants: {
* 'hex-pubkey': {
* messages: [...],
* lastActivity: Date.now(),
* hasNIP4: true,
* hasNIP17: false
* }
* },
* lastSync: { nip4: Date.now(), nip17: null }
* });
* ```
*/
export async function writeMessagesToDB(userNpub: string, messageStore: MessageStore): Promise<void> {
try {
const db = await initDB(userNpub);
const storeName = `messages-${userNpub}`;
// Check if the store exists before trying to write to it
if (!db.objectStoreNames.contains(storeName)) {
console.log(`Store ${storeName} does not exist yet for user ${userNpub.slice(0, 8)}..., creating it`);
// Force a database upgrade to create the store
await db.close();
const newDb = await openDB(DB_NAME, DB_VERSION + 1, {
upgrade(db, _oldVersion, _newVersion) {
if (!db.objectStoreNames.contains(storeName)) {
db.createObjectStore(storeName, { keyPath: 'id' });
console.log(`DMS: Created store ${storeName} in IndexedDB during write`);
}
},
});
await newDb.put(storeName, { id: 'messageStore', ...messageStore });
await newDb.close();
} else {
// Store the entire message store as one object
await db.put(storeName, { id: 'messageStore', ...messageStore });
}
console.log(`Wrote message store to IndexedDB for user ${userNpub.slice(0, 8)}... (${Object.keys(messageStore.participants).length} participants)`);
} catch (error) {
console.error('Error writing messages to IndexedDB:', error);
throw error;
}
}
/**
* Clear all messages from IndexedDB for a specific user
*
* @example
* ```ts
* await clearMessagesFromDB('npub1...');
* ```
*/
export async function clearMessagesFromDB(userNpub: string): Promise<void> {
try {
const db = await initDB(userNpub);
const storeName = `messages-${userNpub}`;
if (db.objectStoreNames.contains(storeName)) {
// Clear the entire store
const tx = db.transaction(storeName, 'readwrite');
const store = tx.objectStore(storeName);
await store.clear();
await tx.done;
console.log(`DMS: Cleared message store from IndexedDB for user ${userNpub.slice(0, 8)}...`);
} else {
console.log(`DMS: Store ${storeName} does not exist for user ${userNpub.slice(0, 8)}..., nothing to clear`);
}
await db.close();
} catch (error) {
console.error('DMS: Error clearing messages from IndexedDB:', error);
throw error;
}
}
+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>
);
}
-59
View File
@@ -1,59 +0,0 @@
import type { NostrEvent } from '@nostrify/nostrify';
/**
* DM Tab Types - for organizing conversations
*/
export type DMTabType = 'known' | 'newRequests';
/**
* Message Protocol Types
*/
export const MESSAGE_PROTOCOL = {
NIP04: 'NIP04',
NIP17: 'NIP17',
UNKNOWN: 'UNKNOWN'
} as const;
export type MessageProtocol = typeof MESSAGE_PROTOCOL[keyof typeof MESSAGE_PROTOCOL];
/**
* Decrypted message with additional metadata
*/
export interface DecryptedMessage extends NostrEvent {
decryptedContent?: string;
error?: string;
isSending?: boolean;
clientFirstSeen?: number;
}
/**
* DM Conversation structure
*/
export interface DMConversation {
id: string; // The other person's pubkey
pubkey: string;
lastMessage?: DecryptedMessage;
lastMessageTime: number;
unreadCount: number;
// Conversation categorization
isKnown?: boolean; // User has sent at least one message to this person
isRequest?: boolean; // Other person has sent messages, but user hasn't replied
// Reply status tracking
lastMessageFromUser?: boolean; // True if user sent the last message, false if other person did
}
/**
* Message sending parameters
*/
export interface SendMessageParams {
recipientPubkey: string;
content: string;
protocol?: MessageProtocol; // Optional - defaults to NIP-04
attachments?: Array<{
url: string;
mimeType: string;
size: number;
name: string;
tags: string[][];
}>;
}
+31
View File
@@ -0,0 +1,31 @@
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"isolatedModules": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"strict": false,
"strictNullChecks": true,
"noUnusedLocals": false,
"noUnusedParameters": false,
"noImplicitAny": false,
"noFallthroughCasesInSwitch": false,
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
}
},
"include": ["src"]
}
+13 -25
View File
@@ -1,31 +1,19 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
],
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"isolatedModules": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"strict": false,
"strictNullChecks": true,
"noUnusedLocals": false,
"noUnusedParameters": false,
"noImplicitAny": false,
"noFallthroughCasesInSwitch": false,
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
}
},
"include": ["src"]
},
"noImplicitAny": false,
"noUnusedParameters": false,
"skipLibCheck": true,
"allowJs": true,
"noUnusedLocals": false,
"strictNullChecks": true
}
}
+22
View File
@@ -0,0 +1,22 @@
{
"compilerOptions": {
"target": "ES2022",
"lib": ["ES2023"],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"isolatedModules": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"strict": true,
"noUnusedLocals": false,
"noUnusedParameters": false,
"noFallthroughCasesInSwitch": true
},
"include": ["vite.config.ts"]
}