UNPKG

@seckav/security-sdk

Version:

SecKav Security SDK - Enterprise-grade security platform with AI-powered threat detection, LLM-powered misconfiguration scanning (Gemini/GPT-4/Claude), end-to-end encryption, behavioral analysis, enhanced file scanning, adaptive rate limiting, GDPR/DPDP/C

578 lines 22.5 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.SecKavSDK = void 0; exports.createSecKavMiddleware = createSecKavMiddleware; exports.createSecKavNextMiddleware = createSecKavNextMiddleware; const RateLimit_1 = require("../modules/RateLimit"); const Authentication_1 = require("../modules/Authentication"); const Organization_1 = require("../modules/Organization"); const Security_1 = require("../modules/Security"); const Analytics_1 = require("../modules/Analytics"); const EnhancedSecurity_1 = require("../modules/EnhancedSecurity"); const Compliance_1 = require("../modules/Compliance"); const GitIntegration_1 = require("../modules/GitIntegration"); const EncryptionModule_1 = require("../modules/EncryptionModule"); const MisconfigurationScanner_1 = require("../modules/MisconfigurationScanner"); /** * SecKav Security SDK - Main class for all security features * Supports: Rate Limiting, Authentication, Organization Management, Security, Analytics, Enhanced Security, Compliance Reporting, Git Integration * NEW: GDPR/DPDP/CERT-IN Compliance, OpenAPI Security Scanning, GitHub/GitLab Integration */ class SecKavSDK { constructor(config) { this.config = { timeout: 5000, features: { rateLimit: true, authentication: true, organizationManagement: true, security: true, analytics: true, enhancedSecurity: true, // Enhanced Security Features apiFirewall: false, // Coming soon threatDetection: false, // Coming soon securityScanning: false, // Legacy (replaced by compliance) complianceReporting: true, // NEW: GDPR, DPDP, CERT-IN compliance gitIntegration: true, // NEW: GitHub/GitLab integration encryption: true, // NEW: End-to-end encryption and key management misconfigurationScanning: true, // NEW: LLM-powered misconfiguration scanning }, debug: false, ...config, }; // Initialize enabled modules if (this.config.features?.rateLimit) { // Ensure we have either apiKey or jwtToken for rate limiting if (this.config.apiKey || this.config.jwtToken) { this.rateLimit = new RateLimit_1.RateLimitModule({ apiUrl: this.config.apiUrl, organizationId: this.config.organizationId, apiKey: this.config.apiKey || '', // RateLimitModule will handle empty string timeout: this.config.timeout, onError: this.config.onError, }); } else { console.warn('Rate limiting disabled: apiKey or jwtToken required'); } } if (this.config.features?.authentication) { this.authentication = new Authentication_1.AuthenticationModule({ apiUrl: this.config.apiUrl, timeout: this.config.timeout, onError: this.config.onError, }); } if (this.config.features?.organizationManagement) { this.organization = new Organization_1.OrganizationModule({ apiUrl: this.config.apiUrl, timeout: this.config.timeout, onError: this.config.onError, }); } if (this.config.features?.security) { this.security = new Security_1.SecurityModule({ apiUrl: this.config.apiUrl, timeout: this.config.timeout, onError: this.config.onError, }); } if (this.config.features?.analytics) { this.analytics = new Analytics_1.AnalyticsModule({ apiUrl: this.config.apiUrl, timeout: this.config.timeout, onError: this.config.onError, }); } if (this.config.features?.enhancedSecurity) { this.enhancedSecurity = new EnhancedSecurity_1.EnhancedSecurityModule({ apiUrl: this.config.apiUrl, timeout: this.config.timeout, onError: this.config.onError, }); } if (this.config.features?.complianceReporting) { this.compliance = new Compliance_1.ComplianceModule({ apiUrl: this.config.apiUrl, timeout: this.config.timeout, onError: this.config.onError, }); } if (this.config.features?.gitIntegration) { this.gitIntegration = new GitIntegration_1.GitIntegrationModule({ apiUrl: this.config.apiUrl, timeout: this.config.timeout, onError: this.config.onError, }); } if (this.config.features?.encryption) { this.encryption = new EncryptionModule_1.EncryptionModule({ apiUrl: this.config.apiUrl, organizationId: this.config.organizationId, timeout: this.config.timeout, onError: this.config.onError, }); } if (this.config.features?.misconfigurationScanning) { this.misconfigurationScanner = new MisconfigurationScanner_1.MisconfigurationScannerModule({ apiUrl: this.config.apiUrl, organizationId: this.config.organizationId, timeout: this.config.timeout, onError: this.config.onError, }); } // Log SDK initialization if (this.config.debug) { console.log('SecKav SDK initialized with features:', Object.entries(this.config.features) .filter(([, enabled]) => enabled) .map(([feature]) => feature)); } } /** * Get Express.js middleware with all enabled security features */ getExpressMiddleware() { return async (req, res, next) => { try { // Rate limiting check (if enabled) if (this.config.features?.rateLimit && this.rateLimit) { const rateLimitResult = await this.rateLimit.checkRequest(req); if (!rateLimitResult.allowed) { return this.rateLimit.handleRateLimitResponse(res, rateLimitResult); } // Set rate limit headers Object.entries(rateLimitResult.headers || {}).forEach(([key, value]) => { res.setHeader(key, value); }); } // Future features will be added here: // - API Firewall validation // - Threat detection analysis // - Security scanning // - Compliance checks next(); } catch (error) { if (this.config.onError) { this.config.onError(error); } // Fail open - allow request to continue if (this.config.debug) { console.error('SecKav middleware error:', error); } next(); } }; } /** * Get Next.js middleware with all enabled security features */ getNextMiddleware() { return async (req) => { try { // Rate limiting check (if enabled) if (this.config.features?.rateLimit && this.rateLimit) { const rateLimitResult = await this.rateLimit.checkNextRequest(req); if (!rateLimitResult.allowed) { return new Response(JSON.stringify({ error: 'Rate limited', retryAfter: rateLimitResult.retryAfter, }), { status: 429, headers: { 'Content-Type': 'application/json', ...rateLimitResult.headers, }, }); } } // Future features will be added here return null; // Allow request to continue } catch (error) { if (this.config.onError) { this.config.onError(error); } // Fail open return null; } }; } /** * Get individual modules for advanced usage */ getRateLimitModule() { return this.rateLimit || null; } getAuthenticationModule() { return this.authentication || null; } getOrganizationModule() { return this.organization || null; } getSecurityModule() { return this.security || null; } getEnhancedSecurityModule() { return this.enhancedSecurity || null; } getAnalyticsModule() { return this.analytics || null; } getComplianceModule() { return this.compliance || null; } getGitIntegrationModule() { return this.gitIntegration || null; } getEncryptionModule() { return this.encryption || null; } getMisconfigurationScannerModule() { return this.misconfigurationScanner || null; } /** * Direct access to misconfiguration scanning features */ get misconfigurationScanning() { if (!this.misconfigurationScanner) { throw new Error('Misconfiguration scanning module not enabled. Set features.misconfigurationScanning to true.'); } return this.misconfigurationScanner; } /** * Convenience methods for common operations */ // Authentication convenience methods async login(email, password) { if (!this.authentication) { throw new Error('Authentication module not enabled'); } return this.authentication.login(email, password); } async register(email, password, name) { if (!this.authentication) { throw new Error('Authentication module not enabled'); } return this.authentication.register(email, password, name); } async getProfile(token) { if (!this.authentication) { throw new Error('Authentication module not enabled'); } return this.authentication.getProfile(token); } // Organization convenience methods async createOrganization(token, name, description, domain) { if (!this.organization) { throw new Error('Organization module not enabled'); } return this.organization.createOrganization(token, name, description, domain); } async getOrganizations(token) { if (!this.organization) { throw new Error('Organization module not enabled'); } return this.organization.getOrganizations(token); } // Security convenience methods async getSecuritySettings(token) { if (!this.security) { throw new Error('Security module not enabled'); } return this.security.getSecuritySettings(token); } async updateIpWhitelist(token, ipAddresses) { if (!this.security) { throw new Error('Security module not enabled'); } return this.security.updateIpWhitelist(token, ipAddresses); } // Analytics convenience methods async getRealTimeMetrics(token) { if (!this.analytics) { throw new Error('Analytics module not enabled'); } return this.analytics.getRealTimeMetrics(token); } async getAnalytics(token, timeframe = '24h') { if (!this.analytics) { throw new Error('Analytics module not enabled'); } return this.analytics.getAnalytics(token, timeframe); } // Enhanced Security convenience methods async analyzeThreat(token, data) { if (!this.enhancedSecurity) { throw new Error('Enhanced Security module not enabled'); } return this.enhancedSecurity.analyzeThreat(token, data); } async analyzeAnomaly(token, requestData) { if (!this.enhancedSecurity) { throw new Error('Enhanced Security module not enabled'); } return this.enhancedSecurity.analyzeAnomaly(token, requestData); } async scanFile(token, file) { if (!this.enhancedSecurity) { throw new Error('Enhanced Security module not enabled'); } return this.enhancedSecurity.scanFile(token, file); } async getSecurityMetrics(token, timeRange = '24h') { if (!this.enhancedSecurity) { throw new Error('Enhanced Security module not enabled'); } return this.enhancedSecurity.getSecurityMetrics(token, timeRange); } async checkDDoSStatus(token, organizationId) { if (!this.enhancedSecurity) { throw new Error('Enhanced Security module not enabled'); } return this.enhancedSecurity.checkDDoSStatus(token, organizationId); } async getSecurityHealth(token) { if (!this.enhancedSecurity) { throw new Error('Enhanced Security module not enabled'); } return this.enhancedSecurity.getSecurityHealth(token); } // ==================== Compliance Module Methods ==================== /** * Generate a compliance report (GDPR, DPDP, CERT-IN) */ async generateComplianceReport(token, reportType, period) { if (!this.compliance) { throw new Error('Compliance module not enabled'); } return this.compliance.generateComplianceReport(token, reportType, period); } /** * Get compliance dashboard data */ async getComplianceDashboard(token) { if (!this.compliance) { throw new Error('Compliance module not enabled'); } return this.compliance.getComplianceDashboard(token); } /** * Scan OpenAPI/Swagger specification for security issues */ async scanApiSpecification(token, file) { if (!this.compliance) { throw new Error('Compliance module not enabled'); } return this.compliance.scanApiSpecification(token, file); } // ==================== Git Integration Module Methods ==================== /** * Test Git provider connection */ async testGitConnection(token, provider) { if (!this.gitIntegration) { throw new Error('Git Integration module not enabled'); } return this.gitIntegration.testConnection(token, provider); } /** * Get repositories from Git provider */ async getRepositories(token, provider, options = {}) { if (!this.gitIntegration) { throw new Error('Git Integration module not enabled'); } return this.gitIntegration.getRepositories(token, provider, options); } /** * Scan repository for security issues */ async scanRepository(token, provider, repositoryId, options = {}) { if (!this.gitIntegration) { throw new Error('Git Integration module not enabled'); } return this.gitIntegration.scanRepository(token, provider, repositoryId, options); } // ==================== Encryption Module Methods ==================== /** * Get encryption status for organization */ async getEncryptionStatus(token) { if (!this.encryption) { throw new Error('Encryption module not enabled'); } return this.encryption.getEncryptionStatus(token); } /** * Enable encryption for organization */ async enableEncryption(token, config) { if (!this.encryption) { throw new Error('Encryption module not enabled'); } return this.encryption.enableEncryption(token, config); } /** * Rotate encryption key manually */ async rotateEncryptionKey(token, reason = 'manual') { if (!this.encryption) { throw new Error('Encryption module not enabled'); } return this.encryption.rotateEncryptionKey(token, reason); } /** * Test encryption functionality */ async testEncryption(token, data, algorithm) { if (!this.encryption) { throw new Error('Encryption module not enabled'); } return this.encryption.testEncryption(token, data, algorithm); } // ==================== Misconfiguration Scanner Module Methods ==================== /** * Scan OpenAPI specification for security issues */ async scanOpenAPISpec(token, specContent, filename) { if (!this.misconfigurationScanner) { throw new Error('Misconfiguration scanner module not enabled'); } return this.misconfigurationScanner.scanOpenAPISpecWithToken(token, specContent, filename); } /** * Upload and scan configuration files */ async scanConfigurationFiles(token, files) { if (!this.misconfigurationScanner) { throw new Error('Misconfiguration scanner module not enabled'); } return this.misconfigurationScanner.uploadAndScanFilesWithToken(token, files); } /** * Get AI-powered security recommendations */ async getSecurityRecommendations(token, context) { if (!this.misconfigurationScanner) { throw new Error('Misconfiguration scanner module not enabled'); } return this.misconfigurationScanner.getSecurityRecommendationsWithToken(token, context); } /** * Configure LLM provider for enhanced scanning */ async configureLLMProvider(token, provider) { if (!this.misconfigurationScanner) { throw new Error('Misconfiguration scanner module not enabled'); } return this.misconfigurationScanner.configureLLMProvider(token, provider); } /** * Test LLM integration */ async testLLMIntegration(token, testPrompt) { if (!this.misconfigurationScanner) { throw new Error('Misconfiguration scanner module not enabled'); } return this.misconfigurationScanner.testLLMIntegrationWithToken(token, testPrompt); } /** * Perform quick security assessment */ async performQuickSecurityAssessment(token, assessment) { if (!this.misconfigurationScanner) { throw new Error('Misconfiguration scanner module not enabled'); } return this.misconfigurationScanner.performQuickAssessment(token, assessment); } /** * Generate security report from scan results */ async generateSecurityReport(token, options) { if (!this.misconfigurationScanner) { throw new Error('Misconfiguration scanner module not enabled'); } return this.misconfigurationScanner.generateSecurityReport(token, options); } /** * Get SDK information and enabled features */ getInfo() { return { version: '2.0.1', enabledFeatures: Object.entries(this.config.features) .filter(([, enabled]) => enabled) .map(([feature]) => feature), organization: this.config.organizationId, apiUrl: this.config.apiUrl, modules: { rateLimit: this.rateLimit?.getInfo() || null, authentication: this.authentication?.getInfo() || null, organization: this.organization?.getInfo() || null, security: this.security?.getInfo() || null, analytics: this.analytics?.getInfo() || null, enhancedSecurity: this.enhancedSecurity?.getInfo() || null, compliance: this.compliance ? { name: 'Compliance', version: '1.0.0' } : null, gitIntegration: this.gitIntegration ? { name: 'Git Integration', version: '1.0.0' } : null, encryption: this.encryption?.getInfo() || null, misconfigurationScanner: this.misconfigurationScanner?.getInfo() || null, }, }; } /** * Update configuration at runtime */ updateConfig(newConfig) { this.config = { ...this.config, ...newConfig }; // Reinitialize modules if needed if (newConfig.features?.rateLimit && !this.rateLimit) { this.rateLimit = new RateLimit_1.RateLimitModule({ apiUrl: this.config.apiUrl, organizationId: this.config.organizationId, apiKey: this.config.apiKey || '', // RateLimitModule will handle empty string timeout: this.config.timeout, onError: this.config.onError, }); } if (newConfig.features?.authentication && !this.authentication) { this.authentication = new Authentication_1.AuthenticationModule({ apiUrl: this.config.apiUrl, timeout: this.config.timeout, onError: this.config.onError, }); } if (newConfig.features?.organizationManagement && !this.organization) { this.organization = new Organization_1.OrganizationModule({ apiUrl: this.config.apiUrl, timeout: this.config.timeout, onError: this.config.onError, }); } if (newConfig.features?.security && !this.security) { this.security = new Security_1.SecurityModule({ apiUrl: this.config.apiUrl, timeout: this.config.timeout, onError: this.config.onError, }); } if (newConfig.features?.analytics && !this.analytics) { this.analytics = new Analytics_1.AnalyticsModule({ apiUrl: this.config.apiUrl, timeout: this.config.timeout, onError: this.config.onError, }); } } } exports.SecKavSDK = SecKavSDK; // Convenience functions for simple usage (backward compatibility) function createSecKavMiddleware(config) { const sdk = new SecKavSDK(config); return sdk.getExpressMiddleware(); } function createSecKavNextMiddleware(config) { const sdk = new SecKavSDK(config); return sdk.getNextMiddleware(); } //# sourceMappingURL=SecKavSDK.js.map