All files / utils report-generator.js

0% Statements 0/83
0% Branches 0/35
0% Functions 0/23
0% Lines 0/80

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         
/**
 * Report Generator
 * Generate vulnerability reports in various formats
 */
 
const chalk = require('chalk')
const { table } = require('table')
 
class ReportGenerator {
  constructor(format = 'table') {
    this.format = format.toLowerCase()
  }
 
  async generate(scanResults) {
    const { vulnerabilities, stats } = scanResults
    
    switch (this.format) {
      case 'table':
        return this.generateTableReport(vulnerabilities, stats)
      case 'json':
        return this.generateJsonReport(scanResults)
      case 'csv':
        return this.generateCsvReport(vulnerabilities, stats)
      case 'sarif':
        return this.generateSarifReport(scanResults)
      default:
        throw new Error(`Unsupported format: ${this.format}`)
    }
  }
 
  generateTableReport(vulnerabilities, stats) {
    let output = []
    
    if (vulnerabilities.length === 0) {
      output.push(chalk.green('✅ No vulnerabilities found!'))
      output.push('')
      output.push(`Scanned ${stats.filesScanned} files (${stats.linesScanned.toLocaleString()} lines) in ${stats.scanDuration}ms`)
      return output.join('\n')
    }
    
    // Group by severity
    const severityGroups = {
      critical: vulnerabilities.filter(v => v.severity === 'critical'),
      high: vulnerabilities.filter(v => v.severity === 'high'),
      medium: vulnerabilities.filter(v => v.severity === 'medium'),
      low: vulnerabilities.filter(v => v.severity === 'low'),
      info: vulnerabilities.filter(v => v.severity === 'info')
    }
    
    // Header
    output.push(chalk.bold.red('🚨 Security Vulnerabilities Found\n'))
    
    // Summary
    const totalVulns = vulnerabilities.length
    output.push(`Found ${chalk.bold(totalVulns)} vulnerabilities:`)
    output.push(`${chalk.red('🔴 Critical:')} ${severityGroups.critical.length}`)
    output.push(`${chalk.yellow('🟡 High:')} ${severityGroups.high.length}`)
    output.push(`${chalk.blue('đŸ”ĩ Medium:')} ${severityGroups.medium.length}`)
    output.push(`${chalk.gray('âšĒ Low:')} ${severityGroups.low.length}`)
    if (severityGroups.info.length > 0) {
      output.push(`${chalk.cyan('â„šī¸  Info:')} ${severityGroups.info.length}`)
    }
    output.push('')
    
    // Detailed vulnerabilities
    const severityOrder = ['critical', 'high', 'medium', 'low', 'info']
    
    severityOrder.forEach(severity => {
      const vulns = severityGroups[severity]
      if (vulns.length === 0) return
      
      const severityColor = {
        critical: chalk.red.bold,
        high: chalk.yellow.bold,
        medium: chalk.blue.bold,
        low: chalk.gray.bold,
        info: chalk.cyan.bold
      }[severity]
      
      output.push(severityColor(`${severity.toUpperCase()} SEVERITY`))
      output.push('─'.repeat(50))
      
      const tableData = [[
        chalk.bold('File'),
        chalk.bold('Line'),
        chalk.bold('Type'),
        chalk.bold('Message')
      ]]
      
      vulns.forEach(vuln => {
        tableData.push([
          vuln.file,
          vuln.line.toString(),
          vuln.type.replace(/_/g, ' '),
          vuln.message
        ])
      })
      
      output.push(table(tableData, {
        header: {
          alignment: 'left',
          content: severityColor(`${severity.toUpperCase()} VULNERABILITIES`)
        }
      }))
      
      output.push('')
    })
    
    return output.join('\n')
  }
 
  generateJsonReport(scanResults) {
    return JSON.stringify(scanResults, null, 2)
  }
 
  generateCsvReport(vulnerabilities, stats) {
    const headers = [
      'File',
      'Line',
      'Type',
      'Severity', 
      'Message',
      'Description',
      'Code'
    ]
    
    const rows = [headers.join(',')]
    
    vulnerabilities.forEach(vuln => {
      const row = [
        this.escapeCsvField(vuln.file),
        vuln.line,
        this.escapeCsvField(vuln.type),
        vuln.severity,
        this.escapeCsvField(vuln.message),
        this.escapeCsvField(vuln.description || ''),
        this.escapeCsvField(vuln.code || '')
      ]
      rows.push(row.join(','))
    })
    
    // Add stats as comment
    rows.push(`# Scan Statistics`)
    rows.push(`# Files Scanned: ${stats.filesScanned}`)
    rows.push(`# Lines Scanned: ${stats.linesScanned}`)
    rows.push(`# Scan Duration: ${stats.scanDuration}ms`)
    
    return rows.join('\n')
  }
 
  generateSarifReport(scanResults) {
    const { vulnerabilities, stats } = scanResults
    
    const sarif = {
      $schema: 'https://json.schemastore.org/sarif-2.1.0.json',
      version: '2.1.0',
      runs: [
        {
          tool: {
            driver: {
              name: 'Vaultace',
              informationUri: 'https://vaultace.com',
              version: '1.0.0',
              rules: this.generateSarifRules(vulnerabilities)
            }
          },
          results: vulnerabilities.map(vuln => ({
            ruleId: vuln.type,
            level: this.mapSeverityToSarifLevel(vuln.severity),
            message: {
              text: vuln.message
            },
            locations: [
              {
                physicalLocation: {
                  artifactLocation: {
                    uri: vuln.file
                  },
                  region: {
                    startLine: vuln.line,
                    startColumn: 1,
                    snippet: {
                      text: vuln.code || ''
                    }
                  }
                }
              }
            ]
          })),
          invocations: [
            {
              executionSuccessful: true,
              endTimeUtc: new Date().toISOString(),
              properties: {
                filesScanned: stats.filesScanned,
                linesScanned: stats.linesScanned,
                scanDuration: stats.scanDuration
              }
            }
          ]
        }
      ]
    }
    
    return JSON.stringify(sarif, null, 2)
  }
 
  generateSarifRules(vulnerabilities) {
    const uniqueTypes = [...new Set(vulnerabilities.map(v => v.type))]
    
    return uniqueTypes.map(type => ({
      id: type,
      name: type.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase()),
      shortDescription: {
        text: this.getRuleDescription(type)
      },
      fullDescription: {
        text: this.getRuleDescription(type)
      },
      defaultConfiguration: {
        level: this.getDefaultSeverityForType(type)
      }
    }))
  }
 
  mapSeverityToSarifLevel(severity) {
    switch (severity) {
      case 'critical':
        return 'error'
      case 'high':
        return 'error'
      case 'medium':
        return 'warning'
      case 'low':
        return 'note'
      case 'info':
        return 'note'
      default:
        return 'warning'
    }
  }
 
  getDefaultSeverityForType(type) {
    const severityMap = {
      sql_injection: 'error',
      command_injection: 'error',
      exposed_secret: 'error',
      xss: 'warning',
      path_traversal: 'warning',
      ai_generated_code: 'note',
      prompt_injection: 'error'
    }
    
    return severityMap[type] || 'warning'
  }
 
  getRuleDescription(type) {
    const descriptions = {
      sql_injection: 'Dynamic SQL queries with user input can lead to data theft or corruption',
      xss: 'Unescaped user input in HTML can execute malicious scripts',
      exposed_secret: 'Hardcoded credentials in source code pose security risks',
      command_injection: 'Dynamic command execution can lead to system compromise',
      path_traversal: 'File path manipulation can access unauthorized files',
      ai_generated_code: 'AI-generated code may contain subtle security vulnerabilities',
      prompt_injection: 'AI prompt manipulation can bypass security controls'
    }
    
    return descriptions[type] || 'Security vulnerability detected'
  }
 
  escapeCsvField(field) {
    if (typeof field !== 'string') {
      field = String(field)
    }
    
    // Escape double quotes and wrap in quotes if needed
    if (field.includes(',') || field.includes('"') || field.includes('\n')) {
      return '"' + field.replace(/"/g, '""') + '"'
    }
    
    return field
  }
}
 
module.exports = ReportGenerator