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

601 lines 22.1 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.MisconfigurationScannerModule = void 0; const axios_1 = __importDefault(require("axios")); class MisconfigurationScannerModule { constructor(config) { this.config = config; } /** * Scan OpenAPI/Swagger specification for security issues */ async scanOpenAPISpec(specContent, filename) { try { const response = await axios_1.default.post(`${this.config.apiUrl}/api/v1/scanner/openapi`, { specContent, filename }, { headers: { 'Content-Type': 'application/json', }, timeout: this.config.timeout || 30000, }); return response.data; } catch (error) { if (this.config.onError) { this.config.onError(error); } throw new Error(error.response?.data?.error || 'Failed to scan OpenAPI specification'); } } /** * Legacy method for backward compatibility */ async scanOpenAPISpecWithToken(token, specContent, filename) { try { const response = await axios_1.default.post(`${this.config.apiUrl}/api/v1/scanner/openapi`, { specContent, filename }, { headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json', }, timeout: this.config.timeout || 30000, }); return { success: true, data: response.data.data, message: 'OpenAPI specification scanned successfully', }; } catch (error) { if (this.config.onError) { this.config.onError(error); } return { success: false, error: error.response?.data?.error || 'Failed to scan OpenAPI specification', message: error.response?.data?.message || 'An error occurred', }; } } /** * Upload and scan configuration files */ async uploadAndScanFiles(files) { try { const response = await axios_1.default.post(`${this.config.apiUrl}/api/v1/scanner/upload`, { files }, { headers: { 'Content-Type': 'application/json', }, timeout: this.config.timeout || 60000, }); return response.data; } catch (error) { if (this.config.onError) { this.config.onError(error); } throw new Error(error.response?.data?.error || 'Failed to scan files'); } } /** * Legacy method for backward compatibility */ async uploadAndScanFilesWithToken(token, files) { try { const formData = new FormData(); files.forEach((file, index) => { const blob = new Blob([file.content], { type: 'text/plain' }); formData.append('files', blob, file.name); }); const response = await axios_1.default.post(`${this.config.apiUrl}/api/v1/scanner/upload`, formData, { headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'multipart/form-data', }, timeout: this.config.timeout || 60000, }); return { success: true, data: response.data.data, message: `${files.length} files scanned successfully`, }; } catch (error) { if (this.config.onError) { this.config.onError(error); } return { success: false, error: error.response?.data?.error || 'Failed to scan files', message: error.response?.data?.message || 'An error occurred', }; } } /** * Get AI-powered security recommendations */ async getSecurityRecommendations(context) { try { const response = await axios_1.default.post(`${this.config.apiUrl}/api/v1/scanner/recommendations`, context, { headers: { 'Content-Type': 'application/json', }, timeout: this.config.timeout || 30000, }); return response.data; } catch (error) { if (this.config.onError) { this.config.onError(error); } throw new Error(error.response?.data?.error || 'Failed to get security recommendations'); } } /** * Legacy method for backward compatibility */ async getSecurityRecommendationsWithToken(token, context) { try { const response = await axios_1.default.post(`${this.config.apiUrl}/api/v1/scanner/recommendations`, context, { headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json', }, timeout: this.config.timeout || 45000, }); return { success: true, data: response.data.data, message: 'Security recommendations generated successfully', }; } catch (error) { if (this.config.onError) { this.config.onError(error); } return { success: false, error: error.response?.data?.error || 'Failed to get security recommendations', message: error.response?.data?.message || 'An error occurred', }; } } /** * Configure LLM provider (modern method) */ async configureLLM(provider) { try { const response = await axios_1.default.post(`${this.config.apiUrl}/api/v1/scanner/llm/configure`, provider, { headers: { 'Content-Type': 'application/json', }, timeout: this.config.timeout || 15000, }); return { success: true, data: response.data, message: 'LLM provider configured successfully', }; } catch (error) { if (this.config.onError) { this.config.onError(error); } throw new Error(error.response?.data?.error || 'Failed to configure LLM provider'); } } /** * Test LLM integration (modern method) */ async testLLMIntegration(options = {}) { try { const response = await axios_1.default.post(`${this.config.apiUrl}/api/v1/scanner/llm/test`, { prompt: options.prompt || 'Test prompt for API security analysis' }, { headers: { 'Content-Type': 'application/json', }, timeout: this.config.timeout || 30000, }); return { response: response.data.response || 'Test completed', success: true }; } catch (error) { if (this.config.onError) { this.config.onError(error); } throw new Error(error.response?.data?.error || 'LLM integration test failed'); } } /** * Get scan history (modern method) */ async getScanHistory(options = {}) { try { const { page = 1, limit = 20, type } = options; const params = new URLSearchParams({ page: page.toString(), limit: limit.toString(), ...(type && { type }) }); const response = await axios_1.default.get(`${this.config.apiUrl}/api/v1/scanner/history?${params}`, { headers: { 'Content-Type': 'application/json', }, timeout: this.config.timeout || 10000, }); return response.data; } catch (error) { if (this.config.onError) { this.config.onError(error); } throw new Error(error.response?.data?.error || 'Failed to get scan history'); } } /** * Generate security report (modern method) */ async generateReport(options) { try { const { scanIds, format = 'json', includeRemediation = true } = options; const response = await axios_1.default.post(`${this.config.apiUrl}/api/v1/scanner/report`, { scanIds, format, includeRemediation }, { headers: { 'Content-Type': 'application/json', }, timeout: this.config.timeout || 30000, }); return response.data; } catch (error) { if (this.config.onError) { this.config.onError(error); } throw new Error(error.response?.data?.error || 'Failed to generate security report'); } } /** * Quick security assessment (modern method) */ async quickAssessment(options) { try { const response = await axios_1.default.post(`${this.config.apiUrl}/api/v1/scanner/quick-assessment`, options, { headers: { 'Content-Type': 'application/json', }, timeout: this.config.timeout || 30000, }); return response.data; } catch (error) { if (this.config.onError) { this.config.onError(error); } throw new Error(error.response?.data?.error || 'Failed to perform quick assessment'); } } /** * Start monitoring (modern method) */ async startMonitoring(options) { try { const response = await axios_1.default.post(`${this.config.apiUrl}/api/v1/scanner/monitor`, options, { headers: { 'Content-Type': 'application/json', }, timeout: this.config.timeout || 15000, }); return response.data; } catch (error) { if (this.config.onError) { this.config.onError(error); } throw new Error(error.response?.data?.error || 'Failed to start monitoring'); } } /** * Configure LLM provider for enhanced scanning (legacy method) */ async configureLLMProvider(token, provider) { try { const response = await axios_1.default.post(`${this.config.apiUrl}/api/v1/scanner/llm/configure`, provider, { headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json', }, timeout: this.config.timeout || 10000, }); return { success: true, data: response.data.data, message: `LLM provider ${provider.name} configured successfully`, }; } catch (error) { if (this.config.onError) { this.config.onError(error); } return { success: false, error: error.response?.data?.error || 'Failed to configure LLM provider', message: error.response?.data?.message || 'An error occurred', }; } } /** * Test LLM integration (legacy method) */ async testLLMIntegrationWithToken(token, testPrompt) { try { const response = await axios_1.default.post(`${this.config.apiUrl}/api/v1/scanner/llm/test`, { prompt: testPrompt }, { headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json', }, timeout: this.config.timeout || 30000, }); return { success: true, data: response.data.data, message: 'LLM integration test completed', }; } catch (error) { if (this.config.onError) { this.config.onError(error); } return { success: false, error: error.response?.data?.error || 'LLM integration test failed', message: error.response?.data?.message || 'An error occurred', }; } } /** * Get scan history with pagination (legacy method) */ async getScanHistoryWithToken(token, options = {}) { try { const { page = 1, limit = 20, type } = options; const params = new URLSearchParams({ page: page.toString(), limit: limit.toString(), ...(type && { type }) }); const response = await axios_1.default.get(`${this.config.apiUrl}/api/v1/scanner/history?${params}`, { headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json', }, timeout: this.config.timeout || 10000, }); return { success: true, data: response.data.data, message: 'Scan history retrieved successfully', }; } catch (error) { if (this.config.onError) { this.config.onError(error); } return { success: false, error: error.response?.data?.error || 'Failed to get scan history', message: error.response?.data?.message || 'An error occurred', }; } } /** * Get specific scan result by ID */ async getScanResult(token, scanId) { try { const response = await axios_1.default.get(`${this.config.apiUrl}/api/v1/scanner/scan/${scanId}`, { headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json', }, timeout: this.config.timeout || 10000, }); return { success: true, data: response.data.data, message: 'Scan result retrieved successfully', }; } catch (error) { if (this.config.onError) { this.config.onError(error); } return { success: false, error: error.response?.data?.error || 'Failed to get scan result', message: error.response?.data?.message || 'An error occurred', }; } } /** * Generate comprehensive security report */ async generateSecurityReport(token, options) { try { const { scanIds, format = 'json', includeRemediation = true } = options; const response = await axios_1.default.post(`${this.config.apiUrl}/api/v1/scanner/report`, { scanIds, format, includeRemediation }, { headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json', }, timeout: this.config.timeout || 30000, }); return { success: true, data: format === 'json' ? response.data.data : response.data, message: 'Security report generated successfully', }; } catch (error) { if (this.config.onError) { this.config.onError(error); } return { success: false, error: error.response?.data?.error || 'Failed to generate security report', message: error.response?.data?.message || 'An error occurred', }; } } /** * Quick security assessment - Combines multiple scans */ async performQuickAssessment(token, assessment) { try { const results = { openApiScans: [], configScans: [], recommendations: null }; // Scan OpenAPI specs if (assessment.openApiSpecs) { for (const spec of assessment.openApiSpecs) { const scanResult = await this.scanOpenAPISpecWithToken(token, spec.content, spec.filename); if (scanResult.success) { results.openApiScans.push(scanResult.data); } } } // Scan config files if (assessment.configFiles) { const configScanResult = await this.uploadAndScanFilesWithToken(token, assessment.configFiles); if (configScanResult.success) { results.configScans.push(configScanResult.data); } } // Generate recommendations if requested if (assessment.generateRecommendations) { const allIssues = [ ...results.openApiScans.flatMap((scan) => scan.issues), ...results.configScans.flatMap((scan) => scan.issues) ]; const recommendationsResult = await this.getSecurityRecommendationsWithToken(token, { currentIssues: allIssues, apiSpecs: assessment.openApiSpecs?.map(spec => spec.filename), configFiles: assessment.configFiles?.map(file => file.name) }); if (recommendationsResult.success) { results.recommendations = recommendationsResult.data; } } // Calculate overall metrics const allScans = [...results.openApiScans, ...results.configScans]; const totalIssues = allScans.reduce((sum, scan) => sum + scan.summary.totalIssues, 0); const avgScore = allScans.reduce((sum, scan) => sum + scan.securityScore, 0) / allScans.length; return { success: true, data: { ...results, summary: { totalScans: allScans.length, totalIssues, averageSecurityScore: Math.round(avgScore * 100) / 100, assessmentCompleted: new Date().toISOString() } }, message: 'Quick security assessment completed successfully', }; } catch (error) { if (this.config.onError) { this.config.onError(error); } return { success: false, error: 'Failed to perform quick security assessment', message: error.message || 'An error occurred during assessment', }; } } /** * Scan from file paths (Node.js environments) */ async scanFromFilePaths(token, filePaths) { // Check if we're in a browser environment if (typeof globalThis !== 'undefined' && typeof globalThis.window !== 'undefined') { return { success: false, error: 'File path scanning is not available in browser environments', message: 'Use uploadAndScanFiles() instead' }; } try { const fs = require('fs').promises; const path = require('path'); const files = await Promise.all(filePaths.map(async (filePath) => { const content = await fs.readFile(filePath, 'utf8'); const name = path.basename(filePath); return { name, content }; })); return await this.uploadAndScanFilesWithToken(token, files); } catch (error) { if (this.config.onError) { this.config.onError(error); } return { success: false, error: 'Failed to scan files from paths', message: error.message || 'An error occurred', }; } } /** * Get scanner information and capabilities */ getInfo() { return { name: 'Misconfiguration Scanner', version: '1.0.0', capabilities: [ 'OpenAPI/Swagger specification scanning', 'Configuration file security analysis', 'LLM-powered deep analysis (GPT-4/Claude)', 'Human-readable security feedback', 'Auto-remediation suggestions', 'Compliance assessment (OWASP, PCI, GDPR, HIPAA)', 'Security report generation (JSON/HTML/Markdown)', 'Historical scan tracking', 'Quick security assessments' ], supportedFormats: [ 'OpenAPI 3.x (JSON/YAML)', 'Swagger 2.x (JSON/YAML)', 'Environment files (.env)', 'Docker configurations', 'Kubernetes manifests', 'JavaScript/TypeScript configs', 'Custom configuration files' ], llmProviders: ['OpenAI GPT-4', 'Anthropic Claude', 'Local models'], apiUrl: this.config.apiUrl }; } } exports.MisconfigurationScannerModule = MisconfigurationScannerModule; exports.default = MisconfigurationScannerModule; //# sourceMappingURL=MisconfigurationScanner.js.map