UNPKG

@openclueo/express-clueobots

Version:

Express.js middleware for ClueoBots AI Security - One line of code, full protection

350 lines (270 loc) 9.28 kB
# @openclueo/express-clueobots > Express.js middleware for ClueoBots AI Security - One line of code, full protection Protect your Express.js applications from AI security threats with just one line of code. Automatically scans incoming requests for prompt injection, jailbreaking, data exfiltration, and other LLM-based attacks. [![npm version](https://badge.fury.io/js/@openclueo%2Fexpress-clueobots.svg)](https://www.npmjs.com/package/@openclueo/express-clueobots) [![License: PROPRIETARY](https://img.shields.io/badge/License-PROPRIETARY-red.svg)](https://clueoai.com/license) ## 🚀 Quick Start ### Installation ```bash npm install @openclueo/express-clueobots ``` ### Basic Usage ```typescript import express from 'express' import { clueobots } from '@openclueo/express-clueobots' const app = express() app.use(express.json()) // ONE LINE = FULL AI SECURITY PROTECTION app.use(clueobots({ apiKey: 'your-clueobots-api-key' })) // All your routes are now automatically protected app.post('/api/chat', (req, res) => { // req.body is already scanned for threats // Malicious prompts are blocked before reaching here res.json({ message: 'Safe to proceed with AI processing!' }) }) app.listen(3000) ``` ## 🛡️ Features - 🔍 Real-time Threat Detection - Scans all incoming requests for AI security threats - 🚫 Automatic Blocking - Blocks malicious requests before they reach your AI - ⚡ Ultra-fast - < 50ms latency, built for production scale - 🎯 Smart Targeting - Only scans AI-related content, ignores static assets - 🔧 Highly Configurable - Customize protection levels and behavior - 📊 Built-in Analytics - Track threats and performance metrics - 💪 TypeScript First - Full type safety and IntelliSense support ## 🎯 Protection Coverage ClueoBots middleware automatically detects and blocks: - Prompt Injection - Attempts to manipulate AI system behavior - Jailbreaking - Efforts to bypass AI safety measures - Data Exfiltration - Attempts to extract sensitive information - Context Manipulation - Conversation hijacking attacks - Model Inversion - Attempts to reverse-engineer AI models - System Prompt Leaks - Efforts to reveal internal prompts ## 📖 Configuration Options ```typescript app.use(clueobots({ apiKey: 'your-api-key', // Required: Your ClueoBots API key baseUrl: 'https://backend.clueobots.com', // Optional: Custom API endpoint blockThreshold: 'medium', // Optional: 'low' | 'medium' | 'high' | 'critical' paths: ['/api/chat', '/api/generate'], // Optional: Specific paths to protect excludePaths: ['/api/health'], // Optional: Paths to skip blockRequests: true, // Optional: Whether to block threats debug: false, // Optional: Enable debug logging timeout: 5000, // Optional: Request timeout (ms) // Optional: Custom threat handler onThreat: (threat, req, res) => { console.log(`Threat detected: ${threat.threatType}`) res.status(400).json({ error: 'Custom threat response', details: threat }) }, // Optional: Custom error handler onError: (error, req, res) => { console.error('ClueoBots error:', error) // Fail open - continue processing } })) ``` ## 💡 Usage Examples ### Protect Specific Routes ```typescript import { clueobots } from '@openclueo/express-clueobots' // Only protect AI-related endpoints app.use('/api/chat', clueobots()) app.use('/api/generate', clueobots()) app.use('/api/ai', clueobots()) // Other routes are unaffected app.use('/api/users', regularMiddleware()) ``` ### Custom Threat Handling ```typescript app.use(clueobots({ apiKey: process.env.CLUEOBOTS_API_KEY, blockThreshold: 'high', // Only block high/critical threats onThreat: (threat, req, res) => { // Log threat for analysis console.log('Security Alert:', { threatType: threat.threatType, riskLevel: threat.riskLevel, userAgent: req.get('user-agent'), ip: req.ip, timestamp: threat.timestamp }) // Custom response res.status(403).json({ error: 'Request blocked for security reasons', message: 'Please rephrase your request and try again', supportId: threat.scanId }) } })) ``` ### Selective Protection ```typescript app.use(clueobots({ paths: ['/api/chat', '/api/generate', '/api/completion'], excludePaths: ['/api/health', '/api/metrics'], skipContentTypes: ['image', 'application/pdf'], maxBodySize: 1024 * 1024, // 1MB max scan size })) ``` ### Development Mode ```typescript app.use(clueobots({ debug: true, // Enable detailed logging blockRequests: false, // Log threats but don't block (monitoring mode) onThreat: (threat, req, res) => { console.log('🚨 THREAT DETECTED (dev mode):', threat) // Continue processing in development } })) ``` ## 🔍 Request Enhancement The middleware enhances your Express requests with threat information: ```typescript interface RequestWithClueoBots extends Request { clueobots?: { scanned: boolean threat?: ThreatInfo scanTime: number } } app.post('/api/chat', (req: RequestWithClueoBots, res) => { if (req.clueobots?.threat) { // Handle threat detected but not blocked console.log(`Low-level threat: ${req.clueobots.threat.threatType}`) } console.log(`Scan took: ${req.clueobots?.scanTime}ms`) // Your business logic here }) ``` ## 🎪 Real-world Examples ### ChatGPT Clone Protection ```typescript import express from 'express' import { clueobots } from '@openclueo/express-clueobots' import OpenAI from 'openai' const app = express() const openai = new OpenAI() // Protect all chat endpoints app.use('/api/chat', clueobots({ blockThreshold: 'medium', onThreat: (threat, req, res) => { res.json({ error: 'I cannot process that request for security reasons.', suggestion: 'Please rephrase your message in a different way.' }) } })) app.post('/api/chat/completions', async (req, res) => { // Request is already secured by ClueoBots const completion = await openai.chat.completions.create({ model: 'gpt-4', messages: req.body.messages }) res.json(completion) }) ``` ### Content Generation API ```typescript app.use('/api/generate', clueobots({ blockThreshold: 'high', // More permissive for creative content onThreat: (threat, req, res) => { if (threat.riskLevel === 'critical') { // Block critical threats res.status(400).json({ error: 'Content generation request blocked', reason: 'Security policy violation' }) } else { // Log but allow medium/high threats for creative content console.log('Creative content threat logged:', threat.threatType) } } })) app.post('/api/generate/story', async (req, res) => { // Generate creative content safely const story = await generateStory(req.body.prompt) res.json({ story }) }) ``` ## 📊 Performance & Analytics ### Monitoring ```typescript app.use(clueobots({ onThreat: (threat, req, res) => { // Send to your analytics service analytics.track('threat_detected', { threatType: threat.threatType, riskLevel: threat.riskLevel, confidence: threat.confidence, endpoint: req.path, userAgent: req.get('user-agent') }) } })) ``` ### Health Checks ```typescript app.get('/api/security/health', (req, res) => { // This endpoint is automatically excluded res.json({ status: 'healthy', clueobots: 'active' }) }) ``` ## 🚨 Error Handling ### Graceful Degradation ```typescript app.use(clueobots({ onError: (error, req, res) => { console.error('ClueoBots service error:', error) // Log to monitoring service monitoring.error('clueobots_error', error) // Fail open - continue processing // Your app stays available even if ClueoBots is down } })) ``` ### Circuit Breaker Pattern ```typescript let errorCount = 0 const ERROR_THRESHOLD = 5 app.use(clueobots({ onError: (error, req, res) => { errorCount++ if (errorCount > ERROR_THRESHOLD) { // Temporarily disable ClueoBots to prevent cascading failures console.log('ClueoBots circuit breaker activated') // Implement your circuit breaker logic } } })) ``` ## 🔧 Environment Variables ```bash # Required CLUEOBOTS_API_KEY=your-api-key-here # Optional CLUEOBOTS_BASE_URL=https://backend.clueobots.com CLUEOBOTS_TIMEOUT=5000 CLUEOBOTS_DEBUG=false ``` ## 📈 Pricing & Limits - Free Tier: 100 scans/month - Pro Tier: 10,000 scans/month - $29/month - Enterprise: Unlimited scans - Contact sales ## 🆘 Support - 📧 Email: [support@clueoai.com](mailto:support@clueoai.com) - 📚 Documentation: [clueoai.com/docs](https://clueoai.com/docs) - 💬 Discord: [Join our community](https://discord.gg/E8WP6gRj) - 🎫 Issues: [GitHub Issues](https://github.com/ClueoFoundation/ClueoBots/issues) ## 📄 License This package is proprietary software. See [LICENSE](https://clueoai.com/license) for details. --- <div align="center"> [Get Started](https://www.clueobots.com/signup) • [View Docs](https://clueoai.com/docs) • [Contact Sales](mailto:emmanuel@clueoai.com) Made with ❤️ by the Clueo Foundation Team </div>