import type { CheckFinding, CheckReport } from "../core/types.js"; /** * Rule-based adversarial code checker. * Analyzes code content for correctness, security, and style issues. * Designed to catch "almost right but not quite" AI-generated code problems. */ interface CheckRule { id: string; category: "correctness" | "security" | "style" | "performance"; severity: "critical" | "warning" | "info"; pattern: RegExp; message: string; suggestion?: string; languages?: string[]; } const CHECK_RULES: CheckRule[] = [ // === Security === { id: "SEC001", category: "security", severity: "critical", pattern: /(?:exec|eval|system|child_process\.exec|Runtime\.getRuntime\(\)\.exec)\s*\(/, message: "Dangerous command execution detected — potential command injection", suggestion: "Use parameterized commands or avoid shell execution entirely", }, { id: "SEC002", category: "security", severity: "critical", pattern: /(?:password|secret|token|api_key|apikey|private_key)\s*[=:]\s*["'][^"']+["']/i, message: "Hardcoded credential or secret detected", suggestion: "Use environment variables or a secrets manager", }, { id: "SEC003", category: "security", severity: "critical", pattern: /(?:SELECT|INSERT|UPDATE|DELETE)\s+.*(?:\+\s*\w+|\$\{|f["'].*\{)/i, message: "Possible SQL injection — string concatenation in query", suggestion: "Use parameterized queries / prepared statements", }, { id: "SEC004", category: "security", severity: "warning", pattern: /(?:innerHTML|dangerouslySetInnerHTML|v-html)\s*[=:]|document\.write\s*\(/, message: "Direct HTML injection — potential XSS vulnerability", suggestion: "Sanitize input or use safe DOM APIs (textContent, text-only rendering)", }, { id: "SEC005", category: "security", severity: "warning", pattern: /(?:http:\/\/|verify\s*[:=]\s*false|rejectUnauthorized\s*:\s*false|NODE_TLS_REJECT_UNAUTHORIZED\s*=\s*['"]?0)/i, message: "Insecure connection or disabled TLS verification", suggestion: "Use HTTPS and verify TLS certificates", }, { id: "SEC006", category: "security", severity: "critical", pattern: /(?:chmod\s+777|0777|os\.chmod\([^,]+,\s*0o?777)/, message: "World-writable file permissions (777) — security risk", suggestion: "Use restrictive permissions (e.g., 755 or 644)", }, // === Correctness === { id: "COR001", category: "correctness", severity: "warning", pattern: /(?:==\s*null|!=\s*null|undefined\s*==|==\s*undefined)/, message: "Loose null/undefined comparison — may cause type coercion bugs", suggestion: "Use === null / !== null / ?? operator", }, { id: "COR002", category: "correctness", severity: "warning", pattern: /catch\s*\(\s*\w+\s*\)\s*\{\s*\}/, message: "Empty catch block — errors silently swallowed", suggestion: "Log the error at minimum; consider re-throwing or handling", }, { id: "COR003", category: "correctness", severity: "warning", pattern: /(?:\.length|\.size)\s*(?:===?|!==?)\s*0/, message: "Length check without null guard — will throw if variable is null/undefined", suggestion: "Add optional chaining (?.length) or null check first", }, { id: "COR004", category: "correctness", severity: "warning", pattern: /new\s+Date\s*\(\s*(?:["']\d{4}-\d{2}-\d{2}["'])\s*\)/, message: "Date parsing from string is timezone-dependent and unreliable", suggestion: "Use Date.UTC() or a date library for consistent parsing", }, { id: "COR005", category: "correctness", severity: "warning", pattern: /for\s*\(\s*var\s+\w+\s*(?:;|in|of)/, message: "var in loop — closure/scoping bug risk", suggestion: "Use let or const instead of var", }, { id: "COR006", category: "correctness", severity: "info", pattern: /TODO|FIXME|HACK|XXX|PLACEHOLDER|Lorem ipsum/i, message: "TODO/FIXME/placeholder marker — incomplete code", suggestion: "Complete the implementation or remove the marker", }, // === Style === { id: "STY001", category: "style", severity: "info", pattern: /console\.log\s*\(/, message: "console.log left in code", suggestion: "Remove debug logging or use a proper logging library", languages: ["javascript", "typescript"], }, { id: "STY002", category: "style", severity: "info", pattern: /(?:function\s+\w+\s*\([^)]*\)\s*\{[\s\S]{500,}?\})/, message: "Function may be too long (>500 chars) — consider refactoring", suggestion: "Break into smaller, focused functions", }, // === Performance === { id: "PERF001", category: "performance", severity: "warning", pattern: /(?:SELECT\s+\*\s+FROM|(?:find|query)\s*\(\s*\{\s*\}\s*\))/i, message: "Unbounded query — fetching all rows without limit", suggestion: "Add pagination or limit clause", }, { id: "PERF002", category: "performance", severity: "info", pattern: /(?:await\s+\w+\s+in\s+(?:a\s+)?for\s*\()/, message: "Sequential await in loop — potential for parallel execution", suggestion: "Consider Promise.all() for independent async operations", }, ]; /** * Analyze code content and return findings. */ export function analyzeCode(content: string, filePath: string, language?: string): CheckFinding[] { const findings: CheckFinding[] = []; const lines = content.split("\n"); for (const rule of CHECK_RULES) { if (rule.languages && language && !rule.languages.includes(language)) continue; for (let i = 0; i < lines.length; i++) { if (rule.pattern.test(lines[i])) { findings.push({ severity: rule.severity, category: rule.category, message: `[${rule.id}] ${rule.message}`, file: filePath, line: i + 1, suggestion: rule.suggestion, }); } } } return findings; } /** * Analyze multiple files and produce a report. */ export function generateReport(fileAnalyses: Array<{ path: string; content: string; language?: string }>): CheckReport { const findings: CheckFinding[] = []; for (const file of fileAnalyses) { findings.push(...analyzeCode(file.content, file.path, file.language)); } // Sort: critical first, then warning, then info const severityOrder = { critical: 0, warning: 1, info: 2 }; findings.sort((a, b) => severityOrder[a.severity] - severityOrder[b.severity]); return { findings, filesChecked: fileAnalyses.length, summary: { critical: findings.filter((f) => f.severity === "critical").length, warning: findings.filter((f) => f.severity === "warning").length, info: findings.filter((f) => f.severity === "info").length, }, }; } /** * Format a check report for terminal output. */ export function formatReport(report: CheckReport): string { const lines: string[] = []; lines.push(`\n 📋 Code Health Report — ${report.filesChecked} file(s) checked\n`); const icon = { critical: "🔴", warning: "🟡", info: "⚪" }; lines.push(` ${icon.critical} ${report.summary.critical} critical ${icon.warning} ${report.summary.warning} warning ${icon.info} ${report.summary.info} info\n`); if (report.findings.length === 0) { lines.push(" ✅ No issues found.\n"); return lines.join("\n"); } for (const f of report.findings) { lines.push(` ${icon[f.severity]} ${f.file}:${f.line ?? "?"}`); lines.push(` ${f.message}`); if (f.suggestion) { lines.push(` 💡 ${f.suggestion}`); } lines.push(""); } return lines.join("\n"); }