# SecKav Security SDK v2.3.0

A comprehensive security SDK for Node.js applications providing AI-powered threat detection, LLM-powered misconfiguration scanning with Gemini/GPT-4/Claude, end-to-end encryption, behavioral analysis, enhanced file scanning, adaptive rate limiting, and advanced security monitoring.

## 🚀 Features

### Core Security Features
- **Rate Limiting**: Dynamic rate limiting with burst and sustained limits
- **Authentication**: User registration, login, and API key management
- **Organization Management**: Multi-tenant organization support with RBAC
- **Security Monitoring**: IP filtering, user agent filtering, geo-location filtering
- **Analytics**: Real-time metrics, comprehensive analytics, and threat analysis
- **Security Events**: Event logging and monitoring
- **Alerting**: Email, Slack, and webhook notifications

### 🆕 Enhanced Security Features (v2.1.0)
- **🤖 AI-Powered Threat Detection**: Advanced pattern recognition for SQL injection, XSS, SSTI, and more
- **🧠 Behavioral Anomaly Analysis**: Machine learning-based user behavior analysis
- **🔍 Advanced File Scanning**: Malware detection, steganography analysis, and document security
- **⚡ Adaptive Rate Limiting**: AI-powered dynamic rate limit calculations
- **🛡️ DDoS Protection**: Multi-layer defense against volumetric, protocol, and application attacks
- **🌐 Threat Intelligence**: Real-time threat feeds and IP reputation scoring
- **🔎 Behavioral Fingerprinting**: Advanced bot detection and user pattern analysis
- **📊 Real-time Security Metrics**: Comprehensive security health monitoring
- **🎯 Custom Threat Rules**: Configurable security policies and threat patterns
- **📈 Security Health Monitoring**: System status and component health tracking
- **📄 Automated Security Reports**: Detailed security analytics and reporting

### 🚀 Latest Features (v2.3.0)
- **🧠 LLM-Powered Misconfiguration Scanner**: AI security analysis with Gemini, GPT-4, and Claude
- **🔐 End-to-End Encryption Gateway**: TLS-enforced communication with automatic key rotation
- **📋 GDPR/DPDP/CERT-IN Compliance**: Automated compliance reporting and assessment
- **🔍 OpenAPI Security Scanning**: Deep analysis of API specifications for vulnerabilities
- **⚙️ Git Integration**: GitHub/GitLab repository security scanning and monitoring
- **🛡️ Advanced Certificate Management**: Automated SSL/TLS certificate lifecycle management
- **🎯 AI Security Recommendations**: Context-aware security improvement suggestions
- **📊 Enhanced Analytics Dashboard**: Real-time security metrics and threat visualization

## 📦 Installation

```bash
npm install @seckav/security-sdk
```

## 🔧 Quick Start

### Basic Setup

```javascript
import { SecKavSDK } from '@seckav/security-sdk';

const sdk = new SecKavSDK({
  apiUrl: 'https://api.seckav.com',
  organizationId: 'your-org-id',
  apiKey: 'your-api-key', // or jwtToken: 'your-jwt-token'
  features: {
    rateLimit: true,
    authentication: true,
    organizationManagement: true,
    security: true,
    analytics: true,
    enhancedSecurity: true, // 🆕 Enable AI-powered security features
    complianceReporting: true, // 🚀 Enable GDPR/DPDP compliance
    gitIntegration: true, // 🚀 Enable GitHub/GitLab scanning
    encryption: true, // 🚀 Enable end-to-end encryption
    misconfigurationScanning: true, // 🚀 Enable LLM-powered scanning
  },
});
```

### Express.js Middleware

```javascript
import express from 'express';
import { createSecKavMiddleware } from '@seckav/security-sdk';

const app = express();

// Apply SecKav security middleware
app.use(createSecKavMiddleware({
  apiUrl: 'https://api.seckav.com',
  organizationId: 'your-org-id',
  apiKey: 'your-api-key',
}));

app.get('/api/protected', (req, res) => {
  res.json({ message: 'This endpoint is protected by SecKav' });
});
```

### Next.js Middleware

```javascript
// middleware.js
import { createSecKavNextMiddleware } from '@seckav/security-sdk';

const secKavMiddleware = createSecKavNextMiddleware({
  apiUrl: 'https://api.seckav.com',
  organizationId: 'your-org-id',
  apiKey: 'your-api-key',
});

export async function middleware(request) {
  return await secKavMiddleware(request);
}

export const config = {
  matcher: '/api/:path*',
};
```

## 📚 Module Usage

### Authentication Module

```javascript
const authModule = sdk.getAuthenticationModule();

// Register a new user
const registerResult = await authModule.register(
  'user@example.com',
  'password123',
  'John Doe'
);

// Login user
const loginResult = await authModule.login('user@example.com', 'password123');
const { token } = loginResult;

// Get user profile
const profileResult = await authModule.getProfile(token);

// Generate API key
const apiKeyResult = await authModule.generateApiKey(token, 'My API Key');
```

### Organization Module

```javascript
const orgModule = sdk.getOrganizationModule();

// Create organization
const orgResult = await orgModule.createOrganization(
  token,
  'My Company',
  'Company description',
  'company.com'
);

// Get organizations
const orgsResult = await orgModule.getOrganizations(token);

// Add member
const memberResult = await orgModule.addMember(token, orgId, {
  email: 'member@example.com',
  role: 'developer'
});
```

### Security Module

```javascript
const securityModule = sdk.getSecurityModule();

// Get security settings
const settingsResult = await securityModule.getSecuritySettings(token);

// Update IP whitelist
const ipResult = await securityModule.updateIpWhitelist(token, [
  '192.168.1.0/24',
  '10.0.0.0/8'
]);

// Update user agent filtering
const uaResult = await securityModule.updateUserAgentFiltering(token, {
  enabled: true,
  blockedPatterns: ['bot', 'crawler'],
  blockUnknownAgents: true
});

// Get security events
const eventsResult = await securityModule.getSecurityEvents(token, {
  page: 1,
  limit: 50,
  severity: 'high'
});
```

### Analytics Module

```javascript
const analyticsModule = sdk.getAnalyticsModule();

// Get real-time metrics
const metricsResult = await analyticsModule.getRealTimeMetrics(token);

// Get comprehensive analytics
const analyticsResult = await analyticsModule.getAnalytics(token, '24h');

// Get geo-distribution
const geoResult = await analyticsModule.getGeoDistribution(token, '7d');

// Track custom event
const trackResult = await analyticsModule.trackEvent(token, {
  ipAddress: '192.168.1.100',
  endpoint: '/api/custom',
  method: 'POST',
  userAgent: 'Custom Client/1.0'
});
```

### Rate Limiting Module

```javascript
const rateLimitModule = sdk.getRateLimitModule();

// Check rate limit manually
const rateLimitResult = await rateLimitModule.checkRequest(req);

if (!rateLimitResult.allowed) {
  // Handle rate limit exceeded
  console.log('Rate limit exceeded:', rateLimitResult.retryAfter);
}
```

### 🆕 Enhanced Security Module

```javascript
const enhancedSecurity = sdk.getEnhancedSecurityModule();

// Analyze request for threats
const threatResult = await sdk.analyzeThreat(token, {
  url: '/api/users',
  method: 'POST',
  headers: { 'User-Agent': 'Mozilla/5.0...' },
  body: { username: 'john_doe', email: 'john@example.com' }
});

// Analyze for behavioral anomalies
const anomalyResult = await sdk.analyzeAnomaly(token, {
  organizationId: 'your-org-id',
  ipAddress: '192.168.1.100',
  userAgent: 'Mozilla/5.0...',
  endpoint: '/api/users',
  method: 'GET',
  payloadSize: 1024,
  timestamp: new Date(),
  country: 'US'
});

// Scan files for malware and threats
const fileResult = await sdk.scanFile(token, {
  filename: 'document.pdf',
  content: fileBuffer,
  mimeType: 'application/pdf'
});

// Get comprehensive security metrics
const securityMetrics = await sdk.getSecurityMetrics(token, '24h');

// Check DDoS attack status
const ddosStatus = await sdk.checkDDoSStatus(token, 'your-org-id');

// Get security system health
const healthStatus = await sdk.getSecurityHealth(token);

// Configure security policy
await enhancedSecurity.configureSecurityPolicy(token, {
  enableThreatDetection: true,
  enableAnomalyDetection: true,
  enableAdaptiveRateLimit: true,
  enableFileScanning: true,
  blockCritical: true,
  blockHigh: true,
  blockMedium: false,
  maxFileSize: 10 * 1024 * 1024, // 10MB
  allowedFileTypes: ['jpg', 'jpeg', 'png', 'pdf', 'docx']
});

// Get threat intelligence for IP
const threatIntel = await enhancedSecurity.getThreatIntelligence(token, '192.168.1.100');

// Analyze behavioral fingerprint
const behavioralResult = await enhancedSecurity.getBehavioralFingerprint(token, [
  {
    timestamp: new Date(),
    endpoint: '/api/users',
    method: 'GET',
    userAgent: 'Mozilla/5.0...',
    payloadSize: 1024,
    responseTime: 150
  }
]);
```

## 🔧 Configuration Options

```javascript
const config = {
  apiUrl: 'https://api.seckav.com',           // Required: SecKav API URL
  organizationId: 'your-org-id',              // Required: Your organization ID
  apiKey: 'your-api-key',                     // Optional: API key for authentication
  jwtToken: 'your-jwt-token',                 // Optional: JWT token for authentication
  timeout: 5000,                              // Optional: Request timeout in ms
  features: {                                 // Optional: Enable/disable features
    rateLimit: true,
    authentication: true,
    organizationManagement: true,
    security: true,
    analytics: true,
  },
  onError: (error) => console.error(error),   // Optional: Error handler
  debug: false,                               // Optional: Enable debug logging
};
```

## 🛡️ Security Features

### IP Filtering
- Whitelist/blacklist IP addresses and CIDR ranges
- Automatic blocking of suspicious IPs
- Real-time IP reputation checking

### User Agent Filtering
- Block known bots and crawlers
- Custom user agent patterns
- Unknown agent detection

### Geo-location Filtering
- Country-based access control
- VPN/Proxy detection
- Location-based analytics

### Rate Limiting
- Per-API-key rate limiting
- IP-based rate limiting
- Burst and sustained limits
- Custom rate limit policies

## 📊 Analytics & Monitoring

### Real-time Metrics
- Current requests per second
- Active connections
- Rate limit hits
- Security blocks

### Historical Analytics
- Request statistics
- Geographic distribution
- Top endpoints
- Threat analysis

### Security Events
- Event logging and tracking
- Severity-based filtering
- Event resolution workflow
- Alert integration

## 🚨 Alerting

### Supported Channels
- Email notifications
- Slack integration
- Webhook endpoints

### Alert Types
- Rate limit violations
- Security incidents
- Suspicious activity
- System events

## 🔄 Backward Compatibility

The SDK maintains backward compatibility with v1.x for rate limiting:

```javascript
import { createRateLimitMiddleware } from '@seckav/security-sdk';

const rateLimitMiddleware = createRateLimitMiddleware({
  apiUrl: 'https://api.seckav.com',
  organizationId: 'your-org-id',
  apiKey: 'your-api-key',
});

app.use(rateLimitMiddleware);
```

## 📖 API Reference

### SecKavSDK Class

#### Constructor
- `new SecKavSDK(config: SecKavConfig)`

#### Methods
- `getExpressMiddleware(): Function`
- `getNextMiddleware(): Function`
- `getRateLimitModule(): RateLimitModule | null`
- `getAuthenticationModule(): AuthenticationModule | null`
- `getOrganizationModule(): OrganizationModule | null`
- `getSecurityModule(): SecurityModule | null`
- `getAnalyticsModule(): AnalyticsModule | null`
- `getInfo(): SDKInfo`
- `updateConfig(config: Partial<SecKavConfig>): void`

#### Convenience Methods
- `login(email: string, password: string): Promise<AuthResult>`
- `register(email: string, password: string, name: string): Promise<AuthResult>`
- `getProfile(token: string): Promise<AuthResult>`
- `createOrganization(token: string, name: string, description?: string, domain?: string): Promise<OrganizationResult>`
- `getOrganizations(token: string): Promise<OrganizationResult>`
- `getSecuritySettings(token: string): Promise<SecurityResult>`
- `updateIpWhitelist(token: string, ipAddresses: string[]): Promise<SecurityResult>`
- `getRealTimeMetrics(token: string): Promise<AnalyticsResult>`
- `getAnalytics(token: string, timeframe?: string): Promise<AnalyticsResult>`

## 🤝 Support

- Documentation: [https://docs.seckav.com](https://docs.seckav.com)
- GitHub Issues: [https://github.com/seckav/security-sdk/issues](https://github.com/seckav/security-sdk/issues)
- Email: support@seckav.com

## 📄 License

MIT License - see [LICENSE](LICENSE) file for details.

### 🧠 Misconfiguration Scanner Module (v2.3.0)

```javascript
const scanner = sdk.misconfigurationScanning;

// Configure LLM provider (Gemini, GPT-4, or Claude)
await scanner.configureLLM({
  provider: 'gemini',
  apiKey: 'your-gemini-api-key',
  model: 'gemini-1.5-flash'
});

// Scan OpenAPI specification
const apiScanResult = await scanner.scanOpenAPISpec(
  JSON.stringify(openApiSpec),
  'api-spec.json'
);

// Scan configuration files
const configScanResult = await scanner.uploadAndScanFiles([
  {
    filename: '.env',
    content: 'API_KEY=secret123\nDATABASE_URL=...',
    type: 'environment'
  }
]);

// Get AI-powered security recommendations
const recommendations = await scanner.getSecurityRecommendations({
  organizationType: 'startup',
  complianceRequirements: ['owasp', 'gdpr']
});

// Perform quick security assessment
const assessment = await scanner.quickAssessment({
  apiSpecs: ['api-spec.json'],
  includeRecommendations: true
});
```

### 🔐 Encryption Module (v2.3.0)

```javascript
const encryption = sdk.getEncryptionModule();

// Get encryption status
const status = await encryption.getEncryptionStatus(token);

// Enable encryption with configuration
await encryption.enableEncryption(token, {
  algorithm: 'AES-256-GCM',
  keyRotationInterval: 24, // hours
  tlsMinVersion: '1.3'
});

// Rotate encryption keys manually
await encryption.rotateEncryptionKey(token, 'security-update');

// Test encryption functionality
const testResult = await encryption.testEncryption(token, {
  message: 'test data'
});
```

### 📋 Compliance Module (v2.3.0)

```javascript
const compliance = sdk.getComplianceModule();

// Generate compliance report
const gdprReport = await compliance.generateComplianceReport(
  token,
  'gdpr',
  {
    startDate: new Date('2024-01-01'),
    endDate: new Date('2024-12-31')
  }
);

// Get compliance dashboard
const dashboard = await compliance.getComplianceDashboard(token);

// Scan API specification for compliance
const complianceScan = await compliance.scanApiSpecification(token, {
  name: 'user-api.json',
  content: JSON.stringify(apiSpec),
  type: 'openapi'
});
```

### ⚙️ Git Integration Module (v2.3.0)

```javascript
const gitIntegration = sdk.getGitIntegrationModule();

// Test GitHub connection
const connectionTest = await gitIntegration.testGitConnection(token, {
  type: 'github',
  token: 'github_pat_...',
});

// Get repositories
const repositories = await gitIntegration.getRepositories(token, {
  type: 'github',
  token: 'github_pat_...',
}, {
  page: 1,
  perPage: 50
});

// Scan repository for security issues
const repoScanResult = await gitIntegration.scanRepository(token, {
  type: 'github',
  token: 'github_pat_...',
}, 'repo-id', {
  branch: 'main',
  includeApiSpecs: true,
  includeConfigFiles: true
});
```

## 🔄 Changelog

### v2.3.0
- ✨ **NEW**: LLM-Powered Misconfiguration Scanner with Gemini, GPT-4, and Claude support
- ✨ **NEW**: End-to-End Encryption Gateway with automatic key rotation
- ✨ **NEW**: GDPR/DPDP/CERT-IN Compliance reporting and assessment
- ✨ **NEW**: OpenAPI/Swagger security scanning with AI analysis
- ✨ **NEW**: GitHub/GitLab integration for repository security scanning
- ✨ **NEW**: Advanced certificate management with automated lifecycle
- ✨ **NEW**: AI-powered security recommendations and threat modeling
- ✨ **NEW**: Enhanced analytics dashboard with real-time visualization
- 🔧 Modern SDK architecture with TypeScript 5.8+ support
- 🚀 Performance improvements and better error handling
- 📚 Comprehensive documentation with practical examples

### v2.1.0
- ✨ **NEW**: Enhanced Security Module with AI-powered threat detection
- ✨ **NEW**: Behavioral anomaly analysis and machine learning capabilities
- ✨ **NEW**: Advanced file scanning with malware and steganography detection
- ✨ **NEW**: Adaptive rate limiting with AI-powered calculations
- ✨ **NEW**: DDoS protection across multiple attack vectors
- ✨ **NEW**: Real-time threat intelligence integration
- ✨ **NEW**: Behavioral fingerprinting and advanced bot detection
- ✨ **NEW**: Comprehensive security metrics and health monitoring
- ✨ **NEW**: Custom threat rules and configurable security policies
- ✨ **NEW**: Automated security reporting capabilities
- 🔧 Enhanced SDK architecture for enterprise-grade performance
- 📚 Updated documentation with enhanced security examples

### v2.0.1
- 📄 Added MIT LICENSE file
- 🔧 Minor package improvements
- ✅ Verified README inclusion in npm package

### v2.0.0
- ✨ Added Authentication module
- ✨ Added Organization Management module
- ✨ Added Security module with IP/UA/Geo filtering
- ✨ Added Analytics module with real-time metrics
- ✨ Added Security Events and Alerting
- ✨ Enhanced TypeScript support
- ✨ Comprehensive error handling
- 🔧 Improved configuration options
- 📚 Complete API documentation

### v1.0.0
- ✨ Initial release with Rate Limiting
- ✨ Express.js and Next.js middleware support
- ✨ Basic API key authentication 