From c0dca78709598c8024308de754ffc07899a1cd01 Mon Sep 17 00:00:00 2001 From: Chad Curtis Date: Tue, 2 Sep 2025 00:09:46 +0000 Subject: [PATCH] Admin Dashboard init --- .env.example | 7 + ADMIN_DASHBOARD.md | 170 ++++++ NIP.md | 179 ++++++ README.md | 11 +- package-lock.json | 10 +- package.json | 2 +- src/AppRouter.tsx | 3 + src/components/AdminDashboardLink.tsx | 41 ++ src/hooks/useAdminStorage.ts | 237 ++++++++ src/pages/AdminDashboard.tsx | 825 ++++++++++++++++++++++++++ 10 files changed, 1478 insertions(+), 7 deletions(-) create mode 100644 .env.example create mode 100644 ADMIN_DASHBOARD.md create mode 100644 NIP.md create mode 100644 src/components/AdminDashboardLink.tsx create mode 100644 src/hooks/useAdminStorage.ts create mode 100644 src/pages/AdminDashboard.tsx diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..3576fc1 --- /dev/null +++ b/.env.example @@ -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 \ No newline at end of file diff --git a/ADMIN_DASHBOARD.md b/ADMIN_DASHBOARD.md new file mode 100644 index 0000000..3f96b75 --- /dev/null +++ b/ADMIN_DASHBOARD.md @@ -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 ( +
+

My App

+ +
+ ); +} +``` + +### 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 \ No newline at end of file diff --git a/NIP.md b/NIP.md new file mode 100644 index 0000000..231f46b --- /dev/null +++ b/NIP.md @@ -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": "", + "tags": [ + ["d", "admin-config"], + ["alt", "Site administration configuration and policies"] + ], + "created_at": , + "pubkey": "" +} +``` + +### Content Schema + +The `content` field contains a JSON object with the following structure: + +```json +{ + "hiddenEvents": ["", "..."], + "allowList": ["", "..."], + "denyList": ["", "..."], + "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) \ No newline at end of file diff --git a/README.md b/README.md index 24402b9..1980be7 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,12 @@ # MKStack -Template for building Nostr client application with React 18.x, TailwindCSS 3.x, Vite, shadcn/ui, and Nostrify. \ No newline at end of file +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 \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index 3e7b594..2a8b96c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -49,7 +49,7 @@ "date-fns": "^3.6.0", "embla-carousel-react": "^8.3.0", "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", @@ -5858,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": { diff --git a/package.json b/package.json index 98f7eb5..ae25d81 100644 --- a/package.json +++ b/package.json @@ -51,7 +51,7 @@ "date-fns": "^3.6.0", "embla-carousel-react": "^8.3.0", "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", diff --git a/src/AppRouter.tsx b/src/AppRouter.tsx index 2db53ee..472f35b 100644 --- a/src/AppRouter.tsx +++ b/src/AppRouter.tsx @@ -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() { } /> + {/* Admin dashboard route - must come before NIP-19 route */} + } /> {/* NIP-19 route for npub1, note1, naddr1, nevent1, nprofile1 */} } /> {/* ADD ALL CUSTOM ROUTES ABOVE THE CATCH-ALL "*" ROUTE */} diff --git a/src/components/AdminDashboardLink.tsx b/src/components/AdminDashboardLink.tsx new file mode 100644 index 0000000..113bfe8 --- /dev/null +++ b/src/components/AdminDashboardLink.tsx @@ -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 ( + + ); +} \ No newline at end of file diff --git a/src/hooks/useAdminStorage.ts b/src/hooks/useAdminStorage.ts new file mode 100644 index 0000000..dd5d433 --- /dev/null +++ b/src/hooks/useAdminStorage.ts @@ -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) => { + 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, + }; +} \ No newline at end of file diff --git a/src/pages/AdminDashboard.tsx b/src/pages/AdminDashboard.tsx new file mode 100644 index 0000000..073ccd0 --- /dev/null +++ b/src/pages/AdminDashboard.tsx @@ -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 ; + } + + // Check if current user is the site admin + const isAuthorized = user?.pubkey === adminPubkey; + + if (!isAuthorized) { + return ( +
+ + + + + Site Admin Access Required + + + You need to be logged in as the site administrator to access this admin panel. + + + + {adminAuthor.data?.metadata && ( +
+ + + + {(adminAuthor.data.metadata.name || genUserName(adminPubkey)).slice(0, 2).toUpperCase()} + + +
+

+ {adminAuthor.data.metadata.display_name || adminAuthor.data.metadata.name || genUserName(adminPubkey)} +

+

+ Site Administrator +

+
+
+ )} + + + + + Only the site administrator can access content moderation and site management features. + + + + +
+
+
+ ); + } + + return ( +
+
+

+ + Site Administration +

+

+ Manage content moderation, user access controls, and site settings +

+
+ + + + Content Moderation + User Management + Blocked Words + Site Analytics + Site Settings + + + + + + + + + + + + + + + + + + + + + + +
+ ); +} + +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 ( +
+ + + + + Recent Content Review + + + Review and moderate recent content posted to the site + + + + {recentContent.isLoading ? ( +
+ {Array.from({ length: 5 }).map((_, i) => ( +
+ +
+ + + +
+ +
+ ))} +
+ ) : recentContent.data?.length ? ( +
+ {recentContent.data.map((event) => { + const isHidden = adminData.hiddenEvents.includes(event.id); + return ( +
+ +
+
+ + + {event.kind === 1 ? 'Note' : 'Article'} + + + {new Date(event.created_at * 1000).toLocaleString()} + +
+

+ {event.kind === 30023 + ? event.tags.find(([tag]) => tag === 'title')?.[1] || 'Untitled Article' + : event.content + } +

+
+
+ {isHidden ? ( + + ) : ( + + )} +
+
+ ); + })} +
+ ) : ( +

No recent content found

+ )} +
+
+
+ ); +} + +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 ( +
+ {/* Add User Form */} + + + + + Add User to Lists + + + Add users to allow list or deny list by their npub + + + +
+ setNewNpub(e.target.value)} + className="flex-1" + /> + + +
+
+
+ +
+ {/* Allow List */} + + + + + Allow List ({adminData.allowList.length}) + + + Users explicitly allowed to post content + + + + {adminData.allowList.length > 0 ? ( +
+ {adminData.allowList.map((pubkey) => ( + removeFromAllowList(pubkey)} + variant="allow" + disabled={isSaving} + /> + ))} +
+ ) : ( +

No users in allow list

+ )} +
+
+ + {/* Deny List */} + + + + + Deny List ({adminData.denyList.length}) + + + Users blocked from posting content + + + + {adminData.denyList.length > 0 ? ( +
+ {adminData.denyList.map((pubkey) => ( + removeFromDenyList(pubkey)} + variant="deny" + disabled={isSaving} + /> + ))} +
+ ) : ( +

No users in deny list

+ )} +
+
+
+
+ ); +} + +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 ( +
+ + + + + Content Filtering Settings + + + Configure automatic content filtering options + + + +
+ updateModerationSettings({ caseSensitive: checked })} + disabled={isSaving} + /> + +
+ +
+ updateModerationSettings({ wholeWordsOnly: checked })} + disabled={isSaving} + /> + +
+
+
+ + + + Add Blocked Word + + Add words or phrases to automatically filter from content + + + +
+ setNewWord(e.target.value)} + onKeyPress={handleKeyPress} + className="flex-1" + /> + +
+
+
+ + + + Blocked Words ({adminData.blockedWords.length}) + + Currently blocked words and phrases + + + + {adminData.blockedWords.length > 0 ? ( +
+ {adminData.blockedWords.map((word) => ( +
+ {word} + +
+ ))} +
+ ) : ( +

No blocked words configured

+ )} +
+
+
+ ); +} + +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 ( +
+
+ + + Total Content + + +
{siteStats.data?.totalEvents || 0}
+

Recent events

+
+
+ + + + Active Users + + +
{siteStats.data?.uniqueAuthors || 0}
+

Unique authors

+
+
+ + + + Last 24h + + +
{siteStats.data?.last24h || 0}
+

New posts

+
+
+ + + + Last 7 days + + +
{siteStats.data?.last7d || 0}
+

New posts

+
+
+
+ + + + Content Breakdown + + Distribution of content types on your site + + + + {siteStats.isLoading ? ( +
+ + +
+ ) : ( +
+
+ Notes + {siteStats.data?.notes || 0} +
+
+ Articles + {siteStats.data?.articles || 0} +
+
+ )} +
+
+
+ ); +} + +function SiteSettings() { + const { data: adminData, updateSiteSettings, updateModerationSettings, isSaving } = useAdminStorage(); + + return ( +
+ + + Site Information + + Basic information about your site + + + +
+ + updateSiteSettings({ siteName: e.target.value })} + placeholder="My Nostr Site" + disabled={isSaving} + /> +
+ +
+ +