import * as path from 'path'; import { Finding, ScanResult, Severity, SEVERITY_COLORS, SEVERITY_ICONS } from './severity'; const RESET = '\x1b[0m'; const BOLD = '\x1b[1m'; const DIM = '\x1b[2m'; const WHITE = '\x1b[37m'; const GREEN = '\x1b[32m'; const YELLOW = '\x1b[33m'; const RED = '\x1b[31m'; const CYAN = '\x1b[36m'; // ============================================================ // Terminal Reporter // ============================================================ export function reportTerminal(result: ScanResult, quiet: boolean = false): string { const lines: string[] = []; lines.push(''); lines.push(`${BOLD}${WHITE} GhostPatch Security Scan Report${RESET}`); lines.push(`${DIM} ${'='.repeat(50)}${RESET}`); lines.push(''); // Summary lines.push(` ${DIM}Target:${RESET} ${result.target}`); lines.push(` ${DIM}Files:${RESET} ${result.filesScanned} scanned, ${result.filesSkipped} skipped`); lines.push(` ${DIM}Time:${RESET} ${result.durationMs}ms`); lines.push(` ${DIM}AI:${RESET} ${result.aiEnabled ? 'enabled' : 'disabled'}`); lines.push(''); // Severity breakdown const { bySeverity } = result.summary; const critCount = bySeverity[Severity.CRITICAL] || 0; const highCount = bySeverity[Severity.HIGH] || 0; const medCount = bySeverity[Severity.MEDIUM] || 0; const lowCount = bySeverity[Severity.LOW] || 0; const infoCount = bySeverity[Severity.INFO] || 0; lines.push(` ${SEVERITY_COLORS[Severity.CRITICAL]} CRITICAL ${RESET} ${critCount}`); lines.push(` ${SEVERITY_COLORS[Severity.HIGH]} HIGH ${RESET} ${highCount}`); lines.push(` ${SEVERITY_COLORS[Severity.MEDIUM]} MEDIUM ${RESET} ${medCount}`); lines.push(` ${SEVERITY_COLORS[Severity.LOW]} LOW ${RESET} ${lowCount}`); lines.push(` ${DIM} INFO ${RESET} ${infoCount}`); lines.push(''); if (result.summary.total === 0) { lines.push(` ${GREEN}${BOLD}No security issues found!${RESET}`); lines.push(''); return lines.join('\n'); } lines.push(` ${DIM}${'─'.repeat(60)}${RESET}`); lines.push(''); if (quiet) { for (const finding of result.findings) { const icon = SEVERITY_ICONS[finding.severity]; const color = SEVERITY_COLORS[finding.severity]; const relPath = path.relative(result.target, finding.filePath) || finding.filePath; lines.push(` ${color}${icon}${RESET} ${finding.title} ${DIM}${relPath}:${finding.line}${RESET}`); } } else { for (const finding of result.findings) { lines.push(formatFinding(finding, result.target)); } } lines.push(''); lines.push(` ${DIM}${'─'.repeat(60)}${RESET}`); lines.push(` ${BOLD}Total: ${result.summary.total} issue(s) found${RESET}`); if (critCount > 0) { lines.push(` ${RED}${BOLD}${critCount} critical issue(s) require immediate attention!${RESET}`); } lines.push(''); return lines.join('\n'); } function formatFinding(finding: Finding, basePath: string): string { const lines: string[] = []; const color = SEVERITY_COLORS[finding.severity]; const icon = SEVERITY_ICONS[finding.severity]; const relPath = path.relative(basePath, finding.filePath) || finding.filePath; lines.push(` ${color}${BOLD}${icon} ${finding.title}${RESET}`); lines.push(` ${DIM}${relPath}:${finding.line}${RESET}${finding.cwe ? ` ${DIM}${finding.cwe}${RESET}` : ''}${finding.aiEnhanced ? ` ${CYAN}[AI]${RESET}` : ''}`); lines.push(` ${finding.description}`); lines.push(''); if (finding.codeSnippet) { const snippetLines = finding.codeSnippet.split('\n'); for (const sl of snippetLines) { if (sl.startsWith('>')) { lines.push(` ${color}${sl}${RESET}`); } else { lines.push(` ${DIM}${sl}${RESET}`); } } lines.push(''); } if (finding.remediation) { lines.push(` ${GREEN}Fix: ${finding.remediation}${RESET}`); } lines.push(` ${DIM}${'─'.repeat(60)}${RESET}`); lines.push(''); return lines.join('\n'); } // ============================================================ // JSON Reporter // ============================================================ export function reportJSON(result: ScanResult): string { return JSON.stringify({ ghostpatch: { version: '1.0.0', scanDate: result.startTime.toISOString(), }, target: result.target, duration: result.durationMs, filesScanned: result.filesScanned, filesSkipped: result.filesSkipped, aiEnabled: result.aiEnabled, summary: result.summary, findings: result.findings.map(f => ({ id: f.id, ruleId: f.ruleId, title: f.title, description: f.description, severity: f.severity, confidence: f.confidence, location: { file: f.filePath, line: f.line, column: f.column, endLine: f.endLine, endColumn: f.endColumn, }, cwe: f.cwe, owasp: f.owasp, codeSnippet: f.codeSnippet, remediation: f.remediation, aiEnhanced: f.aiEnhanced || false, fingerprint: f.fingerprint, })), }, null, 2); } // ============================================================ // SARIF Reporter (Static Analysis Results Interchange Format) // ============================================================ export function reportSARIF(result: ScanResult): string { const sarif = { $schema: 'https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json', version: '2.1.0', runs: [{ tool: { driver: { name: 'GhostPatch', version: '1.0.0', informationUri: 'https://github.com/ghostpatch/ghostpatch', rules: getUniqueRules(result.findings), }, }, results: result.findings.map(f => ({ ruleId: f.ruleId, level: sarifLevel(f.severity), message: { text: f.description, }, locations: [{ physicalLocation: { artifactLocation: { uri: f.filePath.replace(/\\/g, '/'), }, region: { startLine: f.line, startColumn: f.column || 1, endLine: f.endLine || f.line, endColumn: f.endColumn, }, }, }], fingerprints: { 'ghostpatch/v1': f.fingerprint, }, fixes: f.remediation ? [{ description: { text: f.remediation }, }] : undefined, })), }], }; return JSON.stringify(sarif, null, 2); } function sarifLevel(severity: Severity): string { switch (severity) { case Severity.CRITICAL: case Severity.HIGH: return 'error'; case Severity.MEDIUM: return 'warning'; case Severity.LOW: case Severity.INFO: return 'note'; } } function getUniqueRules(findings: Finding[]) { const seen = new Set(); const rules: any[] = []; for (const f of findings) { if (!seen.has(f.ruleId)) { seen.add(f.ruleId); rules.push({ id: f.ruleId, shortDescription: { text: f.title }, fullDescription: { text: f.description }, help: { text: f.remediation || '' }, properties: { cwe: f.cwe, owasp: f.owasp, }, }); } } return rules; } // ============================================================ // HTML Reporter // ============================================================ export function reportHTML(result: ScanResult): string { const { bySeverity } = result.summary; return ` GhostPatch Security Report

GhostPatch Security Report

Scan completed ${result.startTime.toISOString()} | ${result.filesScanned} files scanned | ${result.durationMs}ms

${result.summary.total > 0 ? `
${chartSegment('critical', bySeverity[Severity.CRITICAL], result.summary.total)} ${chartSegment('high', bySeverity[Severity.HIGH], result.summary.total)} ${chartSegment('medium', bySeverity[Severity.MEDIUM], result.summary.total)} ${chartSegment('low', bySeverity[Severity.LOW], result.summary.total)} ${chartSegment('info', bySeverity[Severity.INFO], result.summary.total)}
` : ''}
${bySeverity[Severity.CRITICAL] || 0}
Critical
${bySeverity[Severity.HIGH] || 0}
High
${bySeverity[Severity.MEDIUM] || 0}
Medium
${bySeverity[Severity.LOW] || 0}
Low
${bySeverity[Severity.INFO] || 0}
Info
${result.findings.length === 0 ? '

No security issues found!

' : ''} ${result.findings.map(f => `
${escapeHtml(f.title)}${f.aiEnhanced ? 'AI' : ''} ${f.severity}
${escapeHtml(path.relative(result.target, f.filePath) || f.filePath)}:${f.line}${f.cwe ? ` | ${f.cwe}` : ''}${f.owasp ? ` | OWASP ${f.owasp}` : ''}
${escapeHtml(f.description)}
${f.codeSnippet ? `
${escapeHtml(f.codeSnippet)}
` : ''} ${f.remediation ? `
Fix: ${escapeHtml(f.remediation)}
` : ''}
`).join('\n')}
`; } function chartSegment(severity: string, count: number, total: number): string { if (!count || total === 0) return ''; const pct = (count / total) * 100; return `
`; } function escapeHtml(str: string): string { return str .replace(/&/g, '&') .replace(//g, '>') .replace(/"/g, '"') .replace(/'/g, '''); } // ============================================================ // Report dispatcher // ============================================================ export function generateReport( result: ScanResult, format: 'terminal' | 'json' | 'sarif' | 'html' = 'terminal', quiet: boolean = false, ): string { switch (format) { case 'json': return reportJSON(result); case 'sarif': return reportSARIF(result); case 'html': return reportHTML(result); case 'terminal': default: return reportTerminal(result, quiet); } }