File size: 7,697 Bytes
7bedc79
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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");
}