@openclueo/express-clueobots
Version:
Express.js middleware for ClueoBots AI Security - One line of code, full protection
350 lines (270 loc) • 9.28 kB
Markdown
> 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.
[](https://www.npmjs.com/package/@openclueo/express-clueobots)
[](https://clueoai.com/license)
```bash
npm install @openclueo/express-clueobots
```
```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)
```
- 🔍 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
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
```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
}
}))
```
```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())
```
```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
})
}
}))
```
```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
}))
```
```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
}
}))
```
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
})
```
```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)
})
```
```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 })
})
```
```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')
})
}
}))
```
```typescript
app.get('/api/security/health', (req, res) => {
// This endpoint is automatically excluded
res.json({
status: 'healthy',
clueobots: 'active'
})
})
```
```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
}
}))
```
```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
}
}
}))
```
```bash
CLUEOBOTS_API_KEY=your-api-key-here
CLUEOBOTS_BASE_URL=https://backend.clueobots.com
CLUEOBOTS_TIMEOUT=5000
CLUEOBOTS_DEBUG=false
```
- Free Tier: 100 scans/month
- Pro Tier: 10,000 scans/month - $29/month
- Enterprise: Unlimited scans - Contact sales
- 📧 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)
This package is proprietary software. See [LICENSE](https://clueoai.com/license) for details.
---
<div align="center">
[](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>