Press n or j to go to the next uncovered block, b, p or k for the previous block.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 | /** * Backend Fix Service - Efficient Python backend integration * Calls Python API for AI-powered vulnerability fixing */ const axios = require('axios') const chalk = require('chalk') const fs = require('fs-extra') const path = require('path') const APIClient = require('./api-client') // Simple logger replacement for structlog const logger = { info: (...args) => console.log('[INFO]', ...args), error: (...args) => console.error('[ERROR]', ...args), warn: (...args) => console.warn('[WARN]', ...args), debug: (...args) => console.log('[DEBUG]', ...args) } class BackendFixService { constructor(config = {}) { this.config = config this.apiClient = new APIClient(config) this.baseUrl = config.apiUrl || 'https://api.vaultace.com' // Fix session tracking this.currentSession = null this.stats = { fixes_requested: 0, fixes_applied: 0, fixes_failed: 0, api_calls: 0 } } /** * Execute autonomous fixing via Python backend */ async executeAutonomousFix(repoPath, options = {}) { const startTime = Date.now() try { // Validate repository path const absolutePath = path.resolve(repoPath) if (!await fs.exists(absolutePath)) { throw new Error(`Repository path does not exist: ${absolutePath}`) } // Prepare fix request const fixRequest = { repository_path: absolutePath, severity_filter: options.severity || 'medium', approval_policy: options.approvePolicy || 'hybrid', max_fixes: parseInt(options.maxFixes) || 50, model: options.model || 'claude-sonnet-4', dry_run: options.dryRun || false, skip_tests: options.skipTests || false, branch_name: options.branch || `vaultace-fixes-${Date.now()}` } await logger.info('Starting autonomous fix via backend', { repository_path: absolutePath, options: fixRequest }) // Call Python backend API this.stats.api_calls++ const response = await this.apiClient.post('/api/v1/autonomous-fix', fixRequest) this.currentSession = response.fix_session_id await logger.info('Autonomous fix completed', { session_id: this.currentSession, fixes_applied: response.fixes_applied, fixes_pending: response.fixes_pending, duration_ms: Date.now() - startTime }) // Update stats this.stats.fixes_requested += response.fixes_generated this.stats.fixes_applied += response.fixes_applied this.stats.fixes_failed += response.fixes_failed return response } catch (error) { await logger.error('Autonomous fix failed', { repository_path: repoPath, error: error.message }) this.stats.fixes_failed++ // Handle specific error types if (error.response?.status === 402) { throw new Error('Autonomous fixing requires premium subscription. Upgrade at https://vaultace.com/pricing') } else if (error.response?.status === 429) { throw new Error('Rate limit exceeded. Please try again in a few minutes.') } else if (error.response?.status === 401) { throw new Error('Authentication required. Run: vaultace auth login') } throw new Error(`Autonomous fixing failed: ${error.message}`) } } /** * Generate fix for single vulnerability */ async generateSingleFix(vulnerabilityId, options = {}) { try { const fixRequest = { vulnerability_id: vulnerabilityId, model: options.model || 'claude-sonnet-4', apply_immediately: options.apply || false } await logger.info('Generating single fix via backend', { vulnerability_id: vulnerabilityId, apply_immediately: fixRequest.apply_immediately }) this.stats.api_calls++ const response = await this.apiClient.post('/api/v1/fix-single', fixRequest) if (response.status === 'applied') { this.stats.fixes_applied++ } else { this.stats.fixes_requested++ } return response } catch (error) { this.stats.fixes_failed++ await logger.error('Single fix generation failed', { vulnerability_id: vulnerabilityId, error: error.message }) throw new Error(`Fix generation failed: ${error.message}`) } } /** * Get fixing capabilities from backend */ async getFixCapabilities() { try { this.stats.api_calls++ const capabilities = await this.apiClient.get('/api/v1/fix-capabilities') await logger.info('Retrieved fix capabilities', { subscription_tier: capabilities.subscription_tier, monthly_limit: capabilities.monthly_fix_limit, fixes_used: capabilities.fixes_used_this_month }) return capabilities } catch (error) { await logger.error('Failed to get fix capabilities', { error: error.message }) throw new Error(`Failed to get capabilities: ${error.message}`) } } /** * Apply pending fixes after manual approval */ async applyPendingFixes(fixSessionId, approvedFixIds) { try { const request = { fix_session_id: fixSessionId, approved_fix_ids: approvedFixIds } await logger.info('Applying approved fixes', { session_id: fixSessionId, approved_count: approvedFixIds.length }) this.stats.api_calls++ const response = await this.apiClient.post('/api/v1/apply-approved-fixes', request) this.stats.fixes_applied += response.fixes_applied return response } catch (error) { await logger.error('Failed to apply approved fixes', { session_id: fixSessionId, error: error.message }) throw new Error(`Failed to apply fixes: ${error.message}`) } } /** * Get current session details */ getCurrentSession() { return this.currentSession } /** * Get service statistics */ getStats() { return { ...this.stats, success_rate: this.stats.fixes_requested > 0 ? ((this.stats.fixes_applied / this.stats.fixes_requested) * 100).toFixed(1) + '%' : '0%', current_session: this.currentSession } } /** * Reset statistics */ resetStats() { this.stats = { fixes_requested: 0, fixes_applied: 0, fixes_failed: 0, api_calls: 0 } this.currentSession = null } /** * Check if user has autonomous fixing access */ async checkFixAccess() { try { const capabilities = await this.getFixCapabilities() return { hasAccess: capabilities.monthly_fix_limit > 0, tier: capabilities.subscription_tier, monthlyLimit: capabilities.monthly_fix_limit, used: capabilities.fixes_used_this_month, remaining: capabilities.monthly_fix_limit - capabilities.fixes_used_this_month } } catch (error) { return { hasAccess: false, error: error.message } } } } /** * Lightweight fix result formatter for CLI display */ class FixResultFormatter { static formatSummary(fixResults) { const summary = fixResults.summary || {} return ` ${chalk.bold.cyan('📊 AUTONOMOUS FIX RESULTS')} ${chalk.cyan('━'.repeat(40))} ${chalk.green('✅ Applied:')} ${fixResults.fixes_applied} ${chalk.yellow('⏳ Pending:')} ${fixResults.fixes_pending} ${chalk.red('❌ Failed:')} ${fixResults.fixes_failed} ${chalk.blue('🎯 Total Vulns:')} ${fixResults.total_vulnerabilities} ${chalk.bold('Severity Breakdown:')} ${this.formatSeverityBreakdown(summary.severity_breakdown)} ` } static formatSeverityBreakdown(breakdown = {}) { return Object.entries(breakdown) .map(([severity, count]) => { const color = this.getSeverityColor(severity) return ` ${color}${severity}: ${count}` }) .join('\n') } static formatFixDetails(fix) { const confidenceColor = fix.confidence >= 0.9 ? chalk.green : fix.confidence >= 0.7 ? chalk.yellow : chalk.red return ` ${chalk.bold('Fix Details:')} ${chalk.bold('Type:')} ${fix.vulnerability_type} ${chalk.bold('File:')} ${fix.file_path} ${chalk.bold('Confidence:')} ${confidenceColor((fix.confidence * 100).toFixed(1) + '%')} ${chalk.bold('Risk:')} ${this.getRiskColor(fix.risk_level)(fix.risk_level)} ${chalk.bold('Description:')} ${fix.description} ${chalk.bold('Code Changes:')} ${chalk.red('- ' + fix.original_code)} ${chalk.green('+ ' + fix.fixed_code)} ` } static getSeverityColor(severity) { const colors = { critical: chalk.red, high: chalk.yellow, medium: chalk.blue, low: chalk.gray } return colors[severity] || chalk.gray } static getRiskColor(risk) { const colors = { high: chalk.red, medium: chalk.yellow, low: chalk.green } return colors[risk] || chalk.gray } } module.exports = { BackendFixService, FixResultFormatter } |