Back to Documentation
Security
Protect your AI applications from prompt injection, data leaks, and abuse. Built-in security features for production deployments.
npm install @rana/security
Security Best Practice
Always validate and sanitize user inputs before sending to LLMs. Enable prompt injection detection and PII redaction for all user-facing applications.
Prompt Injection Detection
Detect and block prompt injection attacks in real-time
import { PromptGuard } from '@rana/security';
const guard = new PromptGuard({
sensitivity: 'high',
blockOnDetection: true,
logAttempts: true
});
// Check user input before sending to LLM
const result = guard.check(userInput);
if (result.isInjection) {
console.log(result.type); // 'jailbreak' | 'instruction_override' | 'data_extraction'
console.log(result.confidence); // 0.95
console.log(result.details); // Explanation
throw new Error('Prompt injection detected');
}
// Or use as middleware
app.use(guard.middleware());PII Detection & Redaction
Automatically detect and redact sensitive data
import { PIIDetector } from '@rana/security';
const detector = new PIIDetector({
types: ['email', 'phone', 'ssn', 'credit_card', 'address'],
customPatterns: [
{ name: 'employee_id', pattern: /EMP-\d{6}/ }
]
});
// Detect PII
const findings = detector.detect(text);
// [{ type: 'email', value: 'john@...', start: 10, end: 25 }]
// Redact PII
const redacted = detector.redact(text);
// "Contact [EMAIL] for support"
// Redact with replacement
const masked = detector.redact(text, {
email: (val) => val.replace(/(?<=.).(?=.*@)/g, '*')
});
// "Contact j***@example.com for support"Content Filtering
Filter harmful, inappropriate, or off-topic content
import { ContentFilter } from '@rana/security';
const filter = new ContentFilter({
categories: ['hate', 'violence', 'sexual', 'self_harm'],
customRules: [
{ name: 'competitor_mention', keywords: ['competitor1', 'competitor2'] }
],
thresholds: {
hate: 0.7,
violence: 0.8
}
});
// Check content
const result = await filter.check(content);
if (result.flagged) {
console.log(result.categories); // ['hate']
console.log(result.scores); // { hate: 0.85, violence: 0.1 }
}
// Filter and modify
const safe = await filter.filter(content, {
action: 'redact' // or 'block', 'warn'
});Audit Logging
Comprehensive audit trail for all AI operations
import { AuditLogger } from '@rana/security';
const audit = new AuditLogger({
storage: 'postgresql',
retention: '7 years',
encryption: true
});
// Log AI operations
await audit.log({
action: 'ai.chat',
actor: { id: userId, type: 'user' },
resource: { type: 'conversation', id: conversationId },
input: { prompt: userMessage },
output: { response: aiResponse },
metadata: { model: 'gpt-4', tokens: 500 }
});
// Query audit logs
const logs = await audit.query({
actor: userId,
action: 'ai.*',
timeRange: { from: '30d ago' }
});
// Export for compliance
await audit.export({
format: 'csv',
period: 'last-quarter'
});Rate Limiting
Per-user and per-endpoint rate limiting
import { RateLimiter } from '@rana/security';
const limiter = new RateLimiter({
storage: 'redis',
defaultLimits: {
requests: { max: 100, window: '1m' },
tokens: { max: 10000, window: '1h' },
cost: { max: 1.00, window: '1d' }
}
});
// Check rate limit
const allowed = await limiter.check(userId, {
type: 'requests',
cost: 1
});
if (!allowed.success) {
console.log(allowed.retryAfter); // seconds until reset
throw new RateLimitError(allowed);
}
// Custom limits per user tier
await limiter.setUserLimits(userId, {
requests: { max: 1000, window: '1m' } // Premium user
});
// Express middleware
app.use('/api/chat', limiter.middleware('requests'));API Key Management
Secure API key rotation and access control
import { KeyManager } from '@rana/security';
const keys = new KeyManager({
storage: 'vault', // or 'aws-secrets', 'env'
rotationPolicy: {
maxAge: '90d',
warningBefore: '14d'
}
});
// Get current key (auto-rotates if needed)
const apiKey = await keys.get('openai');
// Manual rotation
await keys.rotate('openai', {
newKey: process.env.NEW_OPENAI_KEY,
gracePeriod: '1h' // Both keys valid during transition
});
// Key usage tracking
const usage = await keys.getUsage('openai');
console.log(usage.requestCount);
console.log(usage.lastUsed);
// Alerts
keys.onRotationNeeded((keyName, daysUntilExpiry) => {
notify(`Key ${keyName} expires in ${daysUntilExpiry} days`);
});