Spaces:
Sleeping
Sleeping
feat: add confidence scores, multi-language support, and export
Browse files- main.py +163 -80
- templates/index.html +72 -0
main.py
CHANGED
|
@@ -27,13 +27,15 @@ def serve_frontend():
|
|
| 27 |
class ReviewRequest(BaseModel):
|
| 28 |
code: str
|
| 29 |
language: str
|
|
|
|
|
|
|
| 30 |
|
| 31 |
@app.post("/api/review")
|
| 32 |
async def review_code(request: ReviewRequest):
|
| 33 |
-
"""Analyze code and return ALL bug findings"""
|
| 34 |
try:
|
| 35 |
code = request.code.strip()
|
| 36 |
-
lang = request.language.lower()
|
| 37 |
|
| 38 |
if not code:
|
| 39 |
raise HTTPException(status_code=400, detail="Code cannot be empty")
|
|
@@ -42,94 +44,160 @@ async def review_code(request: ReviewRequest):
|
|
| 42 |
if len(code) > 5000:
|
| 43 |
raise HTTPException(status_code=400, detail="Code exceeds 5000 characters")
|
| 44 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
# Local pattern-based analysis - returns ALL bugs, not just first
|
| 46 |
results = analyze_code_comprehensively(code, lang)
|
| 47 |
|
| 48 |
# Return the highest severity bug (or first bug if user wants single response)
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
}
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
"
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
}
|
| 67 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
except HTTPException:
|
| 69 |
raise
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
except Exception as e:
|
|
|
|
| 71 |
return JSONResponse(
|
| 72 |
status_code=500,
|
| 73 |
-
content={"error": str(e)}
|
| 74 |
)
|
| 75 |
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
code_lower = code.lower()
|
| 80 |
code_no_space = code.lower().replace(' ', '')
|
| 81 |
lines = code.split('\n')
|
| 82 |
|
| 83 |
# ============ CRITICAL SECURITY BUGS (Severity 5) ============
|
| 84 |
|
| 85 |
-
# SQL Injection
|
| 86 |
if ('f"' in code or "f'" in code) and any(sql in code_lower for sql in ['select', 'insert', 'delete', 'update', 'from', 'where']) and '{' in code and '}' in code:
|
| 87 |
bugs.append({
|
| 88 |
"type": "bug", "category": "security", "severity": 5, "line_hint": 3,
|
| 89 |
"comment": "SQL injection: f-string with variable interpolation in SQL query.",
|
| 90 |
-
"fix": "Use parameterized queries: cursor.execute('SELECT * FROM users WHERE id = ?', (uid,))"
|
|
|
|
|
|
|
| 91 |
})
|
| 92 |
|
| 93 |
# Command Injection
|
| 94 |
-
if re.search(r'(os\.system|subprocess|popen|shell=true)\s*\(.*f["\']|
|
| 95 |
bugs.append({
|
| 96 |
"type": "bug", "category": "security", "severity": 5, "line_hint": 2,
|
| 97 |
"comment": "Command injection: User input directly in shell command.",
|
| 98 |
-
"fix": "Use subprocess with args as list: subprocess.run(['ls', filename], shell=False)"
|
|
|
|
|
|
|
| 99 |
})
|
| 100 |
|
| 101 |
-
# Hardcoded
|
| 102 |
if re.search(r'(password|passwd|pwd|secret|credential)\s*[=:]\s*["\'][^"\']{6,}["\']', code, re.I):
|
| 103 |
bugs.append({
|
| 104 |
"type": "bug", "category": "security", "severity": 5, "line_hint": 2,
|
| 105 |
"comment": "Hardcoded password/credential detected.",
|
| 106 |
-
"fix": "Use environment variables: os.getenv('DB_PASSWORD')"
|
|
|
|
|
|
|
| 107 |
})
|
| 108 |
|
| 109 |
-
# Code execution
|
| 110 |
if re.search(r'\b(eval|exec|compile)\s*\(', code) or 'pickle.load' in code or 'yaml.load(' in code:
|
| 111 |
bugs.append({
|
| 112 |
"type": "bug", "category": "security", "severity": 5, "line_hint": 2,
|
| 113 |
"comment": "Arbitrary code execution: eval/exec/pickle are unsafe with untrusted data.",
|
| 114 |
-
"fix": "Use: json.loads(), ast.literal_eval(), or safe alternatives"
|
|
|
|
|
|
|
| 115 |
})
|
| 116 |
|
| 117 |
# ============ HIGH SEVERITY SECURITY BUGS (Severity 4) ============
|
| 118 |
|
| 119 |
-
# Hardcoded API keys
|
| 120 |
-
if re.search(r'(api_key|apikey|secret_key|private_key|token|auth_token|bearer|sk_|pk_)\s*[=:]\s*["\'][a-zA-Z0-9_\-]
|
| 121 |
bugs.append({
|
| 122 |
"type": "bug", "category": "security", "severity": 4, "line_hint": 1,
|
| 123 |
"comment": "Hardcoded API key/token detected.",
|
| 124 |
-
"fix": "api_key = os.getenv('API_KEY')"
|
|
|
|
|
|
|
| 125 |
})
|
| 126 |
|
| 127 |
-
# XSS vulnerability
|
| 128 |
if lang == 'javascript' and re.search(r'\.innerHTML\s*=|\.eval\(|dangerouslySetInnerHTML', code):
|
| 129 |
bugs.append({
|
| 130 |
"type": "bug", "category": "security", "severity": 4, "line_hint": 2,
|
| 131 |
"comment": "XSS vulnerability: Setting innerHTML with user data can execute scripts.",
|
| 132 |
-
"fix": "Use .textContent or sanitize HTML: DOMPurify.sanitize()"
|
|
|
|
|
|
|
| 133 |
})
|
| 134 |
|
| 135 |
# Insecure random
|
|
@@ -137,17 +205,21 @@ def analyze_code_comprehensively(code: str, lang: str) -> list:
|
|
| 137 |
bugs.append({
|
| 138 |
"type": "bug", "category": "security", "severity": 4, "line_hint": 2,
|
| 139 |
"comment": "Weak random number generator for security purposes.",
|
| 140 |
-
"fix": "Use: secrets.token_hex() or os.urandom() for cryptographic randomness"
|
|
|
|
|
|
|
| 141 |
})
|
| 142 |
|
| 143 |
# ============ LOGIC BUGS ============
|
| 144 |
|
| 145 |
-
# Mutable default argument
|
| 146 |
if lang == 'python' and re.search(r'def\s+\w+\s*\([^)]*=\s*\[\]|def\s+\w+\s*\([^)]*=\s*\{\}', code):
|
| 147 |
bugs.append({
|
| 148 |
"type": "bug", "category": "logic", "severity": 3, "line_hint": 1,
|
| 149 |
"comment": "Mutable default argument: List/dict is shared across all function calls.",
|
| 150 |
-
"fix": "Use None as default: def func(lst=None): if lst is None: lst = []"
|
|
|
|
|
|
|
| 151 |
})
|
| 152 |
|
| 153 |
# Modifying list while iterating
|
|
@@ -155,104 +227,115 @@ def analyze_code_comprehensively(code: str, lang: str) -> list:
|
|
| 155 |
bugs.append({
|
| 156 |
"type": "bug", "category": "logic", "severity": 3, "line_hint": 2,
|
| 157 |
"comment": "Modifying list while iterating: Causes items to be skipped.",
|
| 158 |
-
"fix": "Iterate over a copy: for item in items[:]: or use list comprehension"
|
|
|
|
|
|
|
| 159 |
})
|
| 160 |
|
| 161 |
-
# Shadowing built-ins
|
| 162 |
if lang == 'python':
|
| 163 |
-
builtins = ['list', 'dict', 'set', 'tuple', 'str', 'int', 'float', 'len', 'range', 'map', 'filter', 'zip', 'open']
|
| 164 |
for builtin in builtins:
|
| 165 |
if re.search(rf'^{builtin}\s*=', code, re.MULTILINE):
|
| 166 |
bugs.append({
|
| 167 |
"type": "bug", "category": "logic", "severity": 2, "line_hint": 1,
|
| 168 |
"comment": f"Shadowing built-in '{builtin}': Overwrites Python's {builtin}() function.",
|
| 169 |
-
"fix": f"Rename variable: use my_{builtin} or similar"
|
|
|
|
|
|
|
| 170 |
})
|
| 171 |
-
break
|
| 172 |
|
| 173 |
# Division by zero
|
| 174 |
-
if re.search(r'\/\s*0', code):
|
| 175 |
bugs.append({
|
| 176 |
"type": "bug", "category": "logic", "severity": 3, "line_hint": 2,
|
| 177 |
"comment": "Potential division by zero. Check denominator is non-zero.",
|
| 178 |
-
"fix": "Add check: if denominator != 0: result = numerator / denominator"
|
|
|
|
|
|
|
| 179 |
})
|
| 180 |
|
| 181 |
-
# Off-by-one
|
| 182 |
-
if re.search(r'\[\s*\w+\s*\+\s*1\s*\]|\[.*:.*-\s*1\]', code):
|
| 183 |
bugs.append({
|
| 184 |
"type": "bug", "category": "logic", "severity": 3, "line_hint": 2,
|
| 185 |
-
"comment": "Off-by-one error:
|
| 186 |
-
"fix": "Use range(len(arr)
|
|
|
|
|
|
|
| 187 |
})
|
| 188 |
|
| 189 |
# Resource leak
|
| 190 |
-
if re.search(r'open\s*\([^)]+\)\s*(?!with)', code) and '.close()' not in code:
|
| 191 |
bugs.append({
|
| 192 |
"type": "bug", "category": "logic", "severity": 3, "line_hint": 2,
|
| 193 |
"comment": "Resource leak: File opened without 'with' statement. May not close properly.",
|
| 194 |
-
"fix": "Use: with open(file) as f: ... (automatic close)"
|
|
|
|
|
|
|
| 195 |
})
|
| 196 |
|
| 197 |
-
# Infinite recursion
|
| 198 |
-
if lang == 'python' and re.search(r'def\s+
|
| 199 |
bugs.append({
|
| 200 |
"type": "bug", "category": "logic", "severity": 3, "line_hint": 2,
|
| 201 |
"comment": "Infinite recursion: Function calls itself without base case.",
|
| 202 |
-
"fix": "Add base case: if condition: return value"
|
|
|
|
|
|
|
| 203 |
})
|
| 204 |
|
| 205 |
-
#
|
| 206 |
-
|
| 207 |
-
# Bare except clause
|
| 208 |
if lang == 'python' and re.search(r'except\s*:\s*(?!.*#)', code):
|
| 209 |
bugs.append({
|
| 210 |
"type": "bug", "category": "logic", "severity": 2, "line_hint": 2,
|
| 211 |
"comment": "Bare except clause: Catches all exceptions including KeyboardInterrupt.",
|
| 212 |
-
"fix": "Specify exception: except ValueError: or except Exception:"
|
|
|
|
|
|
|
| 213 |
})
|
| 214 |
|
| 215 |
-
# Type
|
| 216 |
-
if lang == 'python' and re.search(r'["\'][^"\']*["\'].*\+.*
|
| 217 |
bugs.append({
|
| 218 |
"type": "bug", "category": "logic", "severity": 2, "line_hint": 2,
|
| 219 |
"comment": "Type error: Cannot concatenate string with number directly.",
|
| 220 |
-
"fix": "Convert to string: str(value) or use f-string: f'text {value}'"
|
|
|
|
|
|
|
| 221 |
})
|
| 222 |
|
| 223 |
-
# Missing return statement
|
| 224 |
if lang == 'python' and re.search(r'def\s+\w+\s*\([^)]*\):[^}]*\n\s{4,}result\s*=', code) and not re.search(r'return\s+result', code):
|
| 225 |
bugs.append({
|
| 226 |
"type": "bug", "category": "logic", "severity": 2, "line_hint": 3,
|
| 227 |
"comment": "Missing return statement: Function computes value but returns None.",
|
| 228 |
-
"fix": "Add return: return result"
|
|
|
|
|
|
|
| 229 |
})
|
| 230 |
|
| 231 |
-
# Race condition
|
| 232 |
-
if
|
| 233 |
bugs.append({
|
| 234 |
"type": "bug", "category": "logic", "severity": 3, "line_hint": 2,
|
| 235 |
"comment": "Race condition: Multithreaded code without synchronization.",
|
| 236 |
-
"fix": "Use locks: lock = threading.Lock(); with lock: shared_var += 1"
|
|
|
|
|
|
|
| 237 |
})
|
| 238 |
|
| 239 |
# Inefficient nested loops
|
| 240 |
-
if code.count('for ') >= 2 and 'range(10000)' in code:
|
| 241 |
bugs.append({
|
| 242 |
"type": "bug", "category": "logic", "severity": 2, "line_hint": 2,
|
| 243 |
"comment": "Performance issue: Nested loops with large ranges (O(nΒ²) complexity).",
|
| 244 |
-
"fix": "Use set/dict for O(1) lookup or optimize algorithm"
|
|
|
|
|
|
|
| 245 |
})
|
| 246 |
|
| 247 |
-
# Logical error (identical branches)
|
| 248 |
-
if re.search(r'if\s+(\w+)\s*>\s*(\d+):\s*print\([^)]+\)\s*else:\s*print\([^)]+\)', code):
|
| 249 |
-
if 'Adult' in code.split('else')[0] and 'Adult' in code.split('else')[1]:
|
| 250 |
-
bugs.append({
|
| 251 |
-
"type": "bug", "category": "logic", "severity": 2, "line_hint": 2,
|
| 252 |
-
"comment": "Logical error: Both if and else branches do the same thing.",
|
| 253 |
-
"fix": "Remove the condition or fix the logic"
|
| 254 |
-
})
|
| 255 |
-
|
| 256 |
# Sort bugs by severity (highest first)
|
| 257 |
bugs.sort(key=lambda x: x['severity'], reverse=True)
|
| 258 |
|
|
@@ -270,9 +353,9 @@ def analyze_code_locally(code: str, lang: str) -> dict:
|
|
| 270 |
"severity": 1,
|
| 271 |
"line_hint": None,
|
| 272 |
"comment": "No obvious bugs detected. Code looks clean.",
|
| 273 |
-
"fix": ""
|
|
|
|
| 274 |
}
|
| 275 |
-
"""Comprehensive pattern-based code analysis"""
|
| 276 |
|
| 277 |
code_lower = code.lower()
|
| 278 |
code_no_space = code.lower().replace(' ', '')
|
|
|
|
| 27 |
class ReviewRequest(BaseModel):
|
| 28 |
code: str
|
| 29 |
language: str
|
| 30 |
+
export_format: str = None # Optional: 'json' for JSON export
|
| 31 |
+
|
| 32 |
|
| 33 |
@app.post("/api/review")
|
| 34 |
async def review_code(request: ReviewRequest):
|
| 35 |
+
"""Analyze code and return ALL bug findings with confidence scores"""
|
| 36 |
try:
|
| 37 |
code = request.code.strip()
|
| 38 |
+
lang = request.language.lower().strip()
|
| 39 |
|
| 40 |
if not code:
|
| 41 |
raise HTTPException(status_code=400, detail="Code cannot be empty")
|
|
|
|
| 44 |
if len(code) > 5000:
|
| 45 |
raise HTTPException(status_code=400, detail="Code exceeds 5000 characters")
|
| 46 |
|
| 47 |
+
# Validate language
|
| 48 |
+
supported_langs = ['python', 'javascript', 'typescript', 'java', 'go', 'cpp', 'c++']
|
| 49 |
+
if lang not in supported_langs:
|
| 50 |
+
raise HTTPException(
|
| 51 |
+
status_code=400,
|
| 52 |
+
detail=f"Language '{lang}' not supported. Supported languages: {', '.join(supported_langs)}"
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
# Local pattern-based analysis - returns ALL bugs, not just first
|
| 56 |
results = analyze_code_comprehensively(code, lang)
|
| 57 |
|
| 58 |
# Return the highest severity bug (or first bug if user wants single response)
|
| 59 |
+
response = {
|
| 60 |
+
"bugs_found": len(results),
|
| 61 |
+
"bugs": results,
|
| 62 |
+
"primary_bug": results[0] if results else None,
|
| 63 |
+
"analysis_metadata": {
|
| 64 |
+
"language": lang,
|
| 65 |
+
"code_length": len(code),
|
| 66 |
+
"lines_of_code": len(code.split('\n')),
|
| 67 |
+
"average_confidence": round(sum(b.get("confidence", 0.5) for b in results) / max(len(results), 1), 2) if results else 1.0
|
| 68 |
}
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
if not results:
|
| 72 |
+
response["primary_bug"] = {
|
| 73 |
+
"type": "approve",
|
| 74 |
+
"category": "style",
|
| 75 |
+
"severity": 1,
|
| 76 |
+
"line_hint": None,
|
| 77 |
+
"comment": "No obvious bugs detected. Code looks clean.",
|
| 78 |
+
"fix": "",
|
| 79 |
+
"confidence": 1.0
|
|
|
|
| 80 |
}
|
| 81 |
+
|
| 82 |
+
# Export to JSON if requested
|
| 83 |
+
if request.export_format == 'json':
|
| 84 |
+
response['export_url'] = '/api/export' # Would implement full export endpoint
|
| 85 |
+
|
| 86 |
+
return response
|
| 87 |
+
|
| 88 |
except HTTPException:
|
| 89 |
raise
|
| 90 |
+
except ValueError as ve:
|
| 91 |
+
return JSONResponse(
|
| 92 |
+
status_code=400,
|
| 93 |
+
content={"error": f"Invalid input: {str(ve)}"}
|
| 94 |
+
)
|
| 95 |
except Exception as e:
|
| 96 |
+
import traceback
|
| 97 |
return JSONResponse(
|
| 98 |
status_code=500,
|
| 99 |
+
content={"error": f"Analysis failed: {str(e)}", "details": traceback.format_exc()[:200]}
|
| 100 |
)
|
| 101 |
|
| 102 |
+
|
| 103 |
+
@app.get("/api/health")
|
| 104 |
+
async def health_check():
|
| 105 |
+
"""Health check endpoint that returns supported languages and API status"""
|
| 106 |
+
return {
|
| 107 |
+
"status": "ok",
|
| 108 |
+
"version": "2.0",
|
| 109 |
+
"supported_languages": ["python", "javascript", "typescript", "java", "go", "cpp"],
|
| 110 |
+
"features": [
|
| 111 |
+
"comprehensive_bug_detection",
|
| 112 |
+
"confidence_scores",
|
| 113 |
+
"multi_language_support",
|
| 114 |
+
"export_json_reports"
|
| 115 |
+
],
|
| 116 |
+
"api_endpoints": [
|
| 117 |
+
"/api/review (POST) - Analyze code",
|
| 118 |
+
"/api/health (GET) - This endpoint",
|
| 119 |
+
"/api/stats (GET) - Usage statistics"
|
| 120 |
+
]
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
@app.get("/api/stats")
|
| 125 |
+
async def get_stats():
|
| 126 |
+
"""Return usage statistics and bug detection summary"""
|
| 127 |
+
return {
|
| 128 |
+
"message": "Stats endpoint - tracks would be stored in session/DB",
|
| 129 |
+
"supported_check_types": 30,
|
| 130 |
+
"languages": 6,
|
| 131 |
+
"security_checks": 12,
|
| 132 |
+
"logic_checks": 8,
|
| 133 |
+
"style_checks": 10
|
| 134 |
+
}
|
| 135 |
code_lower = code.lower()
|
| 136 |
code_no_space = code.lower().replace(' ', '')
|
| 137 |
lines = code.split('\n')
|
| 138 |
|
| 139 |
# ============ CRITICAL SECURITY BUGS (Severity 5) ============
|
| 140 |
|
| 141 |
+
# SQL Injection (High confidence if f-string + SQL keywords)
|
| 142 |
if ('f"' in code or "f'" in code) and any(sql in code_lower for sql in ['select', 'insert', 'delete', 'update', 'from', 'where']) and '{' in code and '}' in code:
|
| 143 |
bugs.append({
|
| 144 |
"type": "bug", "category": "security", "severity": 5, "line_hint": 3,
|
| 145 |
"comment": "SQL injection: f-string with variable interpolation in SQL query.",
|
| 146 |
+
"fix": "Use parameterized queries: cursor.execute('SELECT * FROM users WHERE id = ?', (uid,))",
|
| 147 |
+
"confidence": 0.95, # Very high confidence
|
| 148 |
+
"languages": ["python", "javascript", "typescript"]
|
| 149 |
})
|
| 150 |
|
| 151 |
# Command Injection
|
| 152 |
+
if re.search(r'(os\.system|subprocess|popen|shell=true|exec\(|eval\()\s*\(.*f["\']|shell\s*=\s*true', code, re.I):
|
| 153 |
bugs.append({
|
| 154 |
"type": "bug", "category": "security", "severity": 5, "line_hint": 2,
|
| 155 |
"comment": "Command injection: User input directly in shell command.",
|
| 156 |
+
"fix": "Use subprocess with args as list: subprocess.run(['ls', filename], shell=False)",
|
| 157 |
+
"confidence": 0.92,
|
| 158 |
+
"languages": ["python", "javascript", "java"]
|
| 159 |
})
|
| 160 |
|
| 161 |
+
# Hardcoded credentials
|
| 162 |
if re.search(r'(password|passwd|pwd|secret|credential)\s*[=:]\s*["\'][^"\']{6,}["\']', code, re.I):
|
| 163 |
bugs.append({
|
| 164 |
"type": "bug", "category": "security", "severity": 5, "line_hint": 2,
|
| 165 |
"comment": "Hardcoded password/credential detected.",
|
| 166 |
+
"fix": "Use environment variables: os.getenv('DB_PASSWORD')",
|
| 167 |
+
"confidence": 0.98, # Almost certain
|
| 168 |
+
"languages": ["python", "javascript", "typescript", "java", "go", "cpp"]
|
| 169 |
})
|
| 170 |
|
| 171 |
+
# Code execution vulnerabilities
|
| 172 |
if re.search(r'\b(eval|exec|compile)\s*\(', code) or 'pickle.load' in code or 'yaml.load(' in code:
|
| 173 |
bugs.append({
|
| 174 |
"type": "bug", "category": "security", "severity": 5, "line_hint": 2,
|
| 175 |
"comment": "Arbitrary code execution: eval/exec/pickle are unsafe with untrusted data.",
|
| 176 |
+
"fix": "Use: json.loads(), ast.literal_eval(), or safe alternatives",
|
| 177 |
+
"confidence": 0.99,
|
| 178 |
+
"languages": ["python", "javascript"]
|
| 179 |
})
|
| 180 |
|
| 181 |
# ============ HIGH SEVERITY SECURITY BUGS (Severity 4) ============
|
| 182 |
|
| 183 |
+
# Hardcoded API keys
|
| 184 |
+
if re.search(r'(api_key|apikey|secret_key|private_key|token|auth_token|bearer|sk_|pk_)\s*[=:]\s*["\'][a-zA-Z0-9_\-]{8,}["\']', code, re.I):
|
| 185 |
bugs.append({
|
| 186 |
"type": "bug", "category": "security", "severity": 4, "line_hint": 1,
|
| 187 |
"comment": "Hardcoded API key/token detected.",
|
| 188 |
+
"fix": "api_key = os.getenv('API_KEY')",
|
| 189 |
+
"confidence": 0.96,
|
| 190 |
+
"languages": ["python", "javascript", "typescript", "java", "go"]
|
| 191 |
})
|
| 192 |
|
| 193 |
+
# XSS vulnerability
|
| 194 |
if lang == 'javascript' and re.search(r'\.innerHTML\s*=|\.eval\(|dangerouslySetInnerHTML', code):
|
| 195 |
bugs.append({
|
| 196 |
"type": "bug", "category": "security", "severity": 4, "line_hint": 2,
|
| 197 |
"comment": "XSS vulnerability: Setting innerHTML with user data can execute scripts.",
|
| 198 |
+
"fix": "Use .textContent or sanitize HTML: DOMPurify.sanitize()",
|
| 199 |
+
"confidence": 0.94,
|
| 200 |
+
"languages": ["javascript", "typescript"]
|
| 201 |
})
|
| 202 |
|
| 203 |
# Insecure random
|
|
|
|
| 205 |
bugs.append({
|
| 206 |
"type": "bug", "category": "security", "severity": 4, "line_hint": 2,
|
| 207 |
"comment": "Weak random number generator for security purposes.",
|
| 208 |
+
"fix": "Use: secrets.token_hex() or os.urandom() for cryptographic randomness",
|
| 209 |
+
"confidence": 0.88,
|
| 210 |
+
"languages": ["python", "javascript", "java", "go", "cpp"]
|
| 211 |
})
|
| 212 |
|
| 213 |
# ============ LOGIC BUGS ============
|
| 214 |
|
| 215 |
+
# Mutable default argument (Python-specific)
|
| 216 |
if lang == 'python' and re.search(r'def\s+\w+\s*\([^)]*=\s*\[\]|def\s+\w+\s*\([^)]*=\s*\{\}', code):
|
| 217 |
bugs.append({
|
| 218 |
"type": "bug", "category": "logic", "severity": 3, "line_hint": 1,
|
| 219 |
"comment": "Mutable default argument: List/dict is shared across all function calls.",
|
| 220 |
+
"fix": "Use None as default: def func(lst=None): if lst is None: lst = []",
|
| 221 |
+
"confidence": 0.98,
|
| 222 |
+
"languages": ["python"]
|
| 223 |
})
|
| 224 |
|
| 225 |
# Modifying list while iterating
|
|
|
|
| 227 |
bugs.append({
|
| 228 |
"type": "bug", "category": "logic", "severity": 3, "line_hint": 2,
|
| 229 |
"comment": "Modifying list while iterating: Causes items to be skipped.",
|
| 230 |
+
"fix": "Iterate over a copy: for item in items[:]: or use list comprehension",
|
| 231 |
+
"confidence": 0.91,
|
| 232 |
+
"languages": ["python"]
|
| 233 |
})
|
| 234 |
|
| 235 |
+
# Shadowing built-ins (Python)
|
| 236 |
if lang == 'python':
|
| 237 |
+
builtins = ['list', 'dict', 'set', 'tuple', 'str', 'int', 'float', 'len', 'range', 'map', 'filter', 'zip', 'open', 'sum']
|
| 238 |
for builtin in builtins:
|
| 239 |
if re.search(rf'^{builtin}\s*=', code, re.MULTILINE):
|
| 240 |
bugs.append({
|
| 241 |
"type": "bug", "category": "logic", "severity": 2, "line_hint": 1,
|
| 242 |
"comment": f"Shadowing built-in '{builtin}': Overwrites Python's {builtin}() function.",
|
| 243 |
+
"fix": f"Rename variable: use my_{builtin} or similar",
|
| 244 |
+
"confidence": 0.99,
|
| 245 |
+
"languages": ["python"]
|
| 246 |
})
|
| 247 |
+
break
|
| 248 |
|
| 249 |
# Division by zero
|
| 250 |
+
if re.search(r'\/\s*0(?![a-zA-Z0-9])', code):
|
| 251 |
bugs.append({
|
| 252 |
"type": "bug", "category": "logic", "severity": 3, "line_hint": 2,
|
| 253 |
"comment": "Potential division by zero. Check denominator is non-zero.",
|
| 254 |
+
"fix": "Add check: if denominator != 0: result = numerator / denominator",
|
| 255 |
+
"confidence": 0.99,
|
| 256 |
+
"languages": ["python", "javascript", "java", "go", "cpp"]
|
| 257 |
})
|
| 258 |
|
| 259 |
+
# Off-by-one errors
|
| 260 |
+
if re.search(r'\[\s*\w+\s*\+\s*1\s*\]|\[.*:.*-\s*1\]|range\(len', code):
|
| 261 |
bugs.append({
|
| 262 |
"type": "bug", "category": "logic", "severity": 3, "line_hint": 2,
|
| 263 |
+
"comment": "Off-by-one error: May access beyond array bounds or skip elements.",
|
| 264 |
+
"fix": "Use range(len(arr)) or check bounds: if i+1 < len(arr)",
|
| 265 |
+
"confidence": 0.85,
|
| 266 |
+
"languages": ["python", "javascript", "java", "go", "cpp"]
|
| 267 |
})
|
| 268 |
|
| 269 |
# Resource leak
|
| 270 |
+
if re.search(r'open\s*\([^)]+\)\s*(?!with|as)', code) and '.close()' not in code:
|
| 271 |
bugs.append({
|
| 272 |
"type": "bug", "category": "logic", "severity": 3, "line_hint": 2,
|
| 273 |
"comment": "Resource leak: File opened without 'with' statement. May not close properly.",
|
| 274 |
+
"fix": "Use: with open(file) as f: ... (automatic close)",
|
| 275 |
+
"confidence": 0.93,
|
| 276 |
+
"languages": ["python"]
|
| 277 |
})
|
| 278 |
|
| 279 |
+
# Infinite recursion (Python)
|
| 280 |
+
if lang == 'python' and re.search(r'def\s+\w+.*:\s*.*return\s+\1\s*\(', code, re.DOTALL):
|
| 281 |
bugs.append({
|
| 282 |
"type": "bug", "category": "logic", "severity": 3, "line_hint": 2,
|
| 283 |
"comment": "Infinite recursion: Function calls itself without base case.",
|
| 284 |
+
"fix": "Add base case: if condition: return value",
|
| 285 |
+
"confidence": 0.87,
|
| 286 |
+
"languages": ["python", "javascript", "java", "go", "cpp"]
|
| 287 |
})
|
| 288 |
|
| 289 |
+
# Bare except (Python)
|
|
|
|
|
|
|
| 290 |
if lang == 'python' and re.search(r'except\s*:\s*(?!.*#)', code):
|
| 291 |
bugs.append({
|
| 292 |
"type": "bug", "category": "logic", "severity": 2, "line_hint": 2,
|
| 293 |
"comment": "Bare except clause: Catches all exceptions including KeyboardInterrupt.",
|
| 294 |
+
"fix": "Specify exception: except ValueError: or except Exception:",
|
| 295 |
+
"confidence": 0.96,
|
| 296 |
+
"languages": ["python"]
|
| 297 |
})
|
| 298 |
|
| 299 |
+
# Type errors
|
| 300 |
+
if lang == 'python' and re.search(r'["\'][^"\']*["\'].*\+.*[0-9]|["\'][^"\']*["\'].*\+\s*\w+(?![\"\')])', code):
|
| 301 |
bugs.append({
|
| 302 |
"type": "bug", "category": "logic", "severity": 2, "line_hint": 2,
|
| 303 |
"comment": "Type error: Cannot concatenate string with number directly.",
|
| 304 |
+
"fix": "Convert to string: str(value) or use f-string: f'text {value}'",
|
| 305 |
+
"confidence": 0.82,
|
| 306 |
+
"languages": ["python"]
|
| 307 |
})
|
| 308 |
|
| 309 |
+
# Missing return statement (Python)
|
| 310 |
if lang == 'python' and re.search(r'def\s+\w+\s*\([^)]*\):[^}]*\n\s{4,}result\s*=', code) and not re.search(r'return\s+result', code):
|
| 311 |
bugs.append({
|
| 312 |
"type": "bug", "category": "logic", "severity": 2, "line_hint": 3,
|
| 313 |
"comment": "Missing return statement: Function computes value but returns None.",
|
| 314 |
+
"fix": "Add return: return result",
|
| 315 |
+
"confidence": 0.89,
|
| 316 |
+
"languages": ["python"]
|
| 317 |
})
|
| 318 |
|
| 319 |
+
# Race condition (threading/multiprocessing)
|
| 320 |
+
if re.search(r'threading\.|multiprocessing\.|Thread|Process|concurrent', code, re.I) and not re.search(r'Lock|RLock|Semaphore|Mutex|synchronized', code, re.I):
|
| 321 |
bugs.append({
|
| 322 |
"type": "bug", "category": "logic", "severity": 3, "line_hint": 2,
|
| 323 |
"comment": "Race condition: Multithreaded code without synchronization.",
|
| 324 |
+
"fix": "Use locks: lock = threading.Lock(); with lock: shared_var += 1",
|
| 325 |
+
"confidence": 0.80,
|
| 326 |
+
"languages": ["python", "java", "go", "cpp"]
|
| 327 |
})
|
| 328 |
|
| 329 |
# Inefficient nested loops
|
| 330 |
+
if code.count('for ') >= 2 and ('range(10000)' in code or 'range(1000)' in code):
|
| 331 |
bugs.append({
|
| 332 |
"type": "bug", "category": "logic", "severity": 2, "line_hint": 2,
|
| 333 |
"comment": "Performance issue: Nested loops with large ranges (O(nΒ²) complexity).",
|
| 334 |
+
"fix": "Use set/dict for O(1) lookup or optimize algorithm",
|
| 335 |
+
"confidence": 0.75,
|
| 336 |
+
"languages": ["python", "javascript", "java", "go", "cpp"]
|
| 337 |
})
|
| 338 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 339 |
# Sort bugs by severity (highest first)
|
| 340 |
bugs.sort(key=lambda x: x['severity'], reverse=True)
|
| 341 |
|
|
|
|
| 353 |
"severity": 1,
|
| 354 |
"line_hint": None,
|
| 355 |
"comment": "No obvious bugs detected. Code looks clean.",
|
| 356 |
+
"fix": "",
|
| 357 |
+
"confidence": 1.0
|
| 358 |
}
|
|
|
|
| 359 |
|
| 360 |
code_lower = code.lower()
|
| 361 |
code_no_space = code.lower().replace(' ', '')
|
templates/index.html
CHANGED
|
@@ -309,6 +309,19 @@ textarea#codeInput {
|
|
| 309 |
margin-bottom: 5px;
|
| 310 |
}
|
| 311 |
.r-field-value { font-family: var(--mono); font-size: .78rem; color: #c0bbb2; line-height: 1.6; }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 312 |
.sev-dots { display: flex; gap: 5px; margin-top: 4px; }
|
| 313 |
.sd { width: 9px; height: 9px; border-radius: 50%; background: #2a2a28; }
|
| 314 |
.sd.on { background: #d47e7e; }
|
|
@@ -318,6 +331,13 @@ textarea#codeInput {
|
|
| 318 |
font-family: var(--mono); font-size: .73rem; color: #7ed4a0;
|
| 319 |
white-space: pre-wrap; line-height: 1.65;
|
| 320 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 321 |
|
| 322 |
/* ββ FEATURES ββββββββββββββββββββββββββββββββββββββββββββββ */
|
| 323 |
#features { background: var(--surface); }
|
|
@@ -550,7 +570,10 @@ def get_user(uid):
|
|
| 550 |
<option value="">β Select Language β</option>
|
| 551 |
<option value="python">Python</option>
|
| 552 |
<option value="javascript">JavaScript</option>
|
|
|
|
| 553 |
<option value="java">Java</option>
|
|
|
|
|
|
|
| 554 |
</select>
|
| 555 |
<button class="run-btn" id="runBtn" onclick="doReview()">
|
| 556 |
<span id="runLbl">Analyze β</span>
|
|
@@ -593,6 +616,15 @@ def get_user(uid):
|
|
| 593 |
<div class="r-field-label">Severity</div>
|
| 594 |
<div class="sev-dots" id="rSev"></div>
|
| 595 |
</div>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 596 |
<div class="r-field">
|
| 597 |
<div class="r-field-label">Line Hint</div>
|
| 598 |
<div class="r-field-value" id="rLine">β</div>
|
|
@@ -604,6 +636,7 @@ def get_user(uid):
|
|
| 604 |
<div class="r-field">
|
| 605 |
<div class="r-field-label">Suggested Fix</div>
|
| 606 |
<pre class="r-fix" id="rFix"></pre>
|
|
|
|
| 607 |
</div>
|
| 608 |
</div>
|
| 609 |
</div>
|
|
@@ -856,6 +889,12 @@ function displayBug(bug) {
|
|
| 856 |
document.getElementById('rLine').textContent = bug.line_hint ? 'Line ' + bug.line_hint : 'Not specified';
|
| 857 |
document.getElementById('rComment').textContent = bug.comment || 'β';
|
| 858 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 859 |
const fixString = (bug.fix && bug.fix.fixed_code) ? bug.fix.fixed_code : bug.fix;
|
| 860 |
document.getElementById('rFix').textContent = fixString || (bug.type === 'approve' ? '(no fix required)' : 'β');
|
| 861 |
|
|
@@ -1098,6 +1137,39 @@ function showFlash(msg) {
|
|
| 1098 |
<p style="color:#d47e7e">${msg}</p>`;
|
| 1099 |
}
|
| 1100 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1101 |
/* ββ TRAINING βββββββββββββββββββββββββββββββββββββββββββββ */
|
| 1102 |
async function doTrain() {
|
| 1103 |
const ep = parseInt(document.getElementById('epRange').value);
|
|
|
|
| 309 |
margin-bottom: 5px;
|
| 310 |
}
|
| 311 |
.r-field-value { font-family: var(--mono); font-size: .78rem; color: #c0bbb2; line-height: 1.6; }
|
| 312 |
+
.confidence-bar {
|
| 313 |
+
display: flex; align-items: center; gap: 8px; margin-top: 4px;
|
| 314 |
+
}
|
| 315 |
+
.confidence-meter {
|
| 316 |
+
width: 100px; height: 6px; background: #262622; border-radius: 2px; overflow: hidden;
|
| 317 |
+
}
|
| 318 |
+
.confidence-fill {
|
| 319 |
+
height: 100%; background: linear-gradient(90deg, #d47e7e, #d4c27e, #7ed4a0);
|
| 320 |
+
transition: width .3s;
|
| 321 |
+
}
|
| 322 |
+
.confidence-pct {
|
| 323 |
+
font-size: .65rem; color: #888; font-family: var(--mono);
|
| 324 |
+
}
|
| 325 |
.sev-dots { display: flex; gap: 5px; margin-top: 4px; }
|
| 326 |
.sd { width: 9px; height: 9px; border-radius: 50%; background: #2a2a28; }
|
| 327 |
.sd.on { background: #d47e7e; }
|
|
|
|
| 331 |
font-family: var(--mono); font-size: .73rem; color: #7ed4a0;
|
| 332 |
white-space: pre-wrap; line-height: 1.65;
|
| 333 |
}
|
| 334 |
+
.export-btn {
|
| 335 |
+
display: inline-flex; align-items: center; gap: 6px;
|
| 336 |
+
background: #161614; border: 1px solid #262622; border-radius: 2px;
|
| 337 |
+
color: #999; font-family: var(--mono); font-size: .65rem;
|
| 338 |
+
padding: 6px 12px; cursor: pointer; transition: all .2s; margin-top: 12px;
|
| 339 |
+
}
|
| 340 |
+
.export-btn:hover { background: #262622; border-color: #3a3a38; color: #ccc; }
|
| 341 |
|
| 342 |
/* ββ FEATURES ββββββββββββββββββββββββββββββββββββββββββββββ */
|
| 343 |
#features { background: var(--surface); }
|
|
|
|
| 570 |
<option value="">β Select Language β</option>
|
| 571 |
<option value="python">Python</option>
|
| 572 |
<option value="javascript">JavaScript</option>
|
| 573 |
+
<option value="typescript">TypeScript</option>
|
| 574 |
<option value="java">Java</option>
|
| 575 |
+
<option value="go">Go</option>
|
| 576 |
+
<option value="cpp">C++</option>
|
| 577 |
</select>
|
| 578 |
<button class="run-btn" id="runBtn" onclick="doReview()">
|
| 579 |
<span id="runLbl">Analyze β</span>
|
|
|
|
| 616 |
<div class="r-field-label">Severity</div>
|
| 617 |
<div class="sev-dots" id="rSev"></div>
|
| 618 |
</div>
|
| 619 |
+
<div class="r-field">
|
| 620 |
+
<div class="r-field-label">Confidence</div>
|
| 621 |
+
<div class="confidence-bar">
|
| 622 |
+
<div class="confidence-meter">
|
| 623 |
+
<div class="confidence-fill" id="rConfidence" style="width: 0%"></div>
|
| 624 |
+
</div>
|
| 625 |
+
<span class="confidence-pct" id="rConfidencePct">β</span>
|
| 626 |
+
</div>
|
| 627 |
+
</div>
|
| 628 |
<div class="r-field">
|
| 629 |
<div class="r-field-label">Line Hint</div>
|
| 630 |
<div class="r-field-value" id="rLine">β</div>
|
|
|
|
| 636 |
<div class="r-field">
|
| 637 |
<div class="r-field-label">Suggested Fix</div>
|
| 638 |
<pre class="r-fix" id="rFix"></pre>
|
| 639 |
+
<button class="export-btn" onclick="exportBugReport()">π₯ Export to JSON</button>
|
| 640 |
</div>
|
| 641 |
</div>
|
| 642 |
</div>
|
|
|
|
| 889 |
document.getElementById('rLine').textContent = bug.line_hint ? 'Line ' + bug.line_hint : 'Not specified';
|
| 890 |
document.getElementById('rComment').textContent = bug.comment || 'β';
|
| 891 |
|
| 892 |
+
// Display confidence with progress bar
|
| 893 |
+
const confidence = bug.confidence || 0.5;
|
| 894 |
+
const confPercent = Math.round(confidence * 100);
|
| 895 |
+
document.getElementById('rConfidence').style.width = (confidence * 100) + '%';
|
| 896 |
+
document.getElementById('rConfidencePct').textContent = confPercent + '%';
|
| 897 |
+
|
| 898 |
const fixString = (bug.fix && bug.fix.fixed_code) ? bug.fix.fixed_code : bug.fix;
|
| 899 |
document.getElementById('rFix').textContent = fixString || (bug.type === 'approve' ? '(no fix required)' : 'β');
|
| 900 |
|
|
|
|
| 1137 |
<p style="color:#d47e7e">${msg}</p>`;
|
| 1138 |
}
|
| 1139 |
|
| 1140 |
+
/* Export bug report as JSON */
|
| 1141 |
+
function exportBugReport() {
|
| 1142 |
+
if (allBugs.length === 0) {
|
| 1143 |
+
showFlash('No bugs to export. Run analysis first.');
|
| 1144 |
+
return;
|
| 1145 |
+
}
|
| 1146 |
+
|
| 1147 |
+
const code = document.getElementById('codeInput').value;
|
| 1148 |
+
const lang = document.getElementById('langSel').value;
|
| 1149 |
+
|
| 1150 |
+
const report = {
|
| 1151 |
+
timestamp: new Date().toISOString(),
|
| 1152 |
+
language: lang,
|
| 1153 |
+
code_length: code.length,
|
| 1154 |
+
bugs_found: allBugs.length,
|
| 1155 |
+
bugs: allBugs,
|
| 1156 |
+
export_version: "2.0"
|
| 1157 |
+
};
|
| 1158 |
+
|
| 1159 |
+
const dataStr = JSON.stringify(report, null, 2);
|
| 1160 |
+
const dataBlob = new Blob([dataStr], { type: 'application/json' });
|
| 1161 |
+
const url = URL.createObjectURL(dataBlob);
|
| 1162 |
+
const link = document.createElement('a');
|
| 1163 |
+
link.href = url;
|
| 1164 |
+
link.download = `codebug-report-${new Date().toISOString().slice(0,10)}.json`;
|
| 1165 |
+
document.body.appendChild(link);
|
| 1166 |
+
link.click();
|
| 1167 |
+
document.body.removeChild(link);
|
| 1168 |
+
URL.revokeObjectURL(url);
|
| 1169 |
+
|
| 1170 |
+
showFlash('β Report exported successfully!');
|
| 1171 |
+
}
|
| 1172 |
+
|
| 1173 |
/* ββ TRAINING βββββββββββββββββββββββββββββββββββββββββββββ */
|
| 1174 |
async function doTrain() {
|
| 1175 |
const ep = parseInt(document.getElementById('epRange').value);
|