---
description: "Security guidelines and API key management best practices"
globs: ["**/*.env*", "**/*.config.*", "src/lib/**/*", "app/api/**/*"]
alwaysApply: true
---

# Security & API Key Management

Critical security guidelines for AI development in this repository.

## Core Security Principles

### 1. API Key and Credential Management
- **NEVER** commit API keys, secrets, or credentials to version control
- Always use environment variables for sensitive data
- Create `.env.example` files to document required environment variables
- Implement proper API key rotation and management patterns
- Use secure storage solutions for production deployments

### 2. Environment Variable Patterns
Create `.env.local` with these patterns:
```env
# AI Service Keys
OPENAI_API_KEY=your_openai_key_here
ANTHROPIC_API_KEY=your_anthropic_key_here

# Application Settings
NEXT_PUBLIC_APP_URL=http://localhost:3000
NODE_ENV=development

# Database (if needed)
DATABASE_URL=your_database_url_here
```

### 3. Data Privacy Guidelines
- Avoid sending sensitive user data to AI services
- Implement data anonymization where possible
- Follow GDPR and privacy regulations
- Document data usage and retention policies

### 4. API Security Best Practices
- Validate all inputs before sending to AI services
- Implement proper CORS settings
- Use HTTPS for all AI API communications
- Regularly rotate API keys and secrets

### 5. Error Handling Security
```javascript
// Secure error handling - don't expose sensitive details
try {
  const response = await aiClient.complete(prompt);
  return response;
} catch (error) {
  // Log detailed error internally
  logger.error('AI service error', { error, userId: user.id });
  
  // Return generic error to client
  throw new Error('AI service temporarily unavailable');
}
```

### 6. Rate Limiting and Monitoring
- Implement proper rate limiting for AI API endpoints
- Monitor API usage and costs
- Track unusual usage patterns
- Implement health checks for AI services