alishasajjad/ModPulse-AI

GitHub: alishasajjad/ModPulse-AI

Stars: 0 | Forks: 0

# ModPulse AI **AI-powered Reddit moderation operating system** — real-time threat detection, intelligent moderation pipelines, moderator copilot, and portfolio-ready SaaS dashboards in one platform. ![ModPulse AI](https://img.shields.io/badge/ModPulse-AI%20Moderation-FF4500?style=for-the-badge) ![Node](https://img.shields.io/badge/Node.js-20+-339933?style=flat-square&logo=node.js) ![React](https://img.shields.io/badge/React-19-61DAFB?style=flat-square&logo=react) ![Express](https://img.shields.io/badge/Express-5-000000?style=flat-square&logo=express) ![MongoDB](https://img.shields.io/badge/MongoDB-Atlas-47A248?style=flat-square&logo=mongodb) ![Socket.io](https://img.shields.io/badge/Socket.io-4-010101?style=flat-square&logo=socket.io) ![License](https://img.shields.io/badge/License-MIT-blue?style=flat-square) ## Introduction **ModPulse AI** is a full-stack moderation control plane built for Reddit communities, final-year projects (FYP), recruiter portfolios, and SaaS-style demos. It combines AI-assisted content scoring, live operational dashboards, and moderator workflows in a single glass-morphism UI. The platform runs as a **React SPA** (Vite) talking to a **Node.js / Express API** on **port 5000**, with **MongoDB** persistence and **Socket.io** for real-time alerts, raid simulation, analytics refresh, and lockdown broadcasts. ## Key features | Area | Capability | |------|------------| | AI moderation | Hugging Face Toxic-BERT scoring, explanations, confidence, heuristic fallback | | Real-time ops | Socket.io live alerts, metrics, raid ticks, lockdown banners | | Threat detection | Raids, spam clusters, investigations, emergency lockdown | | Raid simulator | Coordinated toxic attack simulation with live threat levels | | Reddit sandbox | Fake subreddits, users, posts, live AI analysis | | Moderator copilot | Queue, recommendations, natural-language command chat | | Appeals | Submit, AI re-review, moderator approve/reject | | Analytics | Heatmaps, trends, accuracy dashboard, exports | | Auth & RBAC | JWT + refresh tokens, roles from viewer → super_admin | | Theme | Dark/light toggle with `modpulse-theme` persistence | | Demo mode | Seed data + simulated traffic for presentations | | DevOps | Docker Compose, CI-ready tests, production deploy guides | ### Features checklist - [x] JWT authentication with refresh token rotation - [x] Role-based access control (RBAC) - [x] AI comment analysis with explanation panels - [x] Real-time Socket.io dashboards - [x] AI raid simulator (start / stop / reset) - [x] Fake Reddit sandbox environment - [x] Moderator copilot + NL command chat (`/api/os/copilot/chat`) - [x] AI appeal system with re-analysis - [x] Emergency lockdown mode - [x] User reputation & high-risk scoring - [x] Threat timeline replay - [x] AI moderation accuracy metrics - [x] Live toxic activity heatmaps - [x] Dark / light theme (no flash on load) - [x] Reddit OAuth subreddit connection - [x] Devvit webhook integration - [x] Docker Compose local stack - [x] Optional sound alerts for critical threats ## Platform modules ### SaaS moderation platform Multi-tenant-style layout with protected routes (`/dashboard`, `/ai-moderation`, `/threat-detection`, etc.), command palette (`Ctrl+K`), notification center, audit logging, and role-gated navigation. ### AI moderation pipeline 1. Content enters via API, sandbox, Reddit sync, or Devvit webhooks. 2. `aiModerationService` calls **Hugging Face** (`unitary/toxic-bert` by default). 3. On failure or timeout, **heuristic analysis** runs locally (no external LLM required). 4. Results persist to `ModerationLog` with risk score, recommended action, and explanation fields. 5. High-risk items emit Socket.io alerts and copilot queue updates. ### Real-time threat detection Monitors velocity, coordinated spam, abuse patterns, and raid indicators. Moderators can investigate users, resolve raids, adjust severity, and trigger lockdown simulations with full audit trails. ### AI raid simulator **Threat Detection → AI Raid Simulator** generates coordinated toxic bursts, updates threat level in real time, persists `RaidSimulation` / `RaidDetectionLog` records, and emits `raid:*` socket events for live charts and toasts. ### Reddit sandbox **Reddit Sandbox** (`/reddit-sandbox`) provides a demo environment: create subreddits, users, posts, and comments; each comment runs through the same AI pipeline with `source: sandbox`. ### Moderator copilot **Copilot** page shows prioritized queue, recommendations, and workload. **Natural-language chat** accepts commands such as: - `show high risk users` - `start raid simulation` - `lock subreddit` - `show appeals` - `show recent raids` Commands are parsed deterministically (no paid LLM required) via `POST /api/os/copilot/chat`. ### Appeals system Users/moderators submit appeals; the pipeline re-runs AI analysis. Moderators approve or reject with audit logging and `appeal:*` socket events. ### Analytics & heatmaps ### Live Socket.io architecture ### Authentication & RBAC | Role | Typical access | |------|----------------| | `viewer` | Dashboard, notifications (read-focused) | | `analyst` | Threat detection, community intelligence, analytics | | `moderator` | AI moderation, copilot, alerts, sandbox, settings | | `super_admin` | Full platform + demo traffic controls | ## Tech stack | Layer | Technologies | |-------|----------------| | **Frontend** | React 19, Vite 8, React Router 7, Tailwind CSS 4, Framer Motion, Recharts, Lucide | | **Backend** | Node.js 20+, Express 5, Mongoose 9, Socket.io 4 | | **AI** | Hugging Face Inference API (`unitary/toxic-bert`), local heuristics | | **Database** | MongoDB 6+ / MongoDB Atlas | | **Auth** | JWT access + refresh, bcrypt, cookie-parser | | **Cache (optional)** | Redis (Docker Compose includes Redis; used when configured) | | **DevOps** | Docker, Nginx (frontend image), GitHub Actions CI | ## Architecture flowchart TB subgraph Client["Browser"] SPA["React SPA :5173"] SOC["Socket.io Client"] end subgraph API["Backend :5000"] EXP["Express 5 REST"] SIO["Socket.io Server"] AI["HF Toxic-BERT + Heuristics"] OS["ModPulse OS /api/os"] end subgraph Data["Data Layer"] MONGO[(MongoDB)] REDIS[(Redis optional)] end subgraph External["External"] HF["Hugging Face API"] REDDIT["Reddit OAuth"] end SPA --> EXP SOC --> SIO EXP --> MONGO EXP --> AI AI --> HF OS --> MONGO SIO --> MONGO EXP --> REDIS EXP --> REDDIT See [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) for request flows, security, and service boundaries. ## Project structure ModPulse_AI/ ├── backend/ │ ├── src/ │ │ ├── config/ # env, database, socket │ │ ├── controllers/ │ │ ├── middleware/ # auth, RBAC, security, validation │ │ ├── models/ # Mongoose schemas │ │ ├── routes/ # REST routers (+ osRoutes.js) │ │ ├── services/ # business logic, AI providers, realtime │ │ └── utils/ │ ├── scripts/ # reddit-mock, utilities │ ├── Dockerfile │ └── .env.example ├── frontend/ │ ├── src/ │ │ ├── components/ # UI, dashboard, threat, os/ │ │ ├── context/ # Auth, Theme, ModPulseProvider │ │ ├── pages/ │ │ ├── routes/ │ │ └── services/ # api, socket, osApi │ ├── Dockerfile │ └── .env.example ├── docs/ # Detailed documentation ├── devvit/ # Reddit Devvit app ├── docker-compose.yml ├── docker-compose.prod.yml └── README.md ## Quick start ### Prerequisites - **Node.js 20+** and npm - **MongoDB** (local or [MongoDB Atlas](https://www.mongodb.com/cloud/atlas)) - Optional: **Hugging Face API key** for live Toxic-BERT scoring (heuristics work offline) ### Installation git clone https://github.com/your-username/ModPulse_AI.git cd ModPulse_AI cd backend && npm install cd ../frontend && npm install ### Configure environment cp backend/.env.example backend/.env cp frontend/.env.example frontend/.env Edit `backend/.env` — minimum: `MONGODB_URI`, `JWT_ACCESS_SECRET`, `JWT_REFRESH_SECRET`, `CORS_ORIGIN=http://localhost:5173`. See [docs/ENVIRONMENT.md](docs/ENVIRONMENT.md) for the full variable reference. ### Run development servers **Terminal 1 — API (port 5000):** cd backend npm run dev **Terminal 2 — Frontend (port 5173):** cd frontend npm run dev Open **http://localhost:5173** → landing page. Sign in to access the app shell at **/dashboard**. Verify API: `GET http://localhost:5000/health` ## Environment setup | File | Purpose | |------|---------| | `backend/.env` | API secrets, MongoDB, JWT, Reddit OAuth, Hugging Face, demo flags | | `frontend/.env` | `VITE_API_URL=http://localhost:5000` | **MongoDB Atlas (recommended for demos):** 1. Create a free cluster and database user. 2. Allow your IP (or `0.0.0.0/0` for development only). 3. Copy connection string → `MONGODB_URI=mongodb+srv://...` **Reddit OAuth:** Create an app at [reddit.com/prefs/apps](https://www.reddit.com/prefs/apps) (web app), set redirect URI to `http://localhost:5000/api/auth/reddit/callback`. See [docs/ENVIRONMENT.md](docs/ENVIRONMENT.md). **Devvit:** See [docs/DEVVIT.md](docs/DEVVIT.md). ## Demo credentials & demo mode ### Default admin (created on first startup) | Field | Value | |-------|--------| | Email | `admin@modpulse.ai` | | Password | `ModPulse2026!` (or your `DEFAULT_ADMIN_PASSWORD`) | ### Portfolio demo mode In `backend/.env`: DEMO_MODE=true SEED_ON_STARTUP=true Then (as super_admin): curl -X POST http://localhost:5000/api/demo/seed \ -H "Authorization: Bearer " Optional simulated traffic: curl -X POST http://localhost:5000/api/demo/traffic/start \ -H "Authorization: Bearer " Stop traffic: `POST /api/demo/traffic/stop` See [docs/DEPLOYMENT.md](docs/DEPLOYMENT.md) for production demo instances. ### Demo workflow (FYP / portfolio) 1. Start backend + frontend, sign in as admin. 2. Open **Threat Detection** → **Start Raid Simulation** → observe live threat level and alerts. 3. Open **Reddit Sandbox** → create post → post toxic comment → view AI explanation. 4. Open **Moderator Copilot** → chat: `show high risk users` or `start raid simulation`. 5. Open **AI Moderation** → analyze a comment → expand **AI Reasoning**. 6. Toggle **dark/light theme** from the navbar (persists across reloads). ## API overview Base URL: `http://localhost:5000` (development) Protected routes require: `Authorization: Bearer ` | Namespace | Path | Description | |-----------|------|-------------| | Health | `GET /health`, `GET /metrics` | Liveness & request metrics | | Auth | `/api/auth/*` | Login, register, refresh, Reddit OAuth | | Moderation | `/api/moderation/*` | Analyze, logs, AI health | | Threats | `/api/threats/*` | Alerts, raids, lockdown, investigations | | Copilot | `/api/copilot/*` | Queue, recommendations, actions | | Analytics | `/api/analytics/*` | Dashboard, heatmaps, export | | Community | `/api/community/*` | Insights, mood, snapshots | | Settings | `/api/settings` | Platform & AI automation settings | | Reddit | `/api/reddit/*` | Connected subreddits | | Notifications | `/api/notifications/*` | In-app notifications | | Automation | `/api/automation/*` | Scheduled automation rules | | **ModPulse OS** | `/api/os/*` | Raid sim, sandbox, appeals, lockdown, copilot chat | | Demo | `/api/demo/*` | Seed & traffic (when `DEMO_MODE=true`) | | Devvit | `/api/devvit/*` | Webhooks & install (public routes vary) | Full reference: [docs/API.md](docs/API.md) ## WebSocket events Connect: `io(VITE_API_URL, { path: '/socket.io', auth: { token: accessToken } })` | Category | Events | |----------|--------| | Connection | `modpulse:connected` | | Threat | `threat:alert`, `threat:emergency`, `threat:metrics`, `moderation:alert`, `threat:lockdown` | | Raid sim | `raid:started`, `raid:tick`, `raid:threat-level`, `raid:ended` | | Copilot | `copilot:queue`, `copilot:action`, `copilot:alert`, `copilot:recommendation` | | Analytics | `analytics:live-metrics`, `analytics:dashboard-refresh`, `analytics:update` | | Sandbox | `sandbox:post-created`, `sandbox:comment-created`, `sandbox:moderation-action` | | Appeals | `appeal:created`, `appeal:updated` | | Lockdown | `lockdown:updated` | | Reputation | `user:reputation-updated` | Details: [docs/SOCKET.md](docs/SOCKET.md) ## Theme system - Toggle via **sun/moon** icon in the navbar. - Persisted in `localStorage` under key **`modpulse-theme`** (`dark` | `light`). - Inline script in `frontend/index.html` applies theme before React paint (no flash). - Light mode uses CSS variable overrides in `frontend/src/index.css`. ## Docker # From repository root docker compose up --build | Service | URL | |---------|-----| | Frontend | http://localhost:5173 (nginx) | | API | http://localhost:5000 | | MongoDB | localhost:27017 | | Redis | localhost:6379 | Production profile: docker compose -f docker-compose.prod.yml up --build -d ## Testing # Backend — Jest + Supertest cd backend && npm test # Frontend — Vitest + Testing Library cd frontend && npm test CI runs both test suites via `.github/workflows/ci.yml` when configured. ## Deployment | Component | Suggested target | |-----------|------------------| | Frontend | Vercel, Netlify, or Nginx static host | | API + Socket.io | Railway, Render, Fly.io, or VPS (port **5000**) | | Database | MongoDB Atlas | | Redis | Redis Cloud (optional) | Guide: [docs/DEPLOYMENT.md](docs/DEPLOYMENT.md) ## 🚀 Live Demo / Devvit App ModPulse AI is deployed as a Reddit Devvit application that integrates directly into Reddit moderator workflows. **Playtest / App Link:** https://www.reddit.com/r/modpulse_saas_dev ## 📌 About the App ModPulse AI is an AI-powered Reddit moderation system designed to help moderators manage communities more efficiently. It detects toxic content in real time, identifies raid patterns, and provides AI-assisted moderation decisions. The system includes a full moderation dashboard with live analytics, moderation queues, threat detection, raid simulation, and an intelligent moderator copilot to automate and assist decision-making inside Reddit using Devvit. ## Demo Video - https://youtu.be/RcwOPWY-2e4 ## Documentation | Document | Description | |----------|-------------| | [Architecture](docs/ARCHITECTURE.md) | Layers, flows, security, realtime | | [Local setup](docs/SETUP.md) | Step-by-step dev environment | | [Environment variables](docs/ENVIRONMENT.md) | Full env reference | | [API reference](docs/API.md) | REST endpoints including `/api/os` | | [Socket.io events](docs/SOCKET.md) | Real-time event catalog | | [AI workflows](docs/AI_WORKFLOWS.md) | Scoring, copilot, appeals, raid sim | | [Database schema](docs/DATABASE.md) | Collections & indexes | | [Deployment](docs/DEPLOYMENT.md) | Production & demo instances | | [Devvit](docs/DEVVIT.md) | Reddit app integration | ## Troubleshooting | Issue | Solution | |-------|----------| | `ECONNREFUSED` on API calls | Ensure backend runs on port **5000** and `VITE_API_URL` matches | | Socket shows offline | Check JWT is valid; verify CORS and `CORS_ORIGIN` includes frontend URL | | AI always uses heuristics | Set `HUGGINGFACE_API_KEY`; check network to `api-inference.huggingface.co` | | MongoDB connection failed | Verify `MONGODB_URI`, Atlas IP allowlist, credentials | | Validation errors on sandbox/appeals | Pull latest code — `ModerationLog.source` and `AuditLog.entityType` enums are extended | | Raid sim won't start | Restart backend after schema updates; check MongoDB is running | | Lockdown shows error + success toast | Ensure backend is restarted with updated `AuditLog` enum | | Theme flashes on reload | Clear cache; confirm `index.html` inline theme script is present | ## Future improvements - Redis-backed caching for analytics aggregates - Webhook outbound integrations (Slack, Discord) - Multi-tenant organization billing - Enhanced LLM explanations (optional external provider behind feature flag) - E2E tests with Playwright - Kubernetes Helm chart ## License This project is licensed under the **MIT License** — see the [LICENSE](LICENSE) file in the repository root.
标签:后端开发