diff --git a/.DS_Store b/.DS_Store deleted file mode 100644 index 0079c75..0000000 Binary files a/.DS_Store and /dev/null differ diff --git a/.gitignore b/.gitignore index 8668864..e01fb27 100644 --- a/.gitignore +++ b/.gitignore @@ -129,4 +129,22 @@ dist .pnp.* .vscode -.idea \ No newline at end of file +.idea + +# Python virtual environments +venv/ +.venv/ +.venv +.env/ +__pycache__/ +*.pyc + +# macOS system files +.DS_Store + +# VS Code settings +.vscode/ + +# Logs and temp files +*.log +*.tmp diff --git a/Vulnerability_Tool_V2/api/__init__.py b/Vulnerability_Tool_V2/api/__init__.py new file mode 100644 index 0000000..c3d5503 --- /dev/null +++ b/Vulnerability_Tool_V2/api/__init__.py @@ -0,0 +1,6 @@ +""" +Security Scanner V2.0 API Package +""" + +__version__ = "2.0.0" +__author__ = "NutriHelp Security Team" \ No newline at end of file diff --git a/Vulnerability_Tool_V2/api/scanner_api.py b/Vulnerability_Tool_V2/api/scanner_api.py new file mode 100644 index 0000000..b573594 --- /dev/null +++ b/Vulnerability_Tool_V2/api/scanner_api.py @@ -0,0 +1,527 @@ +#!/usr/bin/env python3 +""" +Security Scanner V2.0 - FastAPI + Swagger UI integrated +api/scanner_api.py +""" + +import os +import sys +import tempfile +import asyncio +from pathlib import Path +from fastapi.responses import HTMLResponse +from typing import List, Dict, Any, Optional +from datetime import datetime + +# FastAPI imports +from fastapi import FastAPI, HTTPException, BackgroundTasks, UploadFile, File +from fastapi.responses import HTMLResponse, FileResponse +from fastapi.staticfiles import StaticFiles +from pydantic import BaseModel, Field +import uvicorn + +# Add scanner path +project_root = Path(__file__).parent.parent +sys.path.insert(0, str(project_root)) + +from core.scanner_engine import SecurityScannerEngine +from core.config_manager import ConfigManager +# Attempt to reuse CLI HTML generator for identical output +try: + # scanner_v2 lives at project root + from scanner_v2 import generate_html_report as cli_generate_html_report + CLI_HTML_GENERATOR_AVAILABLE = True +except Exception: + CLI_HTML_GENERATOR_AVAILABLE = False + +# Shared renderer for consistent HTML output between CLI and API +try: + from core.report_renderer import render_html_report + SHARED_RENDERER_AVAILABLE = True +except Exception: + SHARED_RENDERER_AVAILABLE = False + + +# Pydantic Models for API +class ScanRequest(BaseModel): + """Scan request model""" + target_path: str = Field(..., description="Target path to scan") + plugins: Optional[List[str]] = Field(None, description="Specify plugins to use, leave empty to use all") + output_format: str = Field("json", description="Output format: json or html") + + class Config: + schema_extra = { + "example": { + "target_path": "Please enter the local path of the Nutrihelp-api folder or the path of the target to be scanned.", + "plugins": ["JWTMissingProtectionPlugin", "JWTConfigurationPlugin"], + "output_format": "json" + } + } + + +class ScanResult(BaseModel): + """Scan result model""" + scan_id: str = Field(..., description="Scan ID") + target_path: str = Field(..., description="Target path") + scan_time: datetime = Field(..., description="Scan time") + total_files: int = Field(..., description="Total files scanned") + total_findings: int = Field(..., description="Total findings") + severity_summary: Dict[str, int] = Field(..., description="Severity-based issue statistics") + findings: List[Dict[str, Any]] = Field(..., description="Detailed findings list") + + class Config: + schema_extra = { + "example": { + "scan_id": "scan_20240906_143022", + "target_path": "./routes", + "scan_time": "2024-09-06T14:30:22", + "total_files": 173, + "total_findings": 28, + "severity_summary": {"CRITICAL": 2, "HIGH": 16, "MEDIUM": 9, "LOW": 1}, + "findings": [ + { + "title": "Missing JWT Protection", + "severity": "CRITICAL", + "file_path": "routes/userprofile.js", + "description": "API endpoint lacks JWT authentication middleware", + "recommendation": "Add authenticateToken middleware" + } + ] + } + } + + +class ScanStatus(BaseModel): + """Scan status model""" + scan_id: str + status: str = Field(..., description="Scan status: running, completed, failed") + progress: int = Field(..., description="Scan progress percentage") + message: str = Field(..., description="Status message") + + +# FastAPI application initialization +app = FastAPI( + title="NutriHelp Security Scanner V2.0", + description="Modular security scanner API designed for the NutriHelp project", + version="2.0.0", + docs_url="/scanner/docs", + redoc_url="/scanner/redoc" +) + +# Global variables +scanner_engine = None +config_manager = None +active_scans = {} + + +@app.on_event("startup") +async def startup_event(): + """Initialize scanner on startup""" + global scanner_engine, config_manager + + try: + config_manager = ConfigManager() + scanner_config = config_manager.get_scanner_config() + scanner_engine = SecurityScannerEngine(scanner_config) + + # Load plugins + plugin_configs = config_manager.get_enabled_plugins() + scanner_engine.load_plugins(plugin_configs) + + print(f"βœ… Security Scanner API initialized with {scanner_engine.stats['plugins_loaded']} plugins") + except Exception as e: + print(f"❌ Failed to initialize scanner: {e}") + raise + + +@app.get("/scanner/health", tags=["Health"]) +async def health_check(): + """Health check endpoint""" + return { + "status": "healthy", + "version": "2.0.0", + "plugins_loaded": scanner_engine.stats['plugins_loaded'] if scanner_engine else 0, + "timestamp": datetime.now().isoformat() + } + + +@app.get("/scanner/plugins", tags=["Plugins"]) +async def list_plugins(): + """Get list of available plugins""" + if not scanner_engine: + raise HTTPException(status_code=500, detail="Scanner engine not initialized") + + plugins = [] + for plugin in scanner_engine.plugin_manager.get_plugins(): + info = plugin.get_plugin_info() + plugins.append({ + "name": info['name'], + "version": info['version'], + "description": info['description'], + "severity_level": plugin.get_severity_level() + }) + + return {"plugins": plugins} + + +@app.post("/scanner/scan", response_model=Dict[str, str], tags=["Scanning"]) +async def start_scan(scan_request: ScanRequest, background_tasks: BackgroundTasks): + """Start asynchronous security scan""" + if not scanner_engine: + raise HTTPException(status_code=500, detail="Scanner engine not initialized") + + # Validate target path + if not os.path.exists(scan_request.target_path): + raise HTTPException(status_code=400, detail=f"Target path does not exist: {scan_request.target_path}") + + # Generate scan ID + scan_id = f"scan_{datetime.now().strftime('%Y%m%d_%H%M%S')}" + + # Initialize scan status + active_scans[scan_id] = { + "status": "running", + "progress": 0, + "message": "Scan initiated", + "request": scan_request + } + + # Start background scan task + background_tasks.add_task(perform_scan, scan_id, scan_request) + + return { + "scan_id": scan_id, + "message": "Scan started successfully", + "status_url": f"/scanner/scan/{scan_id}/status" + } + + +@app.get("/scanner/scan/{scan_id}/status", response_model=ScanStatus, tags=["Scanning"]) +async def get_scan_status(scan_id: str): + """Get scan status""" + if scan_id not in active_scans: + raise HTTPException(status_code=404, detail="Scan ID not found") + + scan_info = active_scans[scan_id] + return ScanStatus( + scan_id=scan_id, + status=scan_info["status"], + progress=scan_info["progress"], + message=scan_info["message"] + ) + + +@app.get("/scanner/scan/{scan_id}/result", response_model=ScanResult, tags=["Scanning"]) +async def get_scan_result(scan_id: str): + """Get scan result""" + if scan_id not in active_scans: + raise HTTPException(status_code=404, detail="Scan ID not found") + + scan_info = active_scans[scan_id] + + if scan_info["status"] != "completed": + raise HTTPException(status_code=202, detail="Scan not completed yet") + + if "result" not in scan_info: + raise HTTPException(status_code=500, detail="Scan result not available") + + return scan_info["result"] + + +@app.get("/scanner/scan/{scan_id}/report", tags=["Reports"]) +async def get_scan_report(scan_id: str, format: str = "html", download: bool = False): + """Get scan report file or HTML content (robust handling + download support).""" + if scan_id not in active_scans: + raise HTTPException(status_code=404, detail="Scan ID not found") + + scan_info = active_scans[scan_id] + if scan_info["status"] != "completed": + raise HTTPException(status_code=202, detail="Scan not completed yet") + + result = scan_info.get("result") + if not result: + raise HTTPException(status_code=500, detail="Scan result not available") + + scan_results = { + "summary": { + "total": result.total_findings, + "by_severity": result.severity_summary, + "by_plugin": {} + }, + "findings": [ + { + **f, # Expand the original data + "recommendation": f.get("recommendation", "") # Ensure recommendation is included + } + for f in result.findings + ], + "scan_info": { + "target_path": getattr(result, "target_path", ""), + "timestamp": getattr(result, "scan_time", "").isoformat() if hasattr(getattr(result, "scan_time", None), "isoformat") else str(getattr(result, "scan_time", "")), + "scanner_version": "2.0.0", + "stats": { + "files_scanned": getattr(result, "total_files", 0), + "plugins_loaded": scanner_engine.stats['plugins_loaded'] if scanner_engine else 0 + } + } + } + + try: + if format.lower() == "html": + # Prefer the shared renderer (which uses engine raw_result) for identical output + raw = scan_info.get('raw_result') if isinstance(scan_info, dict) else None + try: + if SHARED_RENDERER_AVAILABLE: + if raw: + html = render_html_report(raw, config_manager=config_manager) + else: + html = render_html_report(scan_results, config_manager=config_manager) + elif CLI_HTML_GENERATOR_AVAILABLE: + # Fallback to CLI generator if shared renderer isn't available + if raw: + html = cli_generate_html_report(raw) + else: + try: + html = cli_generate_html_report(scan_results, config_manager=None) + except TypeError: + html = cli_generate_html_report(scan_results) + else: + # final fallback: Jinja template renderer + html = generate_html_report(scan_results) + + except Exception as e: + # Final fallback to Jinja template render if shared renderer throws + try: + fallback_html = generate_html_report(scan_results) + return HTMLResponse(content=fallback_html, media_type='text/html') + except Exception: + raise HTTPException(status_code=500, detail=f'Failed to render report: {e}') + + # If download requested -> ensure a file exists and return as attachment + if download: + reports_dir = project_root / "reports" + reports_dir.mkdir(parents=True, exist_ok=True) + report_path = reports_dir / f"security_report_{scan_id}.html" + report_path.write_text(str(html), encoding="utf-8") + return FileResponse(str(report_path), media_type="text/html", filename=f"security_report_{scan_id}.html") + + # Return inline HTML + return HTMLResponse(content=str(html), media_type="text/html") + + elif format.lower() == "json": + report_path = generate_json_report(scan_id, result) + # support download query param for json as well + if download: + return FileResponse(report_path, media_type="application/json", filename=f"security_report_{scan_id}.json") + else: + # return file so Swagger can download; browsers may display JSON inline + return FileResponse(report_path, media_type="application/json", filename=f"security_report_{scan_id}.json") + + else: + raise HTTPException(status_code=400, detail="Unsupported format. Use 'html' or 'json'") + + except HTTPException: + raise + except Exception as e: + raise HTTPException(status_code=500, detail=f"Failed to generate report: {str(e)}") + + +def _unwrap_scan_results(scan_results: dict): + """Normalize scanner output into fields used by the API.""" + # Get the number of files directly from scan_info + total_files = scan_results.get("scan_info", {}).get("stats", {}).get("files_scanned") + + # If it is not available above, get it from the summary + if total_files is None: + total_files = scan_results.get("summary", {}).get("files_scanned") + + # Ensure a valid number is returned + if total_files is None: + total_files = 0 + + # Get total findings + total_findings = scan_results.get("summary", {}).get("total") + if total_findings is None: + total_findings = len(scan_results.get("findings", [])) + + severity_summary = scan_results.get("summary", {}).get("by_severity", {}) + findings = scan_results.get("findings", []) + + return int(total_files), int(total_findings), severity_summary, findings + + +# --- replace quick_scan --- +@app.post("/scanner/scan/quick", response_model=ScanResult, tags=["Scanning"]) +async def quick_scan(scan_request: ScanRequest): + """Synchronously perform a quick scan (suitable for small projects)""" + if not scanner_engine: + raise HTTPException(status_code=500, detail="Scanner engine not initialized") + + if not os.path.exists(scan_request.target_path): + raise HTTPException(status_code=400, detail=f"Target path does not exist: {scan_request.target_path}") + + try: + scan_results = scanner_engine.scan_target(scan_request.target_path) + + scan_id = f"quick_{datetime.now().strftime('%Y%m%d_%H%M%S')}" + + total_files, total_findings, severity_summary, findings = _unwrap_scan_results(scan_results) + + result = ScanResult( + scan_id=scan_id, + target_path=scan_request.target_path, + scan_time=datetime.now(), + total_files=total_files, + total_findings=total_findings, + severity_summary=severity_summary, + findings=[ + { + "title": f.get("title"), + "severity": f.get("severity"), + "file_path": f.get("file_path") or f.get("file"), + "line_number": f.get("line_number") or f.get("line"), + "description": f.get("description") or f.get("match", ""), + "plugin_name": f.get("plugin_name") or f.get("plugin"), + "recommendation": f.get("recommendation", "") + } + for f in findings + ] + ) + + # store quick scan so /status and /report work + active_scans[scan_id] = { + "status": "completed", + "progress": 100, + "message": "Quick scan completed", + "request": scan_request, + "result": result, + "raw_result": scan_results + } + + return result + + except Exception as e: + raise HTTPException(status_code=500, detail=f"Scan failed: {str(e)}") + + +# --- replace perform_scan --- +async def perform_scan(scan_id: str, scan_request: ScanRequest): + """Execute background scan task""" + try: + active_scans[scan_id]["progress"] = 10 + active_scans[scan_id]["message"] = "Starting scan..." + + scan_results = scanner_engine.scan_target(scan_request.target_path) + + active_scans[scan_id]["progress"] = 80 + active_scans[scan_id]["message"] = "Processing results..." + + total_files, total_findings, severity_summary, findings = _unwrap_scan_results(scan_results) + + result = ScanResult( + scan_id=scan_id, + target_path=scan_request.target_path, + scan_time=datetime.now(), + total_files=total_files, + total_findings=total_findings, + severity_summary=severity_summary, + findings=[ + { + "title": f.get("title"), + "severity": f.get("severity"), + "file_path": f.get("file_path") or f.get("file"), + "line_number": f.get("line_number") or f.get("line"), + "description": f.get("description") or f.get("match", ""), + "plugin_name": f.get("plugin_name") or f.get("plugin"), + "recommendation": f.get("recommendation", "") # Add a recommendation + } + for f in findings + ] + ) + + # Store the raw scan_results so the API can render reports identical to the CLI + active_scans[scan_id]["raw_result"] = scan_results + + active_scans[scan_id]["progress"] = 100 + active_scans[scan_id]["status"] = "completed" + active_scans[scan_id]["message"] = "Scan completed successfully" + active_scans[scan_id]["result"] = result + + except Exception as e: + # attach error details to active_scans for debugging + msg = f"Scan failed: {str(e)}" + active_scans[scan_id]["status"] = "failed" + active_scans[scan_id]["message"] = msg + # optional: keep traceback in logs + import traceback, logging + logging.getLogger("scanner_api").error(msg) + logging.getLogger("scanner_api").error(traceback.format_exc()) + + +# Safe import of jinja2 with fallback flag +try: + from jinja2 import Environment, FileSystemLoader, select_autoescape + JINJA_AVAILABLE = True +except Exception: + JINJA_AVAILABLE = False + +# Update template directory configuration (add after import statements at the beginning of the file) +project_root = Path(__file__).parent.parent +TEMPLATE_DIR = project_root / "templates" + +def generate_html_report(scan_results: dict) -> str: + """Generate HTML report from scan results.""" + try: + env = Environment( + loader=FileSystemLoader(str(TEMPLATE_DIR)), + autoescape=select_autoescape(['html', 'xml']) + ) + template = env.get_template('report.html') + + # Convert findings to ensure recommendations are included + findings = [] + for f in scan_results.get('findings', []): + finding = { + 'title': f.get('title', ''), + 'severity': f.get('severity', 'MEDIUM'), + 'file_path': f.get('file_path', ''), + 'line_number': f.get('line_number'), + 'description': f.get('description', ''), + 'plugin_name': f.get('plugin_name', ''), + 'recommendation': f.get('recommendation', '') # Ensure recommendation is included + } + findings.append(finding) + + return template.render( + generated_at=datetime.now().strftime("%Y-%m-%d %H:%M:%S"), + scan_info=scan_results.get('scan_info', {}), + summary=scan_results.get('summary', {}), + findings=findings # Use the processed findings + ) + except Exception as e: + raise HTTPException( + status_code=500, + detail=f"Failed to generate report: {str(e)}" + ) + + +def generate_json_report(scan_id: str, result: ScanResult) -> str: + """Generate a report in JSON format""" + reports_dir = project_root / "reports" + reports_dir.mkdir(exist_ok=True) + + report_path = reports_dir / f"security_report_{scan_id}.json" + + with open(report_path, 'w', encoding='utf-8') as f: + f.write(result.json(indent=2)) + + return str(report_path) + + +if __name__ == "__main__": + uvicorn.run( + "scanner_api:app", + host="0.0.0.0", + port=8001, + reload=True, + log_level="info" + ) \ No newline at end of file diff --git a/Vulnerability_Tool_V2/config/scanner_config.yaml b/Vulnerability_Tool_V2/config/scanner_config.yaml new file mode 100644 index 0000000..8239ee7 --- /dev/null +++ b/Vulnerability_Tool_V2/config/scanner_config.yaml @@ -0,0 +1,89 @@ +logging: + file_output: false + file_path: logs/scanner.log + format: '%(asctime)s - %(name)s - %(levelname)s - %(message)s' + level: INFO +plugins: + jwt_configuration: + config: + check_env_files: true + min_secret_length: 32 + enabled: true + jwt_missing_protection: + config: + check_middleware: true + check_routes: true + exclude_paths: + - /health + - /api-docs + enabled: true + rls_missing_protection_disabled: + config: + rls_indicators: + - auth.uid() + - current_user + - user_id + - auth_user + - rls + - row level security + sensitive_tables: + - users + - user_profiles + - auth_logs + - user_sessions + - recipes + - meal_plans + - appointments + - medical_predictions + - user_feedback + - notifications + enabled: false + severity_override: null +reports: + formats: + html: + enabled: false + include_css: true + include_js: false + template: default + json: + enabled: false + include_metadata: true + indent: 2 + text: + enabled: false + include_summary: true + max_width: 120 + group_by_severity: true + include_file_paths: true + include_source_snippets: true + include_timestamps: true + max_snippet_lines: 5 + sort_by_severity: true +scanner: + description: Specialized security scanner for NutriHelp project + exclude_directories: + - node_modules + - .git + - __pycache__ + - venv + - .venv + - dist + - build + - uploads + - temp + file_extensions: + - .js + - .ts + - .py + - .sql + - .json + - .yaml + - .yml + - .env + name: NutriHelp Security Scanner V2.0 + scan_settings: + max_file_size_mb: 50 + parallel_scanning: false + timeout_seconds: 300 + version: 2.0.0 diff --git a/Vulnerability_Tool_V2/core/config_manager.py b/Vulnerability_Tool_V2/core/config_manager.py new file mode 100644 index 0000000..abe984b --- /dev/null +++ b/Vulnerability_Tool_V2/core/config_manager.py @@ -0,0 +1,123 @@ +#!/usr/bin/env python3 +""" +Configuration Manager - handles loading and validation of YAML configuration files +""" + +import os +import yaml +import logging +from typing import Dict, Any, Optional +from pathlib import Path + + +class ConfigManager: + """Configuration Manager""" + + def __init__(self, config_path: Optional[str] = None): + self.config_path = config_path or self._get_default_config_path() + self.config: Dict[str, Any] = {} + self.logger = logging.getLogger("ConfigManager") + self._load_config() + + def _get_default_config_path(self) -> str: + """Get default config file path""" + current_dir = Path(__file__).parent + return str(current_dir.parent / "config" / "scanner_config.yaml") + + def _load_config(self): + """Load config file""" + try: + if os.path.exists(self.config_path): + with open(self.config_path, 'r', encoding='utf-8') as f: + self.config = yaml.safe_load(f) or {} + self.logger.info(f"Loaded configuration from {self.config_path}") + else: + self.logger.warning(f"Config file not found: {self.config_path}") + self.config = self._get_default_config() + self.logger.info("Using default configuration") + except Exception as e: + self.logger.error(f"Error loading configuration: {e}") + self.config = self._get_default_config() + + def _get_default_config(self) -> Dict[str, Any]: + """Get default configuration""" + return { + 'scanner': { + 'name': 'NutriHelp Security Scanner V2.0', + 'version': '2.0.0', + 'file_extensions': ['.js', '.py', '.ts', '.sql'], + 'exclude_directories': ['node_modules', '.git', '__pycache__'] + }, + 'plugins': {}, + 'reports': { + 'include_source_snippets': True, + 'group_by_severity': True + } + } + + def get(self, key: str, default: Any = None) -> Any: + """Get configuration value (supports dot notation)""" + keys = key.split('.') + value = self.config + + try: + for k in keys: + value = value[k] + return value + except (KeyError, TypeError): + return default + + def get_scanner_config(self) -> Dict[str, Any]: + """Get scanner configuration""" + return self.get('scanner', {}) + + def get_plugin_config(self, plugin_name: str) -> Dict[str, Any]: + """Get specific plugin configuration""" + return self.get(f'plugins.{plugin_name}', {}) + + def get_enabled_plugins(self) -> Dict[str, Dict[str, Any]]: + """Get enabled plugin configuration""" + plugins = self.get('plugins', {}) + enabled_plugins = {} + + for plugin_name, plugin_config in plugins.items(): + if plugin_config.get('enabled', True): + enabled_plugins[plugin_name] = plugin_config + + return enabled_plugins + + def get_report_config(self) -> Dict[str, Any]: + """Get report configuration""" + return self.get('reports', {}) + + def validate_config(self) -> bool: + """Validate configuration file""" + required_sections = ['scanner', 'plugins'] + + for section in required_sections: + if section not in self.config: + self.logger.error(f"Missing required config section: {section}") + return False + + # Validate scanner configuration + scanner_config = self.config['scanner'] + if 'name' not in scanner_config or 'version' not in scanner_config: + self.logger.error("Scanner config missing name or version") + return False + + self.logger.info("Configuration validation passed") + return True + + def reload_config(self): + """Reload configuration""" + self._load_config() + + def save_config(self, config_path: Optional[str] = None): + """Save configuration to file""" + save_path = config_path or self.config_path + try: + with open(save_path, 'w', encoding='utf-8') as f: + yaml.dump(self.config, f, default_flow_style=False, indent=2) + self.logger.info(f"Configuration saved to {save_path}") + except Exception as e: + self.logger.error(f"Error saving configuration: {e}") \ No newline at end of file diff --git a/Vulnerability_Tool_V2/core/report_renderer.py b/Vulnerability_Tool_V2/core/report_renderer.py new file mode 100644 index 0000000..3831d30 --- /dev/null +++ b/Vulnerability_Tool_V2/core/report_renderer.py @@ -0,0 +1,305 @@ +#!/usr/bin/env python3 +"""Shared HTML report renderer used by both CLI and API. +Place the common HTML template and rendering logic here so outputs are consistent. +""" +from datetime import datetime +from typing import Dict, Any + + +def render_html_report(scan_results: Dict[str, Any], config_manager=None) -> str: + """Render the HTML report from scan_results dict. + + scan_results must contain keys: summary, findings, scan_info + """ + summary = scan_results.get('summary', {}) + findings = scan_results.get('findings', []) + scan_info = scan_results.get('scan_info', {}) + + # Use the same HTML template as CLI previously used + html_template = """ + + + + + + NutriHelp Security Scanner V2.0 Report + + + +
+
+

πŸ”’ NutriHelp Security Scanner V2.0

+
+
Scan time: {timestamp}
+
Target path: {target_path}
+
Scanner version: {scanner_version}
+
+
+ +
+
+
{critical_count}
+
Critical Issues
+
+
+
{high_count}
+
High Severity
+
+
+
{medium_count}
+
Medium Severity
+
+
+
{low_count}
+
Low Severity
+
+
+ +
+
+
+
{files_scanned}
+
Files Scanned
+
+
+
{plugins_used}
+
Plugins Used
+
+
+
{total_findings}
+
Total Issues
+
+
+ + {findings_html} +
+ + +
+ + + """ + + # Generate HTML for findings + if not findings: + findings_html = '

βœ… No Security Issues Found!

Your codebase has passed all security checks.

' + else: + findings_html = '

πŸ” Detailed Findings

' + + # Sort by severity + sorted_findings = sorted(findings, key=lambda x: { + 'CRITICAL': 0, 'HIGH': 1, 'MEDIUM': 2, 'LOW': 3, 'INFO': 4 + }.get(x.get('severity', 'MEDIUM'), 2)) + + for finding in sorted_findings: + severity = finding.get('severity', 'MEDIUM').lower() + # Format recommendation: support structured object or plain text + recommendation = finding.get('recommendation', None) + formatted_recommendation = '' + + if isinstance(recommendation, dict): + parts = [] + rec_summary = recommendation.get('summary') + steps = recommendation.get('steps', []) + code = recommendation.get('code', '') + + if rec_summary: + parts.append(f"

{rec_summary}

") + if steps: + parts.append('
    ') + for s in steps: + parts.append(f"
  1. {s}
  2. ") + parts.append('
') + if code: + parts.append(f"
{code}
") + + formatted_recommendation = '\n'.join(parts) + elif isinstance(recommendation, str) and recommendation: + formatted_recommendation = recommendation.replace("\n\n", "

").replace("\n", "
") + else: + formatted_recommendation = '

Please review this security issue and take appropriate remediation steps.

' + + finding_html = f""" +
+
+
{finding.get('title','')}
+ {finding.get('severity','MEDIUM')} +
+ +
+ πŸ“„ + {finding.get('file_path','')} + {f" (Line {finding.get('line_number')})" if finding.get('line_number') else ''} +
+ +
{finding.get('description','')}
+ +
+ πŸ’‘ Recommendation: + {formatted_recommendation} +
+ +
+ Plugin: {finding.get('plugin_name', finding.get('plugin', 'Unknown'))} +
+
+ """ + findings_html += finding_html + + # Format timestamp safely + timestamp = ( + scan_results.get('timestamp') or + scan_info.get('timestamp') or + datetime.now().isoformat() + ) + try: + if 'Z' in str(timestamp): + timestamp_obj = datetime.fromisoformat(str(timestamp).replace('Z', '+00:00')) + else: + timestamp_obj = datetime.fromisoformat(str(timestamp)) + formatted_timestamp = timestamp_obj.strftime('%Y-%m-%d %H:%M:%S') + except Exception: + formatted_timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S') + + return html_template.format( + timestamp=formatted_timestamp, + target_path=scan_info.get('target_path', '../'), + scanner_version=scan_info.get('scanner_version', '2.0.0'), + critical_count=summary.get('by_severity', {}).get('CRITICAL', 0), + high_count=summary.get('by_severity', {}).get('HIGH', 0), + medium_count=summary.get('by_severity', {}).get('MEDIUM', 0), + low_count=summary.get('by_severity', {}).get('LOW', 0), + files_scanned=scan_info.get('stats', {}).get('files_scanned', 0), + plugins_used=scan_info.get('stats', {}).get('plugins_loaded', 0), + total_findings=summary.get('total', 0), + findings_html=findings_html + ) diff --git a/Vulnerability_Tool_V2/core/scanner_engine.py b/Vulnerability_Tool_V2/core/scanner_engine.py new file mode 100644 index 0000000..0deeb64 --- /dev/null +++ b/Vulnerability_Tool_V2/core/scanner_engine.py @@ -0,0 +1,287 @@ +#!/usr/bin/env python3 +""" +NutriHelp Security Scanner V2.0 - Core Engine +""" + +import os +import sys +import importlib +import logging +from typing import List, Dict, Any, Optional +from pathlib import Path +import uuid +from datetime import datetime + +# Add the plugin directory to the Python path +sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..')) + +from plugins.base_plugin import BaseSecurityPlugin, PluginManager, SecurityFinding + + +class SecurityScannerEngine: + """Security Scanner Engine Core Class""" + + def __init__(self, config: Optional[Dict[str, Any]] = None): + self.config = config or {} + self.plugin_manager = PluginManager() + self.logger = logging.getLogger("SecurityScannerEngine") + self._setup_logging() + + # Statistics + self.stats = { + 'files_scanned': 0, + 'total_findings': 0, + 'plugins_loaded': 0 + } + + def _setup_logging(self): + """Set up logging configuration""" + logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', + handlers=[ + logging.StreamHandler(), + # can add file processors + ] + ) + + def load_plugins(self, plugin_configs: Optional[Dict[str, Any]] = None): + """Dynamically load plugins""" + plugin_configs = plugin_configs or {} + plugins_loaded = 0 + + # Define plugin mappings + plugin_mappings = { + 'jwt_missing_protection': 'plugins.jwt_security.jwt_missing', + 'jwt_configuration': 'plugins.jwt_security.jwt_config', + # General security plugin + 'general_security': 'plugins.general_security', + # RLS plugin removed to fix dependency issues + } + + for plugin_name, module_path in plugin_mappings.items(): + plugin_config = plugin_configs.get(plugin_name, {}) + + # Check if the plugin is enabled + if not plugin_config.get('enabled', True): + self.logger.info(f"Plugin {plugin_name} is disabled") + continue + + try: + # Dynamically import plugin module + module = importlib.import_module(module_path) + + # Find plugin class (convention: ends with Plugin) + plugin_class = None + for attr_name in dir(module): + attr = getattr(module, attr_name) + if (isinstance(attr, type) and + issubclass(attr, BaseSecurityPlugin) and + attr != BaseSecurityPlugin): + plugin_class = attr + break + + if plugin_class: + plugin_instance = plugin_class(plugin_config.get('config', {})) + self.plugin_manager.register_plugin(plugin_instance) + plugins_loaded += 1 + else: + self.logger.warning(f"No plugin class found in {module_path}") + + except ImportError as e: + self.logger.warning(f"Could not load plugin {plugin_name}: {e}") + except Exception as e: + self.logger.error(f"Error loading plugin {plugin_name}: {e}") + + self.stats['plugins_loaded'] = plugins_loaded + self.logger.info(f"Loaded {plugins_loaded} plugins") + + def _count_by_severity(self, findings: List[Any]) -> Dict[str, int]: + """Count findings by severity level.""" + severity_counts = {} + for finding in findings: + # Handle both object and dict findings + if hasattr(finding, 'severity'): + severity = finding.severity + else: + severity = finding.get('severity', 'UNKNOWN') + + severity = str(severity).upper() + severity_counts[severity] = severity_counts.get(severity, 0) + 1 + return severity_counts + + def _count_by_plugin(self, findings: List[Any]) -> Dict[str, int]: + """Count findings by plugin name.""" + plugin_counts = {} + for finding in findings: + # Handle both object and dict findings + if hasattr(finding, 'plugin'): + plugin = finding.plugin + else: + plugin = finding.get('plugin', 'Unknown') + + plugin_counts[plugin] = plugin_counts.get(plugin, 0) + 1 + return plugin_counts + + def scan_target(self, target_path: str) -> Dict: + """Run all security plugins on the target.""" + self.logger.info(f"Starting security scan on: {target_path}") + all_findings = [] + + # Make sure to count the number of files first + files_scanned = self._count_scannable_files(target_path) + self.stats['files_scanned'] = files_scanned + + for plugin in self.plugin_manager.plugins: + try: + findings = plugin.scan(target_path) + if findings: + # Process each finding + for finding in findings: + # Prefer plugin-provided recommendation; generate only if missing/empty + existing_rec = None + if hasattr(finding, 'recommendation'): + existing_rec = getattr(finding, 'recommendation') + elif isinstance(finding, dict): + existing_rec = finding.get('recommendation') + + if not existing_rec: + # Generate and add recommendation only when plugin didn't provide one + recommendation = self._generate_recommendation( + finding.title if hasattr(finding, 'title') else finding.get('title', ''), + finding.file_path if hasattr(finding, 'file_path') else finding.get('file_path', '') + ) + + # If finding is an object + if hasattr(finding, 'recommendation'): + finding.recommendation = recommendation + # If finding is a dictionary + elif isinstance(finding, dict): + finding['recommendation'] = recommendation + + # Ensure other attributes exist + if hasattr(finding, 'plugin') and not getattr(finding, 'plugin', None): + finding.plugin = plugin.__class__.__name__ + if hasattr(finding, 'file_path') and not getattr(finding, 'file_path', None): + finding.file_path = target_path + + all_findings.extend(findings) + except Exception as e: + self.logger.error(f"Plugin {plugin.__class__.__name__} failed: {e}") + + # Convert findings to ensure recommendations are included + findings_dict = [] + for f in all_findings: + if hasattr(f, 'to_dict'): + finding_dict = f.to_dict() + # Ensure recommendation is included in the dictionary + if hasattr(f, 'recommendation'): + finding_dict['recommendation'] = f.recommendation + findings_dict.append(finding_dict) + else: + findings_dict.append(f) + + return { + 'scan_id': str(uuid.uuid4()), + 'target': target_path, + 'timestamp': datetime.now().isoformat(), + 'findings': findings_dict, # Use the processed findings + 'summary': { + 'total': len(all_findings), + 'files_scanned': files_scanned, + 'by_severity': self._count_by_severity(all_findings), + 'by_plugin': self._count_by_plugin(all_findings) + }, + 'scan_info': { + 'target_path': target_path, + 'scanner_version': "2.0.0", + 'stats': { + 'files_scanned': files_scanned, + 'plugins_loaded': len(self.plugin_manager.plugins), + 'total_findings': len(all_findings) + } + } + } + + def _count_scannable_files(self, target_path: str) -> int: + """Count scannable files""" + count = 0 + for root, dirs, files in os.walk(target_path): + # Skip directories that should not be scanned + dirs[:] = [d for d in dirs if not self._should_skip_dir(os.path.join(root, d))] + + for file in files: + file_path = os.path.join(root, file) + if self._is_scannable_file(file_path): + count += 1 + return count + + def _should_skip_dir(self, dir_path: str) -> bool: + """Check if a directory should be skipped""" + skip_dirs = self.config.get('exclude_directories', [ + 'node_modules', '.git', '__pycache__', 'venv', '.venv', + 'dist', 'build', 'uploads' + ]) + dir_name = os.path.basename(dir_path) + return dir_name in skip_dirs + + def _is_scannable_file(self, file_path: str) -> bool: + """Check if a file is scannable""" + supported_extensions = self.config.get('file_extensions', [ + '.js', '.ts', '.py', '.sql', '.json', '.yaml', '.yml' + ]) + file_ext = os.path.splitext(file_path)[1].lower() + return file_ext in supported_extensions + + def _generate_summary(self, findings: List[SecurityFinding]) -> Dict[str, Any]: + """Generate scan summary""" + summary = { + 'total': len(findings), + 'by_severity': {'CRITICAL': 0, 'HIGH': 0, 'MEDIUM': 0, 'LOW': 0}, + 'by_plugin': {} + } + + for finding in findings: + # Count by severity + severity = finding.severity.upper() + if severity in summary['by_severity']: + summary['by_severity'][severity] += 1 + + # Count by plugin + plugin_name = finding.plugin or 'Unknown' + if plugin_name not in summary['by_plugin']: + summary['by_plugin'][plugin_name] = 0 + summary['by_plugin'][plugin_name] += 1 + + return summary + + def _get_timestamp(self) -> str: + """Get timestamp""" + from datetime import datetime + return datetime.now().isoformat() + + def get_scan_stats(self) -> Dict[str, Any]: + """Get scan statistics""" + return self.stats.copy() + + def _generate_recommendation(self, finding_type: str, file_path: str) -> str: + """Generate specific recommendations based on finding type.""" + # Return a structured recommendation dict + if "JWT" in finding_type: + return { + 'summary': 'Add JWT authentication middleware to the route.', + 'steps': [ + "Import the middleware if missing: const { authenticateToken } = require('../middleware/authenticateToken');", + "Add middleware to the route: e.g. router.post('/', authenticateToken, (req, res) => { ... });", + "Consider optional authentication helper if needed: const { optionalAuth } = require('../middleware/authenticateToken');", + "Verify token lifetimes and error handling policies." + ], + 'code': "const { authenticateToken } = require('../middleware/authenticateToken');\nrouter.post('/', authenticateToken, (req, res) => { ... });" + } + + # Add more recommendation types as needed + return { + 'summary': 'Review this finding and apply best-practice remediation steps.', + 'steps': ["Investigate the issue details.", "Apply an appropriate fix and test."], + 'code': '' + } \ No newline at end of file diff --git a/Vulnerability_Tool_V2/plugins/base_plugin.py b/Vulnerability_Tool_V2/plugins/base_plugin.py new file mode 100644 index 0000000..cdc3e12 --- /dev/null +++ b/Vulnerability_Tool_V2/plugins/base_plugin.py @@ -0,0 +1,163 @@ +#!/usr/bin/env python3 +""" +Base plugin class for NutriHelp Security Scanner V2.0 +""" + +from abc import ABC, abstractmethod +from typing import List, Dict, Any, Optional, Union +import logging +import os +from datetime import datetime + + +class SecurityFinding: + """Standardized security discovery objects""" + + def __init__(self, title: str, severity: str, file_path: str, + description: str, line_number: Optional[int] = None, + plugin: Optional[str] = None, recommendation: Optional[Union[str, Dict[str, Any]]] = None): + self.title = title + self.severity = severity + self.file_path = file_path + self.description = description + self.line_number = line_number + self.plugin = plugin + self.recommendation = recommendation + + def to_dict(self) -> Dict[str, Any]: + return { + 'title': self.title, + 'severity': self.severity, + 'file_path': self.file_path, + 'line_number': self.line_number, + 'description': self.description, + 'plugin_name': self.plugin, + 'recommendation': self.recommendation + } + + +class BaseSecurityPlugin(ABC): + """Base class for all security plugins""" + + def __init__(self, config: Optional[Dict[str, Any]] = None): + self.config = config or {} + self.name = self.__class__.__name__ + self.findings: List[SecurityFinding] = [] + self.logger = logging.getLogger(f"SecurityPlugin.{self.name}") + self._setup_logging() + + def _setup_logging(self): + """Set up logging configuration""" + if not self.logger.handlers: + handler = logging.StreamHandler() + formatter = logging.Formatter( + '%(asctime)s - %(name)s - %(levelname)s - %(message)s' + ) + handler.setFormatter(formatter) + self.logger.addHandler(handler) + self.logger.setLevel(logging.INFO) + + @abstractmethod + def get_plugin_info(self) -> Dict[str, str]: + """Return plugin metadata information""" + pass + + @abstractmethod + def scan(self, target_path: str) -> List[SecurityFinding]: + """Perform security scan and return discovered issues""" + pass + + @abstractmethod + def get_severity_level(self) -> str: + """Return default severity level for issues detected by the plugin""" + pass + + def add_finding(self, title: str, description: str, file_path: str, + line_number: Optional[int] = None, severity: Optional[str] = None, + recommendation: Optional[str] = None) -> SecurityFinding: + """Add security finding""" + if severity is None: + severity = self.get_severity_level() + + finding = SecurityFinding( + title=title, + severity=severity, + file_path=file_path, + description=description, + line_number=line_number, + recommendation=recommendation + ) + finding.plugin = self.name + self.findings.append(finding) + + self.logger.info(f"Added {severity} finding: {title}") + return finding + + def clear_findings(self): + """Clear all findings""" + self.findings.clear() + + def is_file_scannable(self, file_path: str) -> bool: + """Check if a file is scannable""" + # Get supported file extensions + supported_extensions = self.config.get('file_extensions', ['.js', '.py', '.ts']) + file_ext = os.path.splitext(file_path)[1].lower() + return file_ext in supported_extensions + + def should_skip_directory(self, dir_path: str) -> bool: + """Check if a directory should be skipped""" + skip_dirs = self.config.get('skip_directories', [ + 'node_modules', '.git', '__pycache__', 'venv', '.venv' + ]) + dir_name = os.path.basename(dir_path) + return dir_name in skip_dirs + + def read_file_safe(self, file_path: str) -> Optional[str]: + """Safely read file content""" + try: + with open(file_path, 'r', encoding='utf-8') as f: + return f.read() + except (UnicodeDecodeError, PermissionError) as e: + self.logger.warning(f"Cannot read file {file_path}: {e}") + return None + + def get_relative_path(self, file_path: str, base_path: str) -> str: + """Get relative path""" + try: + return os.path.relpath(file_path, base_path) + except ValueError: + return file_path + + +class PluginManager: + """Plugin manager""" + + def __init__(self): + self.plugins: List[BaseSecurityPlugin] = [] + self.logger = logging.getLogger("PluginManager") + + def register_plugin(self, plugin: BaseSecurityPlugin): + """Register plugin""" + self.plugins.append(plugin) + info = plugin.get_plugin_info() + self.logger.info(f"Registered plugin: {info['name']} v{info['version']}") + + def get_plugins(self) -> List[BaseSecurityPlugin]: + """Get all registered plugins""" + return self.plugins + + def run_all_scans(self, target_path: str) -> Dict[str, List[SecurityFinding]]: + """Run all plugin scans""" + results = {} + + for plugin in self.plugins: + plugin.clear_findings() # Clear previous results + try: + findings = plugin.scan(target_path) + results[plugin.name] = findings + self.logger.info(f"Plugin {plugin.name} found {len(findings)} issues") + except Exception as e: + self.logger.error(f"Plugin {plugin.name} failed: {e}") + results[plugin.name] = [] + + return results \ No newline at end of file diff --git a/Vulnerability_Tool_V2/plugins/general_security/README.md b/Vulnerability_Tool_V2/plugins/general_security/README.md new file mode 100644 index 0000000..7d17c38 --- /dev/null +++ b/Vulnerability_Tool_V2/plugins/general_security/README.md @@ -0,0 +1,56 @@ +# General Security Plugin + +This plugin (`general_security`) detects common, generic security issues across a codebase. + +## What it detects + +- Hardcoded secrets + - Looks for variable-like keys (e.g. `password`, `secret`, `api_key`, `token`, `jwt_secret`) assigned string values. + - Requires value length >= 8 to reduce incidental matches. +- Hardcoded database connection strings + - Matches `postgres://` and `mysql://` style URLs in code/config files. +- Permissive CORS configurations + - Detects `Access-Control-Allow-Origin: *` or `origin: '*'` patterns. + +## Configuration + +The plugin reads configuration from the scanner's plugin config and supports the following keys: + +- `enabled` (bool): Enable or disable this plugin. +- `allowlist_keys` (list[str]): Keys to ignore when scanning for secrets (case-insensitive). +- `exclude_paths` (list[str]): Path substrings; if any matches a file path, that file will be skipped by this plugin. +- `secret_keys_allowlist` (list[str]): Additional secret key names to match. + +Example config snippet (in scanner config): + +```yaml +plugins: + general_security: + enabled: true + allowlist_keys: + - 'TEST_SECRET' + exclude_paths: + - 'migrations/' + - 'tests/' + secret_keys_allowlist: + - 'password' + - 'jwt' +``` + +## False positives and mitigation + +- The plugin uses heuristics and simple regexes; add known safe keys to `allowlist_keys` and common test/dev paths to `exclude_paths`. +- If you see many false positives from a specific pattern, prefer to add an allowlist entry or refine your scanner config. + +## Extending + +This plugin is intentionally lightweight. To add more checks: +- Implement additional regex or AST-based checks in `scan()`. +- Use `self.add_finding(...)` to add structured findings (recommendation can be a dict for richer rendering). + +## Output + +Findings are returned as `SecurityFinding` objects (converted to dict by the engine) with fields: +- `title`, `severity`, `file_path`, `line_number`, `description`, `plugin_name`, `recommendation` + +These are rendered in the HTML/JSON reports by the shared renderer. diff --git a/Vulnerability_Tool_V2/plugins/general_security/__init__.py b/Vulnerability_Tool_V2/plugins/general_security/__init__.py new file mode 100644 index 0000000..2a832b9 --- /dev/null +++ b/Vulnerability_Tool_V2/plugins/general_security/__init__.py @@ -0,0 +1,126 @@ +#!/usr/bin/env python3 +"""General security plugin: detects common hardcoded secrets, DB connection strings, +and permissive CORS configurations. +""" +import os +import re +from typing import List, Dict, Any, Optional + +from plugins.base_plugin import BaseSecurityPlugin, SecurityFinding + + +class GeneralSecurityPlugin(BaseSecurityPlugin): + def __init__(self, config: Optional[Dict[str, Any]] = None): + super().__init__(config) + self.name = 'general_security' + # Merge sensible defaults to reduce noisy results + defaults = { + 'allowlist_keys': ['TEST_SECRET', 'PLACEHOLDER', 'EXAMPLE_SECRET'], + 'exclude_paths': ['tests/', '__tests__/', 'fixtures/', 'node_modules/', '.venv/', 'venv/'], + 'secret_keys_allowlist': ['password', 'passwd', 'secret', 'api_key', 'apiKey', 'token', 'jwt_secret', 'jwt'] + } + # Only set defaults for keys not provided by user config + for k, v in defaults.items(): + if k not in self.config: + self.config[k] = v + + def get_plugin_info(self) -> Dict[str, str]: + return { + 'name': 'general_security', + 'version': '0.1.0', + 'description': 'Detect generic security issues such as hardcoded secrets, DB URLs and permissive CORS.' + } + + def get_severity_level(self) -> str: + return 'MEDIUM' + + def scan(self, target_path: str) -> List[SecurityFinding]: + # Walk files under target_path and perform lightweight pattern checks + for root, dirs, files in os.walk(target_path): + # Respect skip directories from base class config + dirs[:] = [d for d in dirs if not self.should_skip_directory(os.path.join(root, d))] + + for fname in files: + fpath = os.path.join(root, fname) + # allow additional common config file extensions even if base class + # doesn't include them (e.g., .conf, .env, .ini, .yaml, .yml, .txt) + extra_exts = {'.conf', '.env', '.ini', '.yaml', '.yml', '.json', '.txt'} + file_ext = os.path.splitext(fpath)[1].lower() + if not (self.is_file_scannable(fpath) or file_ext in extra_exts): + continue + + content = self.read_file_safe(fpath) + if not content: + continue + + # 1) hardcoded secrets (improved heuristic) + # Require variable-like keys and a reasonably long secret value (to avoid short incidental matches) + secret_keys = self.config.get('secret_keys_allowlist', ['password', 'passwd', 'secret', 'api_key', 'apiKey', 'token', 'jwt_secret', 'jwt']) + secret_keys_re = r"(?:" + r"|".join([re.escape(k) for k in secret_keys]) + r")" + # match patterns like: KEY = 'value' or "KEY": "value"; value must be at least 8 chars and not contain whitespace/newlines + secret_pattern = re.compile(rf"(?i)({secret_keys_re})\s*[:=]\s*[\'\"]([A-Za-z0-9@#\$%\^&\-_=+\./\\~`{{}}\|]{{8,512}})[\'\"]") + for m in secret_pattern.finditer(content): + key = m.group(1) + value = m.group(2) + # allowlist check: if key or file path is explicitly allowed, skip + allowlist_keys = [k.lower() for k in self.config.get('allowlist_keys', [])] + if key.lower() in allowlist_keys: + continue + exclude_paths = self.config.get('exclude_paths', []) + if any(p and p in fpath for p in exclude_paths): + continue + + self.add_finding( + title=f'Hardcoded secret: {key}', + description=f'Found likely hardcoded secret key "{key}" in file. Value length: {len(value)}', + file_path=fpath, + line_number=self._estimate_line_number(content, m.start()), + severity='CRITICAL', + recommendation={ + 'summary': 'Remove hardcoded secrets and use environment variables or a secrets manager.', + 'steps': [ + 'Move the secret into an environment variable or encrypted store.', + 'Rotate the exposed secret immediately if used in production.', + 'Ensure secrets are not committed to VCS.' + ] + } + ) + + # 2) DB connection strings + # match postgres://... or mysql://... regardless of surrounding quotes + db_pattern = re.compile(r"(?i)(?:postgres(?:ql)?|mysql)://[^\s'\"`<>]+") + for m in db_pattern.finditer(content): + self.add_finding( + title='Hardcoded DB connection string', + description='Found a database connection string in code or config which may contain credentials.', + file_path=fpath, + line_number=self._estimate_line_number(content, m.start()), + severity='HIGH', + recommendation='Move DB credentials to environment variables and avoid committing connection strings.' + ) + + # 3) permissive CORS or wildcard origins (simple checks) + # look for Access-Control-Allow-Origin: * or origin: '*' in JS/TS configs + if re.search(r"Access-Control-Allow-Origin\s*:\s*\*", content) or re.search(r"origin\s*[:=]\s*[\'\"]\*\b", content): + self.add_finding( + title='Permissive CORS configuration', + description='Detected wildcard CORS origin which allows any origin to access resources.', + file_path=fpath, + line_number=None, + severity='MEDIUM', + recommendation={ + 'summary': 'Restrict CORS origins to a specific allowlist.', + 'steps': [ + 'Replace wildcard origin with an explicit list of allowed origins.', + 'If dynamic, validate and sanitize the Origin header before echoing it back.' + ] + } + ) + + return self.findings + + def _estimate_line_number(self, content: str, pos: int) -> Optional[int]: + try: + return content[:pos].count('\n') + 1 + except Exception: + return None diff --git a/Vulnerability_Tool_V2/plugins/jwt_security/README.md b/Vulnerability_Tool_V2/plugins/jwt_security/README.md new file mode 100644 index 0000000..b4ed4e7 --- /dev/null +++ b/Vulnerability_Tool_V2/plugins/jwt_security/README.md @@ -0,0 +1,91 @@ +# JWT Security Plugin + +This plugin (`jwt_security`) checks code and configuration for common JWT-related misconfigurations and usage issues. + +## What it detects + +- Missing authentication protection on endpoints + - Detects HTTP route handlers that do not use the project's authentication middleware (e.g. `authenticateToken`) and flags endpoints that should be protected. +- Low-entropy or weak JWT secrets + - Scans configuration files (e.g. `.env`) and code for JWT secret values that are short, predictable, or clearly not cryptographically strong. +- Direct, ad-hoc JWT verification usage + - Flags locations where `jwt.verify()` (or equivalent) is used directly instead of a centralized AuthService or helper, encouraging a single location for verification and error handling. +- Incomplete JWT error handling + - Detects code paths which call verification without handling common JWT exceptions (expired token, malformed token, not-before, etc.). + +## Rationale +JWTs are powerful but can be misused in ways that reduce their security. This plugin helps find common pattern mistakes early so they can be centralized, hardened, and consistently handled. + +## Configuration +Add plugin configuration under `plugins.jwt_security` in the scanner config YAML. + +Supported keys: + +- `enabled` (bool): Enable or disable the plugin. +- `auth_middleware_names` (list[str]): Additional function/variable names that should be recognised as authentication middleware (default: `['authenticateToken']`). +- `min_secret_length` (int): Minimum allowed length for JWT secrets before flagging (default: 32). +- `exclude_paths` (list[str]): Path substrings to skip during scanning (e.g. `['tests/', 'fixtures/']`). +- `allowlist_secrets` (list[str]): Secret values or keys that should be ignored by the plugin. + +Example config: + +```yaml +plugins: + jwt_security: + enabled: true + auth_middleware_names: + - 'authenticateToken' + min_secret_length: 32 + exclude_paths: + - 'tests/' + - 'fixtures/' + allowlist_secrets: + - 'LOCAL_DEV_SECRET' +``` + +## False positives and mitigation +- Routes defined in third-party libraries or vendored code may be flagged β€” add their paths to `exclude_paths`. +- Test fixtures often include dummy tokens; add test directories to `exclude_paths` or add known dummy token names to `allowlist_secrets`. +- If your project uses a different middleware name, add it to `auth_middleware_names` so route checks recognise it. + +## Remediation suggestions +- Protect endpoints with a single authentication middleware (e.g. `authenticateToken`) and avoid sprinkling `jwt.verify()` calls across handlers. +- Use strong, randomly-generated secrets stored in environment variables or a secrets manager and rotate them regularly. +- Centralize JWT handling in an AuthService class that encapsulates verify/issue logic and error handling. +- Handle common JWT exceptions explicitly and return appropriate status codes (401 for invalid/expired, 403 for forbidden, etc.). + +## Output +Findings are emitted as `SecurityFinding` objects with these fields: +- `title` +- `severity` (LOW/MEDIUM/HIGH/CRITICAL) +- `file_path` +- `line_number` +- `description` +- `plugin_name` ("jwt_security") +- `recommendation` (string or structured dict) + +Example finding JSON snippet: + +```json +{ + "title": "Missing JWT Protection: POST /api/orders", + "severity": "MEDIUM", + "file_path": "routes/orders.js", + "line_number": 42, + "description": "Endpoint POST /api/orders is not protected by authentication middleware.", + "plugin_name": "jwt_security", + "recommendation": { + "summary": "Add authentication middleware to protect this endpoint.", + "steps": [ + "Import authenticateToken middleware", + "Add middleware to the route: router.post('/api/orders', authenticateToken, handler)" + ] + } +} +``` + +## Extending +To add more JWT checks, implement logic in the plugin's `scan()` method and call `self.add_finding(...)` with structured data. Prefer AST-based checks for accuracy where practical. + +## Notes +This plugin uses heuristics and simple static analysis; it may not catch every JWT issue nor be 100% accurate for all code patterns. Use configuration to tune coverage and reduce false positives. diff --git a/Vulnerability_Tool_V2/plugins/jwt_security/__init__.py b/Vulnerability_Tool_V2/plugins/jwt_security/__init__.py new file mode 100644 index 0000000..c41e9e2 --- /dev/null +++ b/Vulnerability_Tool_V2/plugins/jwt_security/__init__.py @@ -0,0 +1 @@ +# JWT Security Plugin Package \ No newline at end of file diff --git a/Vulnerability_Tool_V2/plugins/jwt_security/jwt_config.py b/Vulnerability_Tool_V2/plugins/jwt_security/jwt_config.py new file mode 100644 index 0000000..50fd32c --- /dev/null +++ b/Vulnerability_Tool_V2/plugins/jwt_security/jwt_config.py @@ -0,0 +1,444 @@ +#!/usr/bin/env python3 +""" +JWT Configuration Validation Plugin - Updated for NutriHelp's resolved architecture +""" + +import os +import re +from typing import List, Dict, Any +from ..base_plugin import BaseSecurityPlugin, SecurityFinding + + +class JWTConfigurationPlugin(BaseSecurityPlugin): + """JWT configuration verification plug-in - detection of existing basic configuration""" + + def get_plugin_info(self) -> Dict[str, str]: + return { + 'name': 'JWT Configuration Validator', + 'version': '2.0.1', + 'description': 'Validates JWT security configurations (NutriHelp architecture optimized)', + 'author': 'NutriHelp Security Team' + } + + def get_severity_level(self) -> str: + return "HIGH" + + def scan(self, target_path: str) -> List[SecurityFinding]: + findings = [] + + # Check JWT secret strength + env_file = os.path.join(target_path, '.env') + if os.path.exists(env_file): + with open(env_file, 'r') as f: + for i, line in enumerate(f, 1): + if 'JWT_SECRET' in line: + secret = line.split('=')[1].strip() + if self._is_low_entropy_secret(secret): + findings.append(SecurityFinding( + title="Low Entropy JWT Secret", + severity="MEDIUM", + file_path=".env", + line_number=i, + description="JWT secret appears to have low entropy (predictable patterns).", + plugin=self.__class__.__name__, + recommendation="""Improve JWT secret security: +1. Generate a strong secret using crypto: + const crypto = require('crypto'); + const secret = crypto.randomBytes(64).toString('hex'); + +2. Use environment-specific secrets +3. Implement secret rotation +4. Consider using asymmetric keys for larger systems""" + )) + + # Check direct JWT usage + middleware_file = os.path.join(target_path, 'middleware.js') + if os.path.exists(middleware_file): + findings.append(SecurityFinding( + title="Direct JWT Usage Instead of AuthService", + severity="MEDIUM", + file_path="middleware.js", + description="Direct jwt.verify() usage detected instead of centralized authService.", + plugin=self.__class__.__name__, + recommendation="""Centralize JWT verification: +1. Create AuthService class +2. Move all JWT operations to AuthService +3. Use AuthService.verifyToken() in middleware +4. Add comprehensive error handling""" + )) + + # Check error handling + findings.append(SecurityFinding( + title="Incomplete JWT Error Handling", + severity="LOW", + file_path="middleware.js", + description="JWT verification lacks comprehensive error handling.", + plugin=self.__class__.__name__, + recommendation="""Implement proper JWT error handling: +1. Handle TokenExpiredError +2. Handle JsonWebTokenError +3. Handle NotBeforeError +4. Add logging for security events +5. Return appropriate status codes""" + )) + + return findings + + def _check_env_files(self, target_path: str): + """Check environment variable configuration""" + env_files = ['.env', '.env.example', '.env.local'] + + for env_file in env_files: + env_path = os.path.join(target_path, env_file) + if os.path.exists(env_path): + self._analyze_env_file(env_path, target_path) + + def _analyze_env_file(self, env_path: str, base_path: str): + """Analyze environment variable files - Based on existing configuration checks""" + try: + content = self.read_file_safe(env_path) + if not content: + return + + relative_path = self.get_relative_path(env_path, base_path) + lines = content.split('\n') + + jwt_secret = None + jwt_secret_line = None + + # Find JWT_SECRET configuration + for i, line in enumerate(lines, 1): + line_clean = line.strip() + + if re.match(r'JWT_SECRET\s*=', line_clean): + jwt_secret_match = re.search(r'JWT_SECRET\s*=\s*(.+)', line_clean) + if jwt_secret_match: + jwt_secret = jwt_secret_match.group(1).strip('\'"') + jwt_secret_line = i + + # Validate JWT secret strength + if jwt_secret: + self._validate_jwt_secret_strength(jwt_secret, jwt_secret_line, relative_path) + + # Check additional security configurations + self._check_additional_security_config(content, relative_path) + + except Exception as e: + self.logger.error(f"Error analyzing env file {env_path}: {e}") + + def _validate_jwt_secret_strength(self, secret: str, line_number: int, file_path: str): + """Validate JWT secret strength""" + min_length = self.config.get('min_secret_length', 32) + + secret_clean = secret.strip('\'"').strip() + + # Check length + if len(secret_clean) < min_length: + self.add_finding( + title=f"JWT Secret Too Short ({len(secret_clean)} chars)", + description=f"JWT secret is {len(secret_clean)} characters. " + f"Recommend at least {min_length} characters for production security.", + file_path=file_path, + line_number=line_number, + severity="MEDIUM", # Medium priority + recommendation="Generate a stronger JWT secret using crypto.randomBytes(64).toString('hex')" + ) + + # Check entropy - Is it too simple? + if self._is_low_entropy_secret(secret_clean): + self.add_finding( + title="Low Entropy JWT Secret", + description="JWT secret appears to have low entropy (predictable patterns). " + "This could make the secret easier to guess.", + file_path=file_path, + line_number=line_number, + severity="MEDIUM", + recommendation="Use cryptographically secure random generation for JWT secrets." + ) + + def _is_low_entropy_secret(self, secret: str) -> bool: + """Check if the secret has low entropy""" + # Check for repeated characters + if len(set(secret)) < len(secret) * 0.6: # If unique characters are less than 60% + return True + + # Check for common patterns + patterns = [r'(.)\1{3,}', r'123', r'abc', r'qwerty'] + for pattern in patterns: + if re.search(pattern, secret.lower()): + return True + + return False + + def _check_additional_security_config(self, content: str, file_path: str): + """Check additional security configurations""" + # Check for missing other important configurations + required_configs = { + 'SUPABASE_URL': 'Database connection configuration', + 'SUPABASE_ANON_KEY': 'Database authentication key' + } + + for config_key, description in required_configs.items(): + if config_key not in content: + self.add_finding( + title=f"Missing Configuration: {config_key}", + description=f"Required configuration {config_key} not found. " + f"This is needed for: {description}", + file_path=file_path, + severity="LOW", + recommendation=f"Add {config_key} configuration to your .env file." + ) + + def _check_jwt_implementation_consistency(self, target_path: str): + """Check JWT implementation consistency""" + + # Check for two JWT middleware files + jwt_files = [ + 'authenticateToken.js', # New version + 'middleware.js', # Old version + 'middleware/authenticateToken.js' + ] + + found_implementations = [] + + for jwt_file in jwt_files: + jwt_path = os.path.join(target_path, jwt_file) + if os.path.exists(jwt_path): + found_implementations.append(jwt_path) + self._analyze_jwt_implementation(jwt_path, target_path) + + # If multiple JWT implementations are found, issue a warning + if len(found_implementations) > 1: + self.add_finding( + title="Multiple JWT Implementation Files Detected", + description=f"Found {len(found_implementations)} different JWT middleware files: " + f"{', '.join([os.path.basename(f) for f in found_implementations])}. " + "This could lead to inconsistent authentication behavior.", + file_path="Multiple files", + severity="MEDIUM", + recommendation="Consider consolidating to a single JWT middleware implementation " + "to avoid confusion and ensure consistent behavior." + ) + + def _analyze_jwt_implementation(self, file_path: str, base_path: str): + """Analyze JWT implementation file - Check best practices""" + try: + content = self.read_file_safe(file_path) + if not content: + return + + relative_path = self.get_relative_path(file_path, base_path) + lines = content.split('\n') + + # Check if the new authService is used + uses_auth_service = 'authService' in content + uses_direct_jwt = 'jwt.verify' in content + + if uses_direct_jwt and not uses_auth_service: + self.add_finding( + title="Direct JWT Usage Instead of AuthService", + description=f"File {os.path.basename(file_path)} uses direct jwt.verify() " + "instead of the centralized authService. This bypasses your " + "unified authentication logic.", + file_path=relative_path, + severity="MEDIUM", + recommendation="Consider updating this file to use authService.verifyAccessToken() " + "for consistent authentication behavior." + ) + + # Check error handling completeness + self._check_error_handling(content, lines, relative_path) + + except Exception as e: + self.logger.error(f"Error analyzing JWT implementation {file_path}: {e}") + + def _check_error_handling(self, content: str, lines: List[str], file_path: str): + """Check error handling completeness""" + + # Check for appropriate error responses + error_patterns = [ + 'TokenExpiredError', + 'JsonWebTokenError', + 'TOKEN_EXPIRED', + 'INVALID_TOKEN' + ] + + has_proper_error_handling = any(pattern in content for pattern in error_patterns) + + if 'jwt.verify' in content and not has_proper_error_handling: + self.add_finding( + title="Incomplete JWT Error Handling", + description="JWT verification code lacks comprehensive error handling. " + "Should handle TokenExpiredError, JsonWebTokenError, and other JWT-related errors.", + file_path=file_path, + severity="LOW", + recommendation="Add comprehensive error handling for different JWT error types " + "to provide better user experience and security." + ) + + def _check_auth_service_config(self, target_path: str): + """Check authService configuration""" + auth_service_path = os.path.join(target_path, 'services', 'authService.js') + + if not os.path.exists(auth_service_path): + return + + try: + content = self.read_file_safe(auth_service_path) + if not content: + return + + relative_path = self.get_relative_path(auth_service_path, target_path) + + # Check access token expiry configuration + access_token_pattern = r'accessTokenExpiry\s*=\s*[\'"`]([^\'"`]+)[\'"`]' + refresh_token_pattern = r'refreshTokenExpiry\s*=\s*([^;]+);' + + access_match = re.search(access_token_pattern, content) + refresh_match = re.search(refresh_token_pattern, content) + + if access_match: + access_expiry = access_match.group(1) + if access_expiry not in ['15m', '10m', '5m']: # Recommended short-term + self.add_finding( + title=f"Long Access Token Expiry: {access_expiry}", + description=f"Access token expiry is set to {access_expiry}. " + "For security, recommend 15 minutes or less.", + file_path=relative_path, + severity="LOW", + recommendation="Set access token expiry to 15m or shorter for better security." + ) + + # Check algorithm configuration + if 'HS256' not in content and 'algorithm' in content: + self.add_finding( + title="Non-Standard JWT Algorithm", + description="JWT signing algorithm might not be explicitly set to HS256. " + "This could lead to algorithm confusion attacks.", + file_path=relative_path, + severity="LOW", + recommendation="Explicitly specify 'HS256' algorithm in JWT configuration." + ) + + except Exception as e: + self.logger.error(f"Error analyzing auth service {auth_service_path}: {e}") + + def _check_middleware_configuration(self, target_path: str): + """Check middleware configuration - Check global configuration in server.js""" + server_path = os.path.join(target_path, 'server.js') + + if not os.path.exists(server_path): + return + + try: + content = self.read_file_safe(server_path) + if not content: + return + + relative_path = self.get_relative_path(server_path, target_path) + + # Check for global authentication middleware (may not be necessary, but worth a reminder) + if 'authenticateToken' in content and 'app.use' in content: + # If there is global JWT middleware, check if it is reasonable + lines = content.split('\n') + for i, line in enumerate(lines, 1): + if 'app.use' in line and 'authenticateToken' in line: + self.add_finding( + title="Global JWT Middleware Detected", + description="Found global JWT middleware in server.js. " + "This will require authentication for ALL routes including public ones.", + file_path=relative_path, + line_number=i, + severity="HIGH", + recommendation="Consider using route-specific JWT middleware instead of global middleware " + "to avoid blocking public endpoints." + ) + + except Exception as e: + self.logger.error(f"Error analyzing server configuration {server_path}: {e}") + + def generate_recommendation(self, issue_type: str) -> str: + """Generate specific recommendation based on issue type""" + if issue_type == "low_entropy": + return """Improve JWT secret security: + +1. Generate a strong secret: + const crypto = require('crypto'); + const secret = crypto.randomBytes(64).toString('hex'); + +2. Store in environment variables: + JWT_SECRET=your-generated-secret + +3. Use different secrets for different environments +4. Rotate secrets periodically +5. Consider using asymmetric keys (RS256) for larger systems""" + + elif issue_type == "direct_jwt": + return """Centralize JWT verification: + +1. Create an auth service: + // services/authService.js + class AuthService { + static verifyToken(token) { + return jwt.verify(token, process.env.JWT_SECRET); + } + } + +2. Update middleware: + const AuthService = require('../services/authService'); + + function authenticateToken(req, res, next) { + try { + const token = req.headers.authorization?.split(' ')[1]; + req.user = AuthService.verifyToken(token); + next(); + } catch (err) { + res.status(401).json({ error: 'Invalid token' }); + } + }""" + + elif issue_type == "multiple_implementation": + return """Consolidate JWT implementations: + +1. Remove duplicate files +2. Create a single auth middleware directory: + /middleware + /auth + index.js - Main export + verify.js - Token verification + generate.js - Token generation + refresh.js - Token refresh logic + +3. Update all imports to use the centralized version +4. Add tests to ensure consistent behavior""" + + else: # incomplete_error + return """Improve JWT error handling: + +1. Handle specific JWT errors: + try { + const decoded = jwt.verify(token, secret); + req.user = decoded; + } catch (err) { + if (err instanceof jwt.TokenExpiredError) { + return res.status(401).json({ error: 'Token expired' }); + } + if (err instanceof jwt.JsonWebTokenError) { + return res.status(401).json({ error: 'Invalid token' }); + } + return res.status(401).json({ error: 'Authentication failed' }); + }""" + + +# Test function +def test_plugin(): + """Test plugin basic functionality""" + plugin = JWTConfigurationPlugin() + + print("Plugin Info:", plugin.get_plugin_info()) + print("Severity Level:", plugin.get_severity_level()) + print("βœ… Updated JWT Configuration Plugin initialized successfully") + + +if __name__ == '__main__': + test_plugin() \ No newline at end of file diff --git a/Vulnerability_Tool_V2/plugins/jwt_security/jwt_missing.py b/Vulnerability_Tool_V2/plugins/jwt_security/jwt_missing.py new file mode 100644 index 0000000..85f4ee1 --- /dev/null +++ b/Vulnerability_Tool_V2/plugins/jwt_security/jwt_missing.py @@ -0,0 +1,180 @@ +#!/usr/bin/env python3 +""" +JWT Missing Protection Plugin +Detecting API endpoints missing JWT protection +""" + +import os +import re +import logging +from typing import List, Dict, Any, Optional +from plugins.base_plugin import BaseSecurityPlugin, SecurityFinding + +class JWTMissingProtectionPlugin(BaseSecurityPlugin): + """JWT Missing Protection Detection Plugin""" + + name = "JWT Missing Protection Detector" + version = "2.0.0" + description = "Detect API endpoints missing JWT authentication protection" + + def __init__(self, config: Dict[str, Any] = None): + super().__init__(config or {}) + self.logger = logging.getLogger(__name__) + + # Public endpoints (no JWT protection needed) + self.public_endpoints = { + '/health', '/api-docs', '/swagger', '/login', '/register', + '/auth/login', '/auth/register', '/auth/refresh', '/signup', + '/contactus', '/articles' + } + + # File extensions to scan + self.target_extensions = ('.js', '.ts', '.py') + + def get_plugin_info(self) -> Dict[str, str]: + return { + "id": "jwt_missing_protection", + "name": self.name, + "version": self.version, + "description": self.description, + } + + def get_severity_level(self) -> str: + return "medium" + + def scan(self, target_path: str = None) -> List[SecurityFinding]: + """Scan the target path for missing JWT protection endpoints""" + findings = [] + + if not target_path or not os.path.exists(target_path): + return findings + + try: + for root, dirs, files in os.walk(target_path): + # Skip specific directories + dirs[:] = [d for d in dirs if d not in {'.git', 'node_modules', '__pycache__', '.venv'}] + + for file in files: + if file.endswith(self.target_extensions): + file_path = os.path.join(root, file) + file_findings = self._scan_file(file_path, target_path) + findings.extend(file_findings) + + except Exception as e: + self.logger.error(f"Error occurred during scanning: {e}") + + return findings + + def _scan_file(self, file_path: str, base_path: str) -> List[SecurityFinding]: + """Scan a single file""" + findings = [] + + try: + with open(file_path, 'r', encoding='utf-8', errors='ignore') as f: + content = f.read() + lines = content.split('\n') + + relative_path = os.path.relpath(file_path, base_path) + + # Check route definitions + route_patterns = [ + r'app\.(get|post|put|delete|patch)\s*\(\s*[\'"`]([^\'"`]+)[\'"`]', + r'router\.(get|post|put|delete|patch)\s*\(\s*[\'"`]([^\'"`]+)[\'"`]', + ] + + for i, line in enumerate(lines, 1): + for pattern in route_patterns: + matches = re.finditer(pattern, line, re.IGNORECASE) + + for match in matches: + if len(match.groups()) >= 2: + method = match.group(1).upper() + endpoint = match.group(2) + else: + continue + + # Skip public endpoints + if self._is_public_endpoint(endpoint): + continue + + # Check for JWT protection + if not self._has_jwt_protection(line, lines, i): + finding = SecurityFinding( + title=f"Missing JWT Protection: {method} {endpoint}", + description=f"API endpoint {method} {endpoint} lacks JWT authentication middleware", + file_path=relative_path, + line_number=i, + severity="MEDIUM", + plugin=self.__class__.__name__, + recommendation=self._get_recommendation(endpoint, method) + ) + findings.append(finding) + + except Exception as e: + self.logger.error(f"Error occurred while scanning file {file_path}: {e}") + + return findings + + def _is_public_endpoint(self, endpoint: str) -> bool: + """Check if the endpoint is public""" + endpoint = endpoint.lower() + return any(pub in endpoint for pub in self.public_endpoints) + + def _has_jwt_protection(self, line: str, all_lines: List[str], line_number: int) -> bool: + """Check for JWT protection middleware""" + # Check current line + jwt_patterns = [ + 'authenticateToken', 'authMiddleware', 'verifyToken', + 'requireAuth', 'jwt', 'authenticate' + ] + + line_lower = line.lower() + if any(pattern.lower() in line_lower for pattern in jwt_patterns): + return True + + # Check surrounding lines + start = max(0, line_number - 3) + end = min(len(all_lines), line_number + 3) + + for i in range(start, end): + if i < len(all_lines): + check_line = all_lines[i].lower() + if any(pattern.lower() in check_line for pattern in jwt_patterns): + return True + + return False + + def _get_recommendation(self, endpoint: str, method: str) -> str: + """Get fix recommendation""" + # Return a structured recommendation + return { + 'summary': f'Protect the {method} {endpoint} endpoint with authentication middleware.', + 'steps': [ + f"Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');", + f"Add middleware to route: router.{method.lower()}('{endpoint}', authenticateToken, (req, res) => {{ /* handler */ }});", + "Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly." + ], + 'code': f"router.{method.lower()}('{endpoint}', authenticateToken, (req, res) => {{\n // Your route handler\n}});" + } + + def run(self, target_path: str = None) -> List[SecurityFinding]: + """Backward compatibility method""" + return self.scan(target_path) + +# Export plugin class +Plugin = JWTMissingProtectionPlugin + +def test_plugin(): + """Test plugin functionality""" + try: + plugin = JWTMissingProtectionPlugin() + info = plugin.get_plugin_info() + print("Plugin Info:", info) + print("βœ… JWT Missing Protection Plugin initialized successfully") + return True + except Exception as e: + print(f"❌ Plugin test failed: {e}") + return False + +if __name__ == '__main__': + test_plugin() \ No newline at end of file diff --git a/Vulnerability_Tool_V2/plugins/rls_security/__init__.py b/Vulnerability_Tool_V2/plugins/rls_security/__init__.py new file mode 100644 index 0000000..35e2b56 --- /dev/null +++ b/Vulnerability_Tool_V2/plugins/rls_security/__init__.py @@ -0,0 +1 @@ +# RLS Security Plugin Package diff --git a/Vulnerability_Tool_V2/plugins/rls_security/rls_missing.py b/Vulnerability_Tool_V2/plugins/rls_security/rls_missing.py new file mode 100644 index 0000000..f676d06 --- /dev/null +++ b/Vulnerability_Tool_V2/plugins/rls_security/rls_missing.py @@ -0,0 +1,41 @@ +#!/usr/bin/env python3 +""" +Minimal RLS Missing Protection Plugin +Minimized RLS plugin to prevent dependency errors +""" + +from plugins.base_plugin import BaseSecurityPlugin, SecurityFinding +from typing import List, Dict, Any + +class RLSMissingProtectionPlugin(BaseSecurityPlugin): + """Minimized RLS Missing Protection Detection Plugin""" + + name = "RLS Missing Protection Detector" + version = "1.0.0" + description = "Minimal RLS protection detector to prevent dependency errors" + + def __init__(self, config: Dict[str, Any] = None): + super().__init__(config or {}) + + def get_plugin_info(self) -> Dict[str, str]: + return { + "id": "rls_missing_protection", + "name": self.name, + "version": self.version, + "description": self.description, + } + + def get_severity_level(self) -> str: + return "low" + + def scan(self, target_path: str = None) -> List[SecurityFinding]: + """Minimized scan - no actual checks performed to avoid errors""" + # Return empty results to avoid false positives + return [] + + def run(self, target_path: str = None) -> List[SecurityFinding]: + """Backward compatibility method""" + return self.scan(target_path) + +# Export plugin class +Plugin = RLSMissingProtectionPlugin diff --git a/Vulnerability_Tool_V2/plugins/rls_security_disabled/rls_missing.py b/Vulnerability_Tool_V2/plugins/rls_security_disabled/rls_missing.py new file mode 100644 index 0000000..192b280 --- /dev/null +++ b/Vulnerability_Tool_V2/plugins/rls_security_disabled/rls_missing.py @@ -0,0 +1,163 @@ +#!/usr/bin/env python3 +""" +RLS Missing Protection Detector + +A simple, robust placeholder implementation that searches your codebase for keywords/statements related to Row-Level Security (RLS). +If no obvious RLS configuration or enablement statements are found, a warning is returned. +The plugin's output uses a common dictionary structure, making it easy to integrate with your project's existing PluginManager/Scanner. +""" + +from __future__ import annotations +import re +import os +import logging +from typing import List, Dict, Optional + +try: + # Base class for project definitions in a formal environment + from plugins.base_plugin import BaseSecurityPlugin, SecurityFinding +except Exception: + # Provide a minimal compatible alternative for single-file testing + class BaseSecurityPlugin: + name = "BaseSecurityPlugin" + version = "0.0.0" + + def __init__(self, *a, **k): + pass + +logger = logging.getLogger("PluginManager") + + +class RLSMissingProtectionPlugin(BaseSecurityPlugin): + """Plugin for detecting missing Row-Level Security (RLS) protection.""" + + name = "RLS Missing Protection Detector" + version = "1.0.0" + description = "Detect potential missing Row-Level Security (RLS) protections." + + # File type and search keyword/regex + _target_extensions = (".sql", ".ddl", ".yml", ".yaml", ".py", ".conf", ".ini", ".json") + _patterns = [ + re.compile(r"row\s*level\s*security", re.I), + re.compile(r"enable\s+row\s+level\s+security", re.I), + re.compile(r"alter\s+table\s+.*\s+enable\s+row\s+level\s+security", re.I), + re.compile(r"\bpolicy\b", re.I), # SQL POLICY + re.compile(r"\brls\b", re.I), + re.compile(r"rls_enabled|enable_rls|row_level_security", re.I), + ] + + def __init__(self, config: Optional[Dict] = None): + super().__init__(config) + self.project_root = os.getcwd() + + def get_plugin_info(self) -> Dict[str, str]: + """Return plugin information (for loader/UI use)""" + return { + "name": self.name, + "version": self.version, + "description": self.description, + } + + def get_severity_level(self) -> str: + """Default severity level (used when no clear evidence is found)""" + return "MEDIUM" + + def _is_target_file(self, path: str) -> bool: + return any(path.lower().endswith(ext) for ext in self._target_extensions) + + def _scan_file(self, path: str) -> List[SecurityFinding]: + """Scan a single file for RLS patterns - RETURNS STANDARD SecurityFinding objects""" + findings = [] + try: + with open(path, "r", encoding="utf-8", errors="ignore") as fh: + for i, line in enumerate(fh, start=1): + for pat in self._patterns: + if pat.search(line): + # Create standard SecurityFinding object + finding = SecurityFinding( + title="Possible RLS-related statement found", + severity="INFO", + file_path=os.path.relpath(path, self.project_root), + description=f"Pattern '{pat.pattern}' matched: {line.strip()}", + line_number=i, + plugin=self.name, + recommendation="Review this RLS configuration to ensure it's properly implemented and covers all sensitive data access patterns." + ) + findings.append(finding) + break + except Exception as e: + logger.debug("Failed to read %s: %s", path, e) + return findings + + def scan(self, target_path: Optional[str] = None) -> List[SecurityFinding]: + """ + Run the RLS detection. Returns standard SecurityFinding objects. + """ + base_path = target_path or self.project_root + logger.info("Running RLS Missing Protection Detector on %s", base_path) + findings = [] + found_evidence = False + + for root, dirs, files in os.walk(base_path): + skip_dirs = {"venv", ".venv", "__pycache__", "node_modules", ".git"} + dirs[:] = [d for d in dirs if d not in skip_dirs] + + for fname in files: + fpath = os.path.join(root, fname) + if not self._is_target_file(fpath): + continue + file_findings = self._scan_file(fpath) + if file_findings: + found_evidence = True + findings.extend(file_findings) + + if not found_evidence: + # Create standard SecurityFinding for missing RLS + finding = SecurityFinding( + title="Potential missing Row-Level Security (RLS)", + severity=self.get_severity_level(), + file_path="General Project Scan", + description=( + "No obvious RLS-related configuration or SQL statements were detected. " + "Ensure that sensitive tables enforce row-level access controls (policies)." + ), + line_number=None, + plugin=self.name, + recommendation="""To implement Row-Level Security (RLS): + +1. Enable RLS on sensitive tables: + ALTER TABLE your_table ENABLE ROW LEVEL SECURITY; + +2. Create RLS policies: + CREATE POLICY user_isolation_policy ON your_table + FOR ALL + USING (user_id = current_user_id()); + +3. Test RLS effectiveness: + - Verify different users can only access their own data + - Confirm superusers bypass RLS as expected + - Check policy performance impact + +4. Consider implementing for these table types: + - User profiles and personal data + - Financial records + - Medical information + - Private communications + - Access logs and audit trails""" + ) + findings.append(finding) + + logger.info("RLS detector finished, findings: %d", len(findings)) + return findings + + # Keep run() for backward compatibility + def run(self) -> List[SecurityFinding]: + return self.scan() + + +# Compatible exports / convenience factory + module instance +Plugin = RLSMissingProtectionPlugin +get_plugin = lambda *a, **kw: RLSMissingProtectionPlugin(*a, **kw) +create_plugin = lambda *a, **kw: RLSMissingProtectionPlugin(*a, **kw) +plugin = RLSMissingProtectionPlugin() +__all__ = ["RLSMissingProtectionPlugin", "Plugin", "get_plugin", "create_plugin", "plugin"] \ No newline at end of file diff --git a/Vulnerability_Tool_V2/reports/security_report_scan_20250907_090434.html b/Vulnerability_Tool_V2/reports/security_report_scan_20250907_090434.html new file mode 100644 index 0000000..9e2577a --- /dev/null +++ b/Vulnerability_Tool_V2/reports/security_report_scan_20250907_090434.html @@ -0,0 +1,2368 @@ + + + + + + + NutriHelp Security Scanner V2.0 Report + + + +
+
+

πŸ”’ NutriHelp Security Scanner V2.0

+
+
Scan time: 2025-09-07 09:04:35
+
Target path: /Users/lichaohui/Desktop/Code/782/Nutrihelp-api
+
Scanner version: 2.0.0
+
+
+ +
+
+
0
+
Critical Issues
+
+
+
0
+
High Severity
+
+
+
68
+
Medium Severity
+
+
+
1
+
Low Severity
+
+
+ +
+
+
+
189
+
Files Scanned
+
+
+
2
+
Plugins Used
+
+
+
69
+
Total Issues
+
+
+ +

πŸ” Detailed Findings

+
+
+
Missing JWT Protection: GET /
+ MEDIUM +
+ +
+ πŸ“„ + jwt server.js + (Line 11) +
+ +
API endpoint GET / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /scanner/plugins
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/api/scanner_api.py + (Line 148) +
+ +
API endpoint GET /scanner/plugins lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /scanner/plugins endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/scanner/plugins', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/scanner/plugins', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /scanner/scan
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/api/scanner_api.py + (Line 167) +
+ +
API endpoint POST /scanner/scan lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST /scanner/scan endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/scanner/scan', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/scanner/scan', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /scanner/scan/{scan_id}/status
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/api/scanner_api.py + (Line 198) +
+ +
API endpoint GET /scanner/scan/{scan_id}/status lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /scanner/scan/{scan_id}/status endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/scanner/scan/{scan_id}/status', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/scanner/scan/{scan_id}/status', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /scanner/scan/{scan_id}/result
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/api/scanner_api.py + (Line 213) +
+ +
API endpoint GET /scanner/scan/{scan_id}/result lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /scanner/scan/{scan_id}/result endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/scanner/scan/{scan_id}/result', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/scanner/scan/{scan_id}/result', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /scanner/scan/{scan_id}/report
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/api/scanner_api.py + (Line 230) +
+ +
API endpoint GET /scanner/scan/{scan_id}/report lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /scanner/scan/{scan_id}/report endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/scanner/scan/{scan_id}/report', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/scanner/scan/{scan_id}/report', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /scanner/scan/quick
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/api/scanner_api.py + (Line 353) +
+ +
API endpoint POST /scanner/scan/quick lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST /scanner/scan/quick endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/scanner/scan/quick', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/scanner/scan/quick', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /users/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/applications.py + (Line 235) +
+ +
API endpoint GET /users/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /users/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/users/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/users/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /items/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/applications.py + (Line 236) +
+ +
API endpoint GET /items/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /items/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/items/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/items/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /items/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/applications.py + (Line 388) +
+ +
API endpoint GET /items/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /items/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/items/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/items/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /items/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/applications.py + (Line 1802) +
+ +
API endpoint GET /items/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /items/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/items/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/items/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: PUT /items/{item_id}
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/applications.py + (Line 2180) +
+ +
API endpoint PUT /items/{item_id} lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the PUT /items/{item_id} endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.put('/items/{item_id}', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.put('/items/{item_id}', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /items/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/applications.py + (Line 2558) +
+ +
API endpoint POST /items/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST /items/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/items/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/items/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: DELETE /items/{item_id}
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/applications.py + (Line 2931) +
+ +
API endpoint DELETE /items/{item_id} lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the DELETE /items/{item_id} endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.delete('/items/{item_id}', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.delete('/items/{item_id}', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: PATCH /items/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/applications.py + (Line 4055) +
+ +
API endpoint PATCH /items/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the PATCH /items/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.patch('/items/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.patch('/items/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /send-notification/{email}
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/background.py + (Line 31) +
+ +
API endpoint POST /send-notification/{email} lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST /send-notification/{email} endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/send-notification/{email}', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/send-notification/{email}', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /users/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/routing.py + (Line 614) +
+ +
API endpoint GET /users/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /users/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/users/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/users/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /users/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/routing.py + (Line 1250) +
+ +
API endpoint GET /users/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /users/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/users/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/users/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /items/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/routing.py + (Line 1710) +
+ +
API endpoint GET /items/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /items/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/items/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/items/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: PUT /items/{item_id}
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/routing.py + (Line 2092) +
+ +
API endpoint PUT /items/{item_id} lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the PUT /items/{item_id} endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.put('/items/{item_id}', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.put('/items/{item_id}', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /items/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/routing.py + (Line 2474) +
+ +
API endpoint POST /items/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST /items/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/items/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/items/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: DELETE /items/{item_id}
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/routing.py + (Line 2851) +
+ +
API endpoint DELETE /items/{item_id} lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the DELETE /items/{item_id} endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.delete('/items/{item_id}', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.delete('/items/{item_id}', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: PATCH /items/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/routing.py + (Line 3992) +
+ +
API endpoint PATCH /items/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the PATCH /items/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.patch('/items/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.patch('/items/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /items/{item_id}
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/exceptions.py + (Line 29) +
+ +
API endpoint GET /items/{item_id} lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /items/{item_id} endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/items/{item_id}', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/items/{item_id}', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /items/{item_id}
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/param_functions.py + (Line 299) +
+ +
API endpoint GET /items/{item_id} lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /items/{item_id} endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/items/{item_id}', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/items/{item_id}', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /items/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/param_functions.py + (Line 2272) +
+ +
API endpoint GET /items/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /items/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/items/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/items/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /users/me/items/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/param_functions.py + (Line 2353) +
+ +
API endpoint GET /users/me/items/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /users/me/items/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/users/me/items/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/users/me/items/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /files/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/datastructures.py + (Line 53) +
+ +
API endpoint POST /files/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST /files/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/files/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/files/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /uploadfile/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/datastructures.py + (Line 58) +
+ +
API endpoint POST /uploadfile/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST /uploadfile/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/uploadfile/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/uploadfile/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /items/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/security/api_key.py + (Line 49) +
+ +
API endpoint GET /items/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /items/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/items/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/items/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /items/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/security/api_key.py + (Line 141) +
+ +
API endpoint GET /items/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /items/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/items/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/items/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /items/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/security/api_key.py + (Line 229) +
+ +
API endpoint GET /items/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /items/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/items/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/items/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /users/me
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/security/http.py + (Line 124) +
+ +
API endpoint GET /users/me lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /users/me endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/users/me', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/users/me', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /users/me
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/security/http.py + (Line 244) +
+ +
API endpoint GET /users/me lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /users/me endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/users/me', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/users/me', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /users/me
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/security/http.py + (Line 348) +
+ +
API endpoint GET /users/me lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /users/me endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/users/me', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/users/me', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /
+ MEDIUM +
+ +
+ πŸ“„ + routes/imageClassification.js + (Line 19) +
+ +
API endpoint POST / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /test
+ MEDIUM +
+ +
+ πŸ“„ + routes/scanner.js + (Line 22) +
+ +
API endpoint GET /test lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /test endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/test', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/test', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /plugins
+ MEDIUM +
+ +
+ πŸ“„ + routes/scanner.js + (Line 164) +
+ +
API endpoint GET /plugins lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /plugins endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/plugins', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/plugins', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /scan
+ MEDIUM +
+ +
+ πŸ“„ + routes/scanner.js + (Line 221) +
+ +
API endpoint POST /scan lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST /scan endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/scan', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/scan', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /scan/:scanId/status
+ MEDIUM +
+ +
+ πŸ“„ + routes/scanner.js + (Line 293) +
+ +
API endpoint GET /scan/:scanId/status lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /scan/:scanId/status endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/scan/:scanId/status', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/scan/:scanId/status', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /scan/:scanId/result
+ MEDIUM +
+ +
+ πŸ“„ + routes/scanner.js + (Line 337) +
+ +
API endpoint GET /scan/:scanId/result lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /scan/:scanId/result endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/scan/:scanId/result', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/scan/:scanId/result', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /scan/:scanId/report
+ MEDIUM +
+ +
+ πŸ“„ + routes/scanner.js + (Line 399) +
+ +
API endpoint GET /scan/:scanId/report lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /scan/:scanId/report endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/scan/:scanId/report', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/scan/:scanId/report', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /quick-scan
+ MEDIUM +
+ +
+ πŸ“„ + routes/scanner.js + (Line 455) +
+ +
API endpoint POST /quick-scan lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST /quick-scan endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/quick-scan', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/quick-scan', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: PUT /update-by-identifier
+ MEDIUM +
+ +
+ πŸ“„ + routes/userprofile.js + (Line 14) +
+ +
API endpoint PUT /update-by-identifier lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the PUT /update-by-identifier endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.put('/update-by-identifier', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.put('/update-by-identifier', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /
+ MEDIUM +
+ +
+ πŸ“„ + routes/upload.js + (Line 5) +
+ +
API endpoint POST / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /
+ MEDIUM +
+ +
+ πŸ“„ + routes/waterIntake.js + (Line 5) +
+ +
API endpoint POST / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /
+ MEDIUM +
+ +
+ πŸ“„ + routes/signup.js + (Line 11) +
+ +
API endpoint POST / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /
+ MEDIUM +
+ +
+ πŸ“„ + routes/login.js + (Line 11) +
+ +
API endpoint POST / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /mfa
+ MEDIUM +
+ +
+ πŸ“„ + routes/login.js + (Line 16) +
+ +
API endpoint POST /mfa lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST /mfa endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/mfa', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/mfa', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /createRecipe
+ MEDIUM +
+ +
+ πŸ“„ + routes/recipe.js + (Line 8) +
+ +
API endpoint POST /createRecipe lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST /createRecipe endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/createRecipe', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/createRecipe', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /
+ MEDIUM +
+ +
+ πŸ“„ + routes/recipe.js + (Line 10) +
+ +
API endpoint POST / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: DELETE /
+ MEDIUM +
+ +
+ πŸ“„ + routes/recipe.js + (Line 11) +
+ +
API endpoint DELETE / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the DELETE / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.delete('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.delete('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /
+ MEDIUM +
+ +
+ πŸ“„ + routes/recipeNutritionlog.js + (Line 27) +
+ +
API endpoint GET / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /classify
+ MEDIUM +
+ +
+ πŸ“„ + routes/routes.js + (Line 32) +
+ +
API endpoint POST /classify lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST /classify endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/classify', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/classify', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /
+ MEDIUM +
+ +
+ πŸ“„ + routes/userfeedback.js + (Line 8) +
+ +
API endpoint POST / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /
+ MEDIUM +
+ +
+ πŸ“„ + routes/healthNews.js + (Line 44) +
+ +
API endpoint GET / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /
+ MEDIUM +
+ +
+ πŸ“„ + routes/healthNews.js + (Line 156) +
+ +
API endpoint POST / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: PUT /
+ MEDIUM +
+ +
+ πŸ“„ + routes/healthNews.js + (Line 214) +
+ +
API endpoint PUT / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the PUT / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.put('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.put('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: DELETE /
+ MEDIUM +
+ +
+ πŸ“„ + routes/healthNews.js + (Line 238) +
+ +
API endpoint DELETE / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the DELETE / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.delete('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.delete('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /generate-baseline
+ MEDIUM +
+ +
+ πŸ“„ + routes/systemRoutes.js + (Line 50) +
+ +
API endpoint POST /generate-baseline lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST /generate-baseline endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/generate-baseline', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/generate-baseline', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /integrity-check
+ MEDIUM +
+ +
+ πŸ“„ + routes/systemRoutes.js + (Line 59) +
+ +
API endpoint GET /integrity-check lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /integrity-check endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/integrity-check', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/integrity-check', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /
+ MEDIUM +
+ +
+ πŸ“„ + routes/filter.js + (Line 7) +
+ +
API endpoint GET / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /
+ MEDIUM +
+ +
+ πŸ“„ + routes/articles.js + (Line 5) +
+ +
API endpoint GET / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /:user_id
+ MEDIUM +
+ +
+ πŸ“„ + routes/notifications.js + (Line 21) +
+ +
API endpoint GET /:user_id lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /:user_id endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/:user_id', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/:user_id', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /
+ MEDIUM +
+ +
+ πŸ“„ + routes/contactus.js + (Line 14) +
+ +
API endpoint POST / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Low Entropy JWT Secret
+ MEDIUM +
+ +
+ πŸ“„ + .env + (Line 8) +
+ +
JWT secret appears to have low entropy (predictable patterns).
+ +
+ πŸ’‘ Recommendation: + Improve JWT secret security:
1. Generate a strong secret using crypto:
const crypto = require('crypto');
const secret = crypto.randomBytes(64).toString('hex');

2. Use environment-specific secrets
3. Implement secret rotation
4. Consider using asymmetric keys for larger systems +

+ +
+ Plugin: JWTConfigurationPlugin +
+
+ +
+
+
Low Entropy JWT Secret
+ MEDIUM +
+ +
+ πŸ“„ + .env + (Line 10) +
+ +
JWT secret appears to have low entropy (predictable patterns).
+ +
+ πŸ’‘ Recommendation: + Improve JWT secret security:
1. Generate a strong secret using crypto:
const crypto = require('crypto');
const secret = crypto.randomBytes(64).toString('hex');

2. Use environment-specific secrets
3. Implement secret rotation
4. Consider using asymmetric keys for larger systems +

+ +
+ Plugin: JWTConfigurationPlugin +
+
+ +
+
+
Direct JWT Usage Instead of AuthService
+ MEDIUM +
+ +
+ πŸ“„ + middleware.js + +
+ +
Direct jwt.verify() usage detected instead of centralized authService.
+ +
+ πŸ’‘ Recommendation: + Centralize JWT verification:
1. Create AuthService class
2. Move all JWT operations to AuthService
3. Use AuthService.verifyToken() in middleware
4. Add comprehensive error handling +
+ +
+ Plugin: JWTConfigurationPlugin +
+
+ +
+
+
Incomplete JWT Error Handling
+ LOW +
+ +
+ πŸ“„ + middleware.js + +
+ +
JWT verification lacks comprehensive error handling.
+ +
+ πŸ’‘ Recommendation: + Implement proper JWT error handling:
1. Handle TokenExpiredError
2. Handle JsonWebTokenError
3. Handle NotBeforeError
4. Add logging for security events
5. Return appropriate status codes +
+ +
+ Plugin: JWTConfigurationPlugin +
+
+ +
+ + +
+ + + \ No newline at end of file diff --git a/Vulnerability_Tool_V2/requirements.txt b/Vulnerability_Tool_V2/requirements.txt new file mode 100644 index 0000000..ed62c91 --- /dev/null +++ b/Vulnerability_Tool_V2/requirements.txt @@ -0,0 +1,21 @@ +# Core dependencies +PyYAML>=6.0 +Jinja2>=3.1.0 +colorama>=0.4.6 + +# Development dependencies +pytest>=7.0.0 +pytest-cov>=4.0.0 +black>=22.0.0 +flake8>=5.0.0 + +# Optional dependencies for advanced features +requests>=2.28.0 +gitpython>=3.1.0 + +# FastAPI and ASGI server +fastapi>=0.104.1 +uvicorn[standard]>=0.24.0 + +# File handling +python-multipart>=0.0.6 \ No newline at end of file diff --git a/Vulnerability_Tool_V2/scanner_v2.py b/Vulnerability_Tool_V2/scanner_v2.py new file mode 100644 index 0000000..abfb3d2 --- /dev/null +++ b/Vulnerability_Tool_V2/scanner_v2.py @@ -0,0 +1,239 @@ +#!/usr/bin/env python3 +""" +NutriHelp Security Scanner V2.0 - Main Entry Point +Modular security scanner main program +""" + +import os +import sys +import argparse +import json +import re +import logging +from pathlib import Path + +# Add the current directory to the Python path +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +from core.scanner_engine import SecurityScannerEngine +from core.config_manager import ConfigManager +from core.report_renderer import render_html_report + + +def setup_logging(verbose: bool = False): + """Set up logging system""" + level = logging.DEBUG if verbose else logging.INFO + logging.basicConfig( + level=level, + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', + handlers=[logging.StreamHandler()] + ) + + +def main(): + """Main function""" + parser = argparse.ArgumentParser( + description='NutriHelp Security Scanner V2.0 - Modular security scanner', + formatter_class=argparse.RawDescriptionHelpFormatter, + epilog=""" + Example usage: + %(prog)s --target ../ # Scan parent directory + %(prog)s --target ../ --format json # Output in JSON format + %(prog)s --target ../ --output report.html --format html + %(prog)s --config custom_config.yaml --target ../ + """ + ) + + parser.add_argument('--target', '-t', required=True, + help='Target directory path') + parser.add_argument('--config', '-c', + help='Configuration file path') + parser.add_argument('--format', '-f', default='summary', + choices=['json', 'html', 'summary'], + help='Output format (default: summary)') + parser.add_argument('--output', '-o', + help='Output file path (default: stdout)') + parser.add_argument('--verbose', '-v', action='store_true', + help='Show verbose logs') + parser.add_argument('--version', action='version', version='%(prog)s 2.0.0') + + args = parser.parse_args() + + # Set up logging + setup_logging(args.verbose) + logger = logging.getLogger("main") + + try: + logger.info("Starting NutriHelp Security Scanner V2.0") + + # 1. Load configuration + config_manager = ConfigManager(args.config) + if not config_manager.validate_config(): + logger.error("Configuration validation failed") + return 1 + + # 2. Initialize scanner engine + scanner_config = config_manager.get_scanner_config() + engine = SecurityScannerEngine(scanner_config) + + # 3. Load plugins + plugin_configs = config_manager.get_enabled_plugins() + # Ensure general_security is enabled by default unless explicitly disabled + if 'general_security' not in plugin_configs: + plugin_configs['general_security'] = { 'enabled': True } + engine.load_plugins(plugin_configs) + + if engine.stats['plugins_loaded'] == 0: + logger.warning("No plugins loaded! Scanner will not find any issues.") + + # 4. Execute scan + logger.info(f"Scanning target: {args.target}") + scan_results = engine.scan_target(args.target) + + # 5. Generate output + output_content = format_output(scan_results, args.format, config_manager) + + # 6. Write output + if args.output: + write_output_file(output_content, args.output, args.format) + logger.info(f"Results saved to: {args.output}") + else: + print(output_content) + + # 7. Set exit code + critical_count = scan_results['summary']['by_severity'].get('CRITICAL', 0) + if critical_count > 0: + logger.warning(f"Found {critical_count} critical security issues!") + return 1 + + logger.info("Scan completed successfully") + return 0 + + except FileNotFoundError as e: + logger.error(f"File not found: {e}") + return 1 + except Exception as e: + logger.error(f"Unexpected error: {e}") + if args.verbose: + import traceback + traceback.print_exc() + return 1 + + +def format_output(scan_results: dict, output_format: str, config_manager: ConfigManager) -> str: + """Format output results""" + if output_format == 'json': + return json.dumps(scan_results, indent=2, ensure_ascii=False) + + elif output_format == 'html': + # Use shared renderer for consistent output with API + return render_html_report(scan_results, config_manager) + + elif output_format == 'summary': + return generate_summary_report(scan_results) + + else: + raise ValueError(f"Unsupported output format: {output_format}") + + +def generate_summary_report(scan_results: dict) -> str: + """Generate summary report""" + summary = scan_results['summary'] + findings = scan_results['findings'] + scan_info = scan_results['scan_info'] + + lines = [] + lines.append("πŸ”’ NutriHelp Security Scanner V2.0 Results") + lines.append("=" * 50) + lines.append("") + + # Scan information + lines.append(f"πŸ“ Target: {scan_info['target_path']}") + lines.append(f"⏰ Scan Time: {scan_info['timestamp']}") + lines.append(f"πŸ“Š Files Scanned: {scan_info['stats']['files_scanned']}") + lines.append(f"πŸ”Œ Plugins Used: {scan_info['stats']['plugins_loaded']}") + lines.append("") + + # Summary statistics + lines.append("πŸ“Š Issues Found by Severity:") + severity_colors = { + 'CRITICAL': 'πŸ”΄', + 'HIGH': '🟠', + 'MEDIUM': '🟑', + 'LOW': '🟒' + } + + total_issues = summary['total'] + if total_issues == 0: + lines.append(" βœ… No security issues found!") + else: + for severity in ['CRITICAL', 'HIGH', 'MEDIUM', 'LOW']: + count = summary['by_severity'].get(severity, 0) + if count > 0: + color = severity_colors.get(severity, 'βšͺ') + lines.append(f" {color} {severity}: {count}") + + lines.append("") + lines.append(f"Total Issues: {total_issues}") + + # Plugin statistics + if summary['by_plugin']: + lines.append("") + lines.append("πŸ”Œ Issues by Plugin:") + for plugin_name, count in summary['by_plugin'].items(): + lines.append(f" β€’ {plugin_name}: {count}") + + # Critical issues details + critical_findings = [f for f in findings if f.get('severity') == 'CRITICAL'] + if critical_findings: + lines.append("") + lines.append("🚨 CRITICAL ISSUES (Need immediate attention):") + lines.append("-" * 40) + + for i, finding in enumerate(critical_findings[:5], 1): # Only show the first 5 + lines.append(f"{i}. {finding['title']}") + lines.append(f" πŸ“ File: {finding['file_path']}") + if finding.get('line_number'): + lines.append(f" πŸ“ Line: {finding['line_number']}") + lines.append(f" πŸ“ {finding['description']}") + lines.append("") + + if len(critical_findings) > 5: + lines.append(f" ... and {len(critical_findings) - 5} more critical issues") + + # High priority issues overview + high_findings = [f for f in findings if f.get('severity') == 'HIGH'] + if high_findings and len(high_findings) <= 3: # Only show when high priority issues are few + lines.append("") + lines.append("πŸ”Ά HIGH PRIORITY ISSUES:") + lines.append("-" * 30) + + for finding in high_findings: + lines.append(f"β€’ {finding['title']} ({finding['file_path']})") + + lines.append("") + lines.append("πŸ’‘ Use --format html for detailed visual report") + lines.append("πŸ’‘ Use --format json for machine-readable output") + + return '\n'.join(lines) + + + # CLI previously had a large in-file renderer; replaced by shared renderer + + +def write_output_file(content: str, file_path: str, output_format: str): + """Write output file""" + # Ensure output directory exists + output_dir = os.path.dirname(file_path) + if output_dir and not os.path.exists(output_dir): + os.makedirs(output_dir) + + # Determine encoding + encoding = 'utf-8' + + with open(file_path, 'w', encoding=encoding) as f: + f.write(content) + + +if __name__ == '__main__': + sys.exit(main()) \ No newline at end of file diff --git a/Vulnerability_Tool_V2/security_report.html b/Vulnerability_Tool_V2/security_report.html new file mode 100644 index 0000000..51c2278 --- /dev/null +++ b/Vulnerability_Tool_V2/security_report.html @@ -0,0 +1,2400 @@ + + + + + + + NutriHelp Security Scanner V2.0 Report + + + +
+
+

πŸ”’ NutriHelp Security Scanner V2.0

+
+
Scan time: 2025-09-07 12:12:14
+
Target path: ../
+
Scanner version: 2.0.0
+
+
+ +
+
+
0
+
Critical Issues
+
+
+
0
+
High Severity
+
+
+
69
+
Medium Severity
+
+
+
1
+
Low Severity
+
+
+ +
+
+
+
190
+
Files Scanned
+
+
+
2
+
Plugins Used
+
+
+
70
+
Total Issues
+
+
+ +

πŸ” Detailed Findings

+
+
+
Missing JWT Protection: GET /
+ MEDIUM +
+ +
+ πŸ“„ + jwt server.js + (Line 11) +
+ +
API endpoint GET / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /scanner/plugins
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/api/scanner_api.py + (Line 148) +
+ +
API endpoint GET /scanner/plugins lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /scanner/plugins endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/scanner/plugins', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/scanner/plugins', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /scanner/scan
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/api/scanner_api.py + (Line 167) +
+ +
API endpoint POST /scanner/scan lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST /scanner/scan endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/scanner/scan', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/scanner/scan', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /scanner/scan/{scan_id}/status
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/api/scanner_api.py + (Line 198) +
+ +
API endpoint GET /scanner/scan/{scan_id}/status lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /scanner/scan/{scan_id}/status endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/scanner/scan/{scan_id}/status', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/scanner/scan/{scan_id}/status', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /scanner/scan/{scan_id}/result
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/api/scanner_api.py + (Line 213) +
+ +
API endpoint GET /scanner/scan/{scan_id}/result lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /scanner/scan/{scan_id}/result endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/scanner/scan/{scan_id}/result', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/scanner/scan/{scan_id}/result', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /scanner/scan/{scan_id}/report
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/api/scanner_api.py + (Line 230) +
+ +
API endpoint GET /scanner/scan/{scan_id}/report lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /scanner/scan/{scan_id}/report endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/scanner/scan/{scan_id}/report', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/scanner/scan/{scan_id}/report', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /scanner/scan/quick
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/api/scanner_api.py + (Line 353) +
+ +
API endpoint POST /scanner/scan/quick lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST /scanner/scan/quick endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/scanner/scan/quick', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/scanner/scan/quick', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /users/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/applications.py + (Line 235) +
+ +
API endpoint GET /users/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /users/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/users/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/users/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /items/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/applications.py + (Line 236) +
+ +
API endpoint GET /items/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /items/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/items/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/items/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /items/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/applications.py + (Line 388) +
+ +
API endpoint GET /items/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /items/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/items/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/items/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /items/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/applications.py + (Line 1802) +
+ +
API endpoint GET /items/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /items/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/items/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/items/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: PUT /items/{item_id}
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/applications.py + (Line 2180) +
+ +
API endpoint PUT /items/{item_id} lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the PUT /items/{item_id} endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.put('/items/{item_id}', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.put('/items/{item_id}', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /items/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/applications.py + (Line 2558) +
+ +
API endpoint POST /items/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST /items/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/items/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/items/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: DELETE /items/{item_id}
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/applications.py + (Line 2931) +
+ +
API endpoint DELETE /items/{item_id} lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the DELETE /items/{item_id} endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.delete('/items/{item_id}', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.delete('/items/{item_id}', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: PATCH /items/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/applications.py + (Line 4055) +
+ +
API endpoint PATCH /items/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the PATCH /items/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.patch('/items/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.patch('/items/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /send-notification/{email}
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/background.py + (Line 31) +
+ +
API endpoint POST /send-notification/{email} lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST /send-notification/{email} endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/send-notification/{email}', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/send-notification/{email}', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /users/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/routing.py + (Line 614) +
+ +
API endpoint GET /users/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /users/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/users/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/users/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /users/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/routing.py + (Line 1250) +
+ +
API endpoint GET /users/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /users/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/users/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/users/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /items/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/routing.py + (Line 1710) +
+ +
API endpoint GET /items/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /items/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/items/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/items/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: PUT /items/{item_id}
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/routing.py + (Line 2092) +
+ +
API endpoint PUT /items/{item_id} lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the PUT /items/{item_id} endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.put('/items/{item_id}', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.put('/items/{item_id}', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /items/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/routing.py + (Line 2474) +
+ +
API endpoint POST /items/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST /items/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/items/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/items/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: DELETE /items/{item_id}
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/routing.py + (Line 2851) +
+ +
API endpoint DELETE /items/{item_id} lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the DELETE /items/{item_id} endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.delete('/items/{item_id}', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.delete('/items/{item_id}', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: PATCH /items/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/routing.py + (Line 3992) +
+ +
API endpoint PATCH /items/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the PATCH /items/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.patch('/items/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.patch('/items/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /items/{item_id}
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/exceptions.py + (Line 29) +
+ +
API endpoint GET /items/{item_id} lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /items/{item_id} endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/items/{item_id}', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/items/{item_id}', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /items/{item_id}
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/param_functions.py + (Line 299) +
+ +
API endpoint GET /items/{item_id} lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /items/{item_id} endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/items/{item_id}', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/items/{item_id}', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /items/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/param_functions.py + (Line 2272) +
+ +
API endpoint GET /items/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /items/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/items/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/items/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /users/me/items/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/param_functions.py + (Line 2353) +
+ +
API endpoint GET /users/me/items/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /users/me/items/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/users/me/items/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/users/me/items/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /files/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/datastructures.py + (Line 53) +
+ +
API endpoint POST /files/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST /files/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/files/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/files/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /uploadfile/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/datastructures.py + (Line 58) +
+ +
API endpoint POST /uploadfile/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST /uploadfile/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/uploadfile/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/uploadfile/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /items/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/security/api_key.py + (Line 49) +
+ +
API endpoint GET /items/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /items/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/items/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/items/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /items/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/security/api_key.py + (Line 141) +
+ +
API endpoint GET /items/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /items/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/items/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/items/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /items/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/security/api_key.py + (Line 229) +
+ +
API endpoint GET /items/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /items/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/items/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/items/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /users/me
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/security/http.py + (Line 124) +
+ +
API endpoint GET /users/me lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /users/me endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/users/me', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/users/me', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /users/me
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/security/http.py + (Line 244) +
+ +
API endpoint GET /users/me lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /users/me endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/users/me', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/users/me', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /users/me
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/security/http.py + (Line 348) +
+ +
API endpoint GET /users/me lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /users/me endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/users/me', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/users/me', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /
+ MEDIUM +
+ +
+ πŸ“„ + routes/imageClassification.js + (Line 19) +
+ +
API endpoint POST / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /test
+ MEDIUM +
+ +
+ πŸ“„ + routes/scanner.js + (Line 35) +
+ +
API endpoint GET /test lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /test endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/test', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/test', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /plugins
+ MEDIUM +
+ +
+ πŸ“„ + routes/scanner.js + (Line 177) +
+ +
API endpoint GET /plugins lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /plugins endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/plugins', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/plugins', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /scan
+ MEDIUM +
+ +
+ πŸ“„ + routes/scanner.js + (Line 234) +
+ +
API endpoint POST /scan lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST /scan endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/scan', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/scan', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /scan/:scanId/status
+ MEDIUM +
+ +
+ πŸ“„ + routes/scanner.js + (Line 306) +
+ +
API endpoint GET /scan/:scanId/status lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /scan/:scanId/status endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/scan/:scanId/status', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/scan/:scanId/status', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /scan/:scanId/result
+ MEDIUM +
+ +
+ πŸ“„ + routes/scanner.js + (Line 386) +
+ +
API endpoint GET /scan/:scanId/result lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /scan/:scanId/result endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/scan/:scanId/result', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/scan/:scanId/result', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /scan/:scanId/report
+ MEDIUM +
+ +
+ πŸ“„ + routes/scanner.js + (Line 464) +
+ +
API endpoint GET /scan/:scanId/report lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /scan/:scanId/report endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/scan/:scanId/report', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/scan/:scanId/report', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /scan/:scanId/raw
+ MEDIUM +
+ +
+ πŸ“„ + routes/scanner.js + (Line 587) +
+ +
API endpoint GET /scan/:scanId/raw lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /scan/:scanId/raw endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/scan/:scanId/raw', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/scan/:scanId/raw', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /quick-scan
+ MEDIUM +
+ +
+ πŸ“„ + routes/scanner.js + (Line 621) +
+ +
API endpoint POST /quick-scan lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST /quick-scan endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/quick-scan', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/quick-scan', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: PUT /update-by-identifier
+ MEDIUM +
+ +
+ πŸ“„ + routes/userprofile.js + (Line 14) +
+ +
API endpoint PUT /update-by-identifier lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the PUT /update-by-identifier endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.put('/update-by-identifier', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.put('/update-by-identifier', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /
+ MEDIUM +
+ +
+ πŸ“„ + routes/upload.js + (Line 5) +
+ +
API endpoint POST / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /
+ MEDIUM +
+ +
+ πŸ“„ + routes/waterIntake.js + (Line 5) +
+ +
API endpoint POST / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /
+ MEDIUM +
+ +
+ πŸ“„ + routes/signup.js + (Line 11) +
+ +
API endpoint POST / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /
+ MEDIUM +
+ +
+ πŸ“„ + routes/login.js + (Line 11) +
+ +
API endpoint POST / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /mfa
+ MEDIUM +
+ +
+ πŸ“„ + routes/login.js + (Line 16) +
+ +
API endpoint POST /mfa lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST /mfa endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/mfa', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/mfa', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /createRecipe
+ MEDIUM +
+ +
+ πŸ“„ + routes/recipe.js + (Line 8) +
+ +
API endpoint POST /createRecipe lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST /createRecipe endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/createRecipe', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/createRecipe', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /
+ MEDIUM +
+ +
+ πŸ“„ + routes/recipe.js + (Line 10) +
+ +
API endpoint POST / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: DELETE /
+ MEDIUM +
+ +
+ πŸ“„ + routes/recipe.js + (Line 11) +
+ +
API endpoint DELETE / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the DELETE / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.delete('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.delete('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /
+ MEDIUM +
+ +
+ πŸ“„ + routes/recipeNutritionlog.js + (Line 27) +
+ +
API endpoint GET / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /classify
+ MEDIUM +
+ +
+ πŸ“„ + routes/routes.js + (Line 32) +
+ +
API endpoint POST /classify lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST /classify endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/classify', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/classify', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /
+ MEDIUM +
+ +
+ πŸ“„ + routes/userfeedback.js + (Line 8) +
+ +
API endpoint POST / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /
+ MEDIUM +
+ +
+ πŸ“„ + routes/healthNews.js + (Line 44) +
+ +
API endpoint GET / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /
+ MEDIUM +
+ +
+ πŸ“„ + routes/healthNews.js + (Line 156) +
+ +
API endpoint POST / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: PUT /
+ MEDIUM +
+ +
+ πŸ“„ + routes/healthNews.js + (Line 214) +
+ +
API endpoint PUT / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the PUT / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.put('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.put('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: DELETE /
+ MEDIUM +
+ +
+ πŸ“„ + routes/healthNews.js + (Line 238) +
+ +
API endpoint DELETE / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the DELETE / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.delete('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.delete('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /generate-baseline
+ MEDIUM +
+ +
+ πŸ“„ + routes/systemRoutes.js + (Line 50) +
+ +
API endpoint POST /generate-baseline lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST /generate-baseline endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/generate-baseline', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/generate-baseline', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /integrity-check
+ MEDIUM +
+ +
+ πŸ“„ + routes/systemRoutes.js + (Line 59) +
+ +
API endpoint GET /integrity-check lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /integrity-check endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/integrity-check', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/integrity-check', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /
+ MEDIUM +
+ +
+ πŸ“„ + routes/filter.js + (Line 7) +
+ +
API endpoint GET / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /
+ MEDIUM +
+ +
+ πŸ“„ + routes/articles.js + (Line 5) +
+ +
API endpoint GET / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /:user_id
+ MEDIUM +
+ +
+ πŸ“„ + routes/notifications.js + (Line 21) +
+ +
API endpoint GET /:user_id lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /:user_id endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/:user_id', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/:user_id', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /
+ MEDIUM +
+ +
+ πŸ“„ + routes/contactus.js + (Line 14) +
+ +
API endpoint POST / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Low Entropy JWT Secret
+ MEDIUM +
+ +
+ πŸ“„ + .env + (Line 8) +
+ +
JWT secret appears to have low entropy (predictable patterns).
+ +
+ πŸ’‘ Recommendation: + Improve JWT secret security:
1. Generate a strong secret using crypto:
const crypto = require('crypto');
const secret = crypto.randomBytes(64).toString('hex');

2. Use environment-specific secrets
3. Implement secret rotation
4. Consider using asymmetric keys for larger systems +

+ +
+ Plugin: JWTConfigurationPlugin +
+
+ +
+
+
Low Entropy JWT Secret
+ MEDIUM +
+ +
+ πŸ“„ + .env + (Line 10) +
+ +
JWT secret appears to have low entropy (predictable patterns).
+ +
+ πŸ’‘ Recommendation: + Improve JWT secret security:
1. Generate a strong secret using crypto:
const crypto = require('crypto');
const secret = crypto.randomBytes(64).toString('hex');

2. Use environment-specific secrets
3. Implement secret rotation
4. Consider using asymmetric keys for larger systems +

+ +
+ Plugin: JWTConfigurationPlugin +
+
+ +
+
+
Direct JWT Usage Instead of AuthService
+ MEDIUM +
+ +
+ πŸ“„ + middleware.js + +
+ +
Direct jwt.verify() usage detected instead of centralized authService.
+ +
+ πŸ’‘ Recommendation: + Centralize JWT verification:
1. Create AuthService class
2. Move all JWT operations to AuthService
3. Use AuthService.verifyToken() in middleware
4. Add comprehensive error handling +
+ +
+ Plugin: JWTConfigurationPlugin +
+
+ +
+
+
Incomplete JWT Error Handling
+ LOW +
+ +
+ πŸ“„ + middleware.js + +
+ +
JWT verification lacks comprehensive error handling.
+ +
+ πŸ’‘ Recommendation: + Implement proper JWT error handling:
1. Handle TokenExpiredError
2. Handle JsonWebTokenError
3. Handle NotBeforeError
4. Add logging for security events
5. Return appropriate status codes +
+ +
+ Plugin: JWTConfigurationPlugin +
+
+ +
+ + +
+ + + \ No newline at end of file diff --git a/Vulnerability_Tool_V2/security_report_general.html b/Vulnerability_Tool_V2/security_report_general.html new file mode 100644 index 0000000..4960ed1 --- /dev/null +++ b/Vulnerability_Tool_V2/security_report_general.html @@ -0,0 +1,2761 @@ + + + + + + + NutriHelp Security Scanner V2.0 Report + + + +
+
+

πŸ”’ NutriHelp Security Scanner V2.0

+
+
Scan time: 2025-09-07 12:38:00
+
Target path: ../
+
Scanner version: 2.0.0
+
+
+ +
+
+
9
+
Critical Issues
+
+
+
3
+
High Severity
+
+
+
70
+
Medium Severity
+
+
+
1
+
Low Severity
+
+
+ +
+
+
+
192
+
Files Scanned
+
+
+
3
+
Plugins Used
+
+
+
83
+
Total Issues
+
+
+ +

πŸ” Detailed Findings

+
+
+
Hardcoded secret: password
+ CRITICAL +
+ +
+ πŸ“„ + ../test/logintest.js + (Line 43) +
+ +
Found likely hardcoded secret key "password" in file. Value length: 20
+ +
+ πŸ’‘ Recommendation: +

Remove hardcoded secrets and use environment variables or a secrets manager.

+
    +
  1. Move the secret into an environment variable or encrypted store.
  2. +
  3. Rotate the exposed secret immediately if used in production.
  4. +
  5. Ensure secrets are not committed to VCS.
  6. +
+
+ +
+ Plugin: general_security +
+
+ +
+
+
Hardcoded secret: password
+ CRITICAL +
+ +
+ πŸ“„ + ../test/logintest.js + (Line 62) +
+ +
Found likely hardcoded secret key "password" in file. Value length: 15
+ +
+ πŸ’‘ Recommendation: +

Remove hardcoded secrets and use environment variables or a secrets manager.

+
    +
  1. Move the secret into an environment variable or encrypted store.
  2. +
  3. Rotate the exposed secret immediately if used in production.
  4. +
  5. Ensure secrets are not committed to VCS.
  6. +
+
+ +
+ Plugin: general_security +
+
+ +
+
+
Hardcoded secret: password
+ CRITICAL +
+ +
+ πŸ“„ + ../test/logintest.js + (Line 81) +
+ +
Found likely hardcoded secret key "password" in file. Value length: 11
+ +
+ πŸ’‘ Recommendation: +

Remove hardcoded secrets and use environment variables or a secrets manager.

+
    +
  1. Move the secret into an environment variable or encrypted store.
  2. +
  3. Rotate the exposed secret immediately if used in production.
  4. +
  5. Ensure secrets are not committed to VCS.
  6. +
+
+ +
+ Plugin: general_security +
+
+ +
+
+
Hardcoded secret: password
+ CRITICAL +
+ +
+ πŸ“„ + ../test/logintest.js + (Line 97) +
+ +
Found likely hardcoded secret key "password" in file. Value length: 11
+ +
+ πŸ’‘ Recommendation: +

Remove hardcoded secrets and use environment variables or a secrets manager.

+
    +
  1. Move the secret into an environment variable or encrypted store.
  2. +
  3. Rotate the exposed secret immediately if used in production.
  4. +
  5. Ensure secrets are not committed to VCS.
  6. +
+
+ +
+ Plugin: general_security +
+
+ +
+
+
Hardcoded secret: password
+ CRITICAL +
+ +
+ πŸ“„ + ../test/userPreferencesTests.js + (Line 32) +
+ +
Found likely hardcoded secret key "password" in file. Value length: 11
+ +
+ πŸ’‘ Recommendation: +

Remove hardcoded secrets and use environment variables or a secrets manager.

+
    +
  1. Move the secret into an environment variable or encrypted store.
  2. +
  3. Rotate the exposed secret immediately if used in production.
  4. +
  5. Ensure secrets are not committed to VCS.
  6. +
+
+ +
+ Plugin: general_security +
+
+ +
+
+
Hardcoded secret: password
+ CRITICAL +
+ +
+ πŸ“„ + ../test/signuptest.js + (Line 63) +
+ +
Found likely hardcoded secret key "password" in file. Value length: 18
+ +
+ πŸ’‘ Recommendation: +

Remove hardcoded secrets and use environment variables or a secrets manager.

+
    +
  1. Move the secret into an environment variable or encrypted store.
  2. +
  3. Rotate the exposed secret immediately if used in production.
  4. +
  5. Ensure secrets are not committed to VCS.
  6. +
+
+ +
+ Plugin: general_security +
+
+ +
+
+
Hardcoded secret: jwt
+ CRITICAL +
+ +
+ πŸ“„ + ../Vulnerability_Tool_V2/plugins/jwt_security/jwt_config.py + (Line 235) +
+ +
Found likely hardcoded secret key "jwt" in file. Value length: 10
+ +
+ πŸ’‘ Recommendation: +

Remove hardcoded secrets and use environment variables or a secrets manager.

+
    +
  1. Move the secret into an environment variable or encrypted store.
  2. +
  3. Rotate the exposed secret immediately if used in production.
  4. +
  5. Ensure secrets are not committed to VCS.
  6. +
+
+ +
+ Plugin: general_security +
+
+ +
+
+
Hardcoded secret: JWT_SECRET
+ CRITICAL +
+ +
+ πŸ“„ + ../Vulnerability_Tool_V2/tests/test_general_security_plugin.py + (Line 19) +
+ +
Found likely hardcoded secret key "JWT_SECRET" in file. Value length: 14
+ +
+ πŸ’‘ Recommendation: +

Remove hardcoded secrets and use environment variables or a secrets manager.

+
    +
  1. Move the secret into an environment variable or encrypted store.
  2. +
  3. Rotate the exposed secret immediately if used in production.
  4. +
  5. Ensure secrets are not committed to VCS.
  6. +
+
+ +
+ Plugin: general_security +
+
+ +
+
+
Hardcoded secret: Token
+ CRITICAL +
+ +
+ πŸ“„ + ../scripts/testAuthAPI.js + (Line 225) +
+ +
Found likely hardcoded secret key "Token" in file. Value length: 25
+ +
+ πŸ’‘ Recommendation: +

Remove hardcoded secrets and use environment variables or a secrets manager.

+
    +
  1. Move the secret into an environment variable or encrypted store.
  2. +
  3. Rotate the exposed secret immediately if used in production.
  4. +
  5. Ensure secrets are not committed to VCS.
  6. +
+
+ +
+ Plugin: general_security +
+
+ +
+
+
Hardcoded DB connection string
+ HIGH +
+ +
+ πŸ“„ + ../Vulnerability_Tool_V2/plugins/general_security/__init__.py + (Line 80) +
+ +
Found a database connection string in code or config which may contain credentials.
+ +
+ πŸ’‘ Recommendation: + Move DB credentials to environment variables and avoid committing connection strings. +
+ +
+ Plugin: general_security +
+
+ +
+
+
Hardcoded DB connection string
+ HIGH +
+ +
+ πŸ“„ + ../Vulnerability_Tool_V2/plugins/general_security/__init__.py + (Line 80) +
+ +
Found a database connection string in code or config which may contain credentials.
+ +
+ πŸ’‘ Recommendation: + Move DB credentials to environment variables and avoid committing connection strings. +
+ +
+ Plugin: general_security +
+
+ +
+
+
Hardcoded DB connection string
+ HIGH +
+ +
+ πŸ“„ + ../Vulnerability_Tool_V2/tests/test_general_security_plugin.py + (Line 28) +
+ +
Found a database connection string in code or config which may contain credentials.
+ +
+ πŸ’‘ Recommendation: + Move DB credentials to environment variables and avoid committing connection strings. +
+ +
+ Plugin: general_security +
+
+ +
+
+
Missing JWT Protection: GET /
+ MEDIUM +
+ +
+ πŸ“„ + jwt server.js + (Line 11) +
+ +
API endpoint GET / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /scanner/plugins
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/api/scanner_api.py + (Line 148) +
+ +
API endpoint GET /scanner/plugins lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /scanner/plugins endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/scanner/plugins', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/scanner/plugins', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /scanner/scan
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/api/scanner_api.py + (Line 167) +
+ +
API endpoint POST /scanner/scan lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST /scanner/scan endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/scanner/scan', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/scanner/scan', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /scanner/scan/{scan_id}/status
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/api/scanner_api.py + (Line 198) +
+ +
API endpoint GET /scanner/scan/{scan_id}/status lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /scanner/scan/{scan_id}/status endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/scanner/scan/{scan_id}/status', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/scanner/scan/{scan_id}/status', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /scanner/scan/{scan_id}/result
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/api/scanner_api.py + (Line 213) +
+ +
API endpoint GET /scanner/scan/{scan_id}/result lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /scanner/scan/{scan_id}/result endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/scanner/scan/{scan_id}/result', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/scanner/scan/{scan_id}/result', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /scanner/scan/{scan_id}/report
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/api/scanner_api.py + (Line 230) +
+ +
API endpoint GET /scanner/scan/{scan_id}/report lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /scanner/scan/{scan_id}/report endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/scanner/scan/{scan_id}/report', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/scanner/scan/{scan_id}/report', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /scanner/scan/quick
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/api/scanner_api.py + (Line 353) +
+ +
API endpoint POST /scanner/scan/quick lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST /scanner/scan/quick endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/scanner/scan/quick', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/scanner/scan/quick', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /users/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/applications.py + (Line 235) +
+ +
API endpoint GET /users/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /users/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/users/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/users/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /items/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/applications.py + (Line 236) +
+ +
API endpoint GET /items/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /items/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/items/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/items/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /items/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/applications.py + (Line 388) +
+ +
API endpoint GET /items/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /items/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/items/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/items/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /items/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/applications.py + (Line 1802) +
+ +
API endpoint GET /items/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /items/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/items/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/items/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: PUT /items/{item_id}
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/applications.py + (Line 2180) +
+ +
API endpoint PUT /items/{item_id} lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the PUT /items/{item_id} endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.put('/items/{item_id}', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.put('/items/{item_id}', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /items/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/applications.py + (Line 2558) +
+ +
API endpoint POST /items/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST /items/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/items/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/items/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: DELETE /items/{item_id}
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/applications.py + (Line 2931) +
+ +
API endpoint DELETE /items/{item_id} lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the DELETE /items/{item_id} endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.delete('/items/{item_id}', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.delete('/items/{item_id}', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: PATCH /items/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/applications.py + (Line 4055) +
+ +
API endpoint PATCH /items/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the PATCH /items/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.patch('/items/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.patch('/items/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /send-notification/{email}
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/background.py + (Line 31) +
+ +
API endpoint POST /send-notification/{email} lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST /send-notification/{email} endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/send-notification/{email}', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/send-notification/{email}', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /users/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/routing.py + (Line 614) +
+ +
API endpoint GET /users/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /users/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/users/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/users/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /users/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/routing.py + (Line 1250) +
+ +
API endpoint GET /users/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /users/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/users/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/users/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /items/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/routing.py + (Line 1710) +
+ +
API endpoint GET /items/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /items/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/items/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/items/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: PUT /items/{item_id}
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/routing.py + (Line 2092) +
+ +
API endpoint PUT /items/{item_id} lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the PUT /items/{item_id} endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.put('/items/{item_id}', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.put('/items/{item_id}', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /items/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/routing.py + (Line 2474) +
+ +
API endpoint POST /items/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST /items/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/items/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/items/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: DELETE /items/{item_id}
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/routing.py + (Line 2851) +
+ +
API endpoint DELETE /items/{item_id} lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the DELETE /items/{item_id} endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.delete('/items/{item_id}', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.delete('/items/{item_id}', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: PATCH /items/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/routing.py + (Line 3992) +
+ +
API endpoint PATCH /items/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the PATCH /items/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.patch('/items/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.patch('/items/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /items/{item_id}
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/exceptions.py + (Line 29) +
+ +
API endpoint GET /items/{item_id} lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /items/{item_id} endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/items/{item_id}', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/items/{item_id}', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /items/{item_id}
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/param_functions.py + (Line 299) +
+ +
API endpoint GET /items/{item_id} lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /items/{item_id} endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/items/{item_id}', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/items/{item_id}', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /items/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/param_functions.py + (Line 2272) +
+ +
API endpoint GET /items/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /items/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/items/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/items/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /users/me/items/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/param_functions.py + (Line 2353) +
+ +
API endpoint GET /users/me/items/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /users/me/items/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/users/me/items/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/users/me/items/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /files/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/datastructures.py + (Line 53) +
+ +
API endpoint POST /files/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST /files/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/files/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/files/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /uploadfile/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/datastructures.py + (Line 58) +
+ +
API endpoint POST /uploadfile/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST /uploadfile/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/uploadfile/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/uploadfile/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /items/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/security/api_key.py + (Line 49) +
+ +
API endpoint GET /items/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /items/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/items/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/items/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /items/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/security/api_key.py + (Line 141) +
+ +
API endpoint GET /items/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /items/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/items/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/items/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /items/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/security/api_key.py + (Line 229) +
+ +
API endpoint GET /items/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /items/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/items/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/items/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /users/me
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/security/http.py + (Line 124) +
+ +
API endpoint GET /users/me lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /users/me endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/users/me', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/users/me', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /users/me
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/security/http.py + (Line 244) +
+ +
API endpoint GET /users/me lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /users/me endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/users/me', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/users/me', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /users/me
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/security/http.py + (Line 348) +
+ +
API endpoint GET /users/me lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /users/me endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/users/me', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/users/me', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /
+ MEDIUM +
+ +
+ πŸ“„ + routes/imageClassification.js + (Line 19) +
+ +
API endpoint POST / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /test
+ MEDIUM +
+ +
+ πŸ“„ + routes/scanner.js + (Line 35) +
+ +
API endpoint GET /test lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /test endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/test', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/test', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /plugins
+ MEDIUM +
+ +
+ πŸ“„ + routes/scanner.js + (Line 177) +
+ +
API endpoint GET /plugins lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /plugins endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/plugins', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/plugins', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /scan
+ MEDIUM +
+ +
+ πŸ“„ + routes/scanner.js + (Line 234) +
+ +
API endpoint POST /scan lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST /scan endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/scan', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/scan', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /scan/:scanId/status
+ MEDIUM +
+ +
+ πŸ“„ + routes/scanner.js + (Line 306) +
+ +
API endpoint GET /scan/:scanId/status lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /scan/:scanId/status endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/scan/:scanId/status', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/scan/:scanId/status', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /scan/:scanId/result
+ MEDIUM +
+ +
+ πŸ“„ + routes/scanner.js + (Line 386) +
+ +
API endpoint GET /scan/:scanId/result lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /scan/:scanId/result endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/scan/:scanId/result', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/scan/:scanId/result', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /scan/:scanId/report
+ MEDIUM +
+ +
+ πŸ“„ + routes/scanner.js + (Line 464) +
+ +
API endpoint GET /scan/:scanId/report lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /scan/:scanId/report endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/scan/:scanId/report', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/scan/:scanId/report', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /scan/:scanId/raw
+ MEDIUM +
+ +
+ πŸ“„ + routes/scanner.js + (Line 587) +
+ +
API endpoint GET /scan/:scanId/raw lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /scan/:scanId/raw endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/scan/:scanId/raw', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/scan/:scanId/raw', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /quick-scan
+ MEDIUM +
+ +
+ πŸ“„ + routes/scanner.js + (Line 621) +
+ +
API endpoint POST /quick-scan lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST /quick-scan endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/quick-scan', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/quick-scan', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: PUT /update-by-identifier
+ MEDIUM +
+ +
+ πŸ“„ + routes/userprofile.js + (Line 14) +
+ +
API endpoint PUT /update-by-identifier lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the PUT /update-by-identifier endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.put('/update-by-identifier', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.put('/update-by-identifier', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /
+ MEDIUM +
+ +
+ πŸ“„ + routes/upload.js + (Line 5) +
+ +
API endpoint POST / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /
+ MEDIUM +
+ +
+ πŸ“„ + routes/waterIntake.js + (Line 5) +
+ +
API endpoint POST / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /
+ MEDIUM +
+ +
+ πŸ“„ + routes/signup.js + (Line 11) +
+ +
API endpoint POST / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /
+ MEDIUM +
+ +
+ πŸ“„ + routes/login.js + (Line 11) +
+ +
API endpoint POST / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /mfa
+ MEDIUM +
+ +
+ πŸ“„ + routes/login.js + (Line 16) +
+ +
API endpoint POST /mfa lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST /mfa endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/mfa', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/mfa', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /createRecipe
+ MEDIUM +
+ +
+ πŸ“„ + routes/recipe.js + (Line 8) +
+ +
API endpoint POST /createRecipe lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST /createRecipe endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/createRecipe', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/createRecipe', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /
+ MEDIUM +
+ +
+ πŸ“„ + routes/recipe.js + (Line 10) +
+ +
API endpoint POST / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: DELETE /
+ MEDIUM +
+ +
+ πŸ“„ + routes/recipe.js + (Line 11) +
+ +
API endpoint DELETE / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the DELETE / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.delete('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.delete('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /
+ MEDIUM +
+ +
+ πŸ“„ + routes/recipeNutritionlog.js + (Line 27) +
+ +
API endpoint GET / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /classify
+ MEDIUM +
+ +
+ πŸ“„ + routes/routes.js + (Line 32) +
+ +
API endpoint POST /classify lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST /classify endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/classify', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/classify', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /
+ MEDIUM +
+ +
+ πŸ“„ + routes/userfeedback.js + (Line 8) +
+ +
API endpoint POST / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /
+ MEDIUM +
+ +
+ πŸ“„ + routes/healthNews.js + (Line 44) +
+ +
API endpoint GET / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /
+ MEDIUM +
+ +
+ πŸ“„ + routes/healthNews.js + (Line 156) +
+ +
API endpoint POST / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: PUT /
+ MEDIUM +
+ +
+ πŸ“„ + routes/healthNews.js + (Line 214) +
+ +
API endpoint PUT / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the PUT / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.put('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.put('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: DELETE /
+ MEDIUM +
+ +
+ πŸ“„ + routes/healthNews.js + (Line 238) +
+ +
API endpoint DELETE / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the DELETE / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.delete('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.delete('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /generate-baseline
+ MEDIUM +
+ +
+ πŸ“„ + routes/systemRoutes.js + (Line 50) +
+ +
API endpoint POST /generate-baseline lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST /generate-baseline endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/generate-baseline', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/generate-baseline', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /integrity-check
+ MEDIUM +
+ +
+ πŸ“„ + routes/systemRoutes.js + (Line 59) +
+ +
API endpoint GET /integrity-check lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /integrity-check endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/integrity-check', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/integrity-check', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /
+ MEDIUM +
+ +
+ πŸ“„ + routes/filter.js + (Line 7) +
+ +
API endpoint GET / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /
+ MEDIUM +
+ +
+ πŸ“„ + routes/articles.js + (Line 5) +
+ +
API endpoint GET / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /:user_id
+ MEDIUM +
+ +
+ πŸ“„ + routes/notifications.js + (Line 21) +
+ +
API endpoint GET /:user_id lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /:user_id endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/:user_id', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/:user_id', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /
+ MEDIUM +
+ +
+ πŸ“„ + routes/contactus.js + (Line 14) +
+ +
API endpoint POST / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Low Entropy JWT Secret
+ MEDIUM +
+ +
+ πŸ“„ + .env + (Line 8) +
+ +
JWT secret appears to have low entropy (predictable patterns).
+ +
+ πŸ’‘ Recommendation: + Improve JWT secret security:
1. Generate a strong secret using crypto:
const crypto = require('crypto');
const secret = crypto.randomBytes(64).toString('hex');

2. Use environment-specific secrets
3. Implement secret rotation
4. Consider using asymmetric keys for larger systems +

+ +
+ Plugin: JWTConfigurationPlugin +
+
+ +
+
+
Low Entropy JWT Secret
+ MEDIUM +
+ +
+ πŸ“„ + .env + (Line 10) +
+ +
JWT secret appears to have low entropy (predictable patterns).
+ +
+ πŸ’‘ Recommendation: + Improve JWT secret security:
1. Generate a strong secret using crypto:
const crypto = require('crypto');
const secret = crypto.randomBytes(64).toString('hex');

2. Use environment-specific secrets
3. Implement secret rotation
4. Consider using asymmetric keys for larger systems +

+ +
+ Plugin: JWTConfigurationPlugin +
+
+ +
+
+
Direct JWT Usage Instead of AuthService
+ MEDIUM +
+ +
+ πŸ“„ + middleware.js + +
+ +
Direct jwt.verify() usage detected instead of centralized authService.
+ +
+ πŸ’‘ Recommendation: + Centralize JWT verification:
1. Create AuthService class
2. Move all JWT operations to AuthService
3. Use AuthService.verifyToken() in middleware
4. Add comprehensive error handling +
+ +
+ Plugin: JWTConfigurationPlugin +
+
+ +
+
+
Permissive CORS configuration
+ MEDIUM +
+ +
+ πŸ“„ + ../Vulnerability_Tool_V2/plugins/general_security/__init__.py + +
+ +
Detected wildcard CORS origin which allows any origin to access resources.
+ +
+ πŸ’‘ Recommendation: +

Restrict CORS origins to a specific allowlist.

+
    +
  1. Replace wildcard origin with an explicit list of allowed origins.
  2. +
  3. If dynamic, validate and sanitize the Origin header before echoing it back.
  4. +
+
+ +
+ Plugin: general_security +
+
+ +
+
+
Incomplete JWT Error Handling
+ LOW +
+ +
+ πŸ“„ + middleware.js + +
+ +
JWT verification lacks comprehensive error handling.
+ +
+ πŸ’‘ Recommendation: + Implement proper JWT error handling:
1. Handle TokenExpiredError
2. Handle JsonWebTokenError
3. Handle NotBeforeError
4. Add logging for security events
5. Return appropriate status codes +
+ +
+ Plugin: JWTConfigurationPlugin +
+
+ +
+ + +
+ + + \ No newline at end of file diff --git a/Vulnerability_Tool_V2/templates/report.html b/Vulnerability_Tool_V2/templates/report.html new file mode 100644 index 0000000..8ae54f8 --- /dev/null +++ b/Vulnerability_Tool_V2/templates/report.html @@ -0,0 +1,183 @@ + + + + + + NutriHelp Security Scanner V2.0 Report + + + +
+
+

πŸ”’ NutriHelp Security Scanner V2.0

+
+

Scan time: {{ generated_at }}

+

Target path: {{ scan_info.target_path }}

+

Scanner version: {{ scan_info.scanner_version|default('2.0.0') }}

+
+
+ +
+ {% set severity_counts = {'CRITICAL': 0, 'HIGH': 0, 'MEDIUM': 0, 'LOW': 0} %} + {% for severity, count in summary.by_severity.items() %} + {% if severity.upper() in severity_counts %} + {% set _ = severity_counts.update({severity.upper(): count}) %} + {% endif %} + {% endfor %} + +
+

{{ severity_counts.CRITICAL }}

+

Critical Issues

+
+
+

{{ severity_counts.HIGH }}

+

High Severity

+
+
+

{{ severity_counts.MEDIUM }}

+

Medium Severity

+
+
+

{{ severity_counts.LOW }}

+

Low Severity

+
+
+ +
+
+
+
{{ scan_info.stats.files_scanned }}
+
Files Scanned
+
+
+
{{ scan_info.stats.plugins_loaded }}
+
Plugins Used
+
+
+
{{ summary.total }}
+
Total Issues
+
+
+ +

πŸ” Detailed Findings

+ {% for f in findings %} +
+
+
{{ f.title }}
+ {{ f.severity }} +
+ +
+ πŸ“ {{ f.file_path }} + {% if f.line_number %} (Line {{ f.line_number }}){% endif %} +
+ +
{{ f.description }}
+ + {% if f.recommendation is defined and f.recommendation %} +
+ πŸ’‘ Recommendation: + {{ f.recommendation|replace('\n', '
')|safe }} +
+ {% endif %} + +
+ Plugin: {{ f.plugin_name }} +
+
+ {% endfor %} +
+ + +
+ + \ No newline at end of file diff --git a/Vulnerability_Tool_V2/tests/test_basic_functionality.py b/Vulnerability_Tool_V2/tests/test_basic_functionality.py new file mode 100644 index 0000000..bd61837 --- /dev/null +++ b/Vulnerability_Tool_V2/tests/test_basic_functionality.py @@ -0,0 +1,140 @@ +#!/usr/bin/env python3 +""" +Basic functional unit testing for Vulnerability_Tool_V2 +tests/test_basic_functionality.py +""" + +import unittest +import sys +import os +from pathlib import Path + +# Add project root directory to Python path +project_root = Path(__file__).parent.parent +sys.path.insert(0, str(project_root)) + +try: + from core.config_manager import ConfigManager + from core.scanner_engine import SecurityScannerEngine + from plugins.base_plugin import BaseSecurityPlugin, SecurityFinding +except ImportError as e: + print(f"Import error: {e}") + print("This is expected if modules are not yet implemented") + + +class TestBasicFunctionality(unittest.TestCase): + """Basic functionality test class""" + + def setUp(self): + """Test setup""" + self.test_config_path = project_root / "config" / "scanner_config.yaml" + + def test_config_manager_initialization(self): + """Test ConfigManager initialization""" + try: + config_manager = ConfigManager() + self.assertIsNotNone(config_manager) + print("βœ… ConfigManager initialization test passed") + except Exception as e: + self.skipTest(f"ConfigManager not available: {e}") + + def test_scanner_engine_initialization(self): + """Test SecurityScannerEngine initialization""" + try: + config_manager = ConfigManager() + scanner_config = config_manager.get_scanner_config() + engine = SecurityScannerEngine(scanner_config) + self.assertIsNotNone(engine) + print("βœ… SecurityScannerEngine initialization test passed") + except Exception as e: + self.skipTest(f"SecurityScannerEngine not available: {e}") + + def test_security_finding_creation(self): + """Test SecurityFinding creation""" + try: + finding = SecurityFinding( + title="Test Finding", + description="Test Description", + severity="MEDIUM", + file_path="/test/path", + line_number=1, + plugin_name="TestPlugin" + ) + self.assertEqual(finding.title, "Test Finding") + self.assertEqual(finding.severity, "MEDIUM") + print("βœ… SecurityFinding creation test passed") + except Exception as e: + self.skipTest(f"SecurityFinding not available: {e}") + + def test_base_plugin_interface(self): + """Test BaseSecurityPlugin interface""" + try: + # Create a simple test plugin + class TestPlugin(BaseSecurityPlugin): + def get_plugin_info(self): + return { + 'name': 'Test Plugin', + 'version': '1.0.0', + 'description': 'Test plugin for unit testing' + } + + def get_severity_level(self): + return 'MEDIUM' + + def scan(self, target_path): + return [] + + plugin = TestPlugin() + info = plugin.get_plugin_info() + self.assertEqual(info['name'], 'Test Plugin') + print("βœ… BaseSecurityPlugin interface test passed") + except Exception as e: + self.skipTest(f"BaseSecurityPlugin not available: {e}") + + def test_configuration_file_exists(self): + """Test configuration file existence""" + self.assertTrue(self.test_config_path.exists(), + f"Configuration file not found: {self.test_config_path}") + print("βœ… Configuration file existence test passed") + + def test_directory_structure(self): + """Test directory structure""" + required_dirs = [ + "core", + "plugins", + "config", + "reports", + "tests" + ] + + for dir_name in required_dirs: + dir_path = project_root / dir_name + self.assertTrue(dir_path.exists(), f"Required directory not found: {dir_name}") + + print("βœ… Directory structure test passed") + + +def run_tests(): + """Run all tests""" + print("πŸ§ͺ Running basic functionality tests...") + print("=" * 50) + + # Create test suite + test_suite = unittest.TestLoader().loadTestsFromTestCase(TestBasicFunctionality) + + # Run tests + runner = unittest.TextTestRunner(verbosity=2) + result = runner.run(test_suite) + + print("=" * 50) + if result.wasSuccessful(): + print("πŸŽ‰ All basic functionality tests passed!") + return True + else: + print("❌ Some tests failed or were skipped") + return False + + +if __name__ == '__main__': + success = run_tests() + sys.exit(0 if success else 1) \ No newline at end of file diff --git a/Vulnerability_Tool_V2/tests/test_general_security_plugin.py b/Vulnerability_Tool_V2/tests/test_general_security_plugin.py new file mode 100644 index 0000000..835379e --- /dev/null +++ b/Vulnerability_Tool_V2/tests/test_general_security_plugin.py @@ -0,0 +1,32 @@ +import os +import sys +from pathlib import Path + +# Ensure the package root (Vulnerability_Tool_V2) is on sys.path so `plugins` is importable +sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) + +from plugins.general_security import GeneralSecurityPlugin + + +def make_sample_file(tmp_path, content, name='sample.js'): + p = tmp_path / name + p.write_text(content, encoding='utf-8') + return str(p) + + +def test_hardcoded_secret_detection(tmp_path): + content = """ + const JWT_SECRET = "supersecret123"; + """ + f = make_sample_file(tmp_path, content, 'secret.js') + plugin = GeneralSecurityPlugin() + findings = plugin.scan(str(tmp_path)) + assert any('Hardcoded secret' in f.title for f in findings) + + +def test_db_connection_detection(tmp_path): + content = "db_url = 'postgres://user:pass@localhost:5432/dbname'" + f = make_sample_file(tmp_path, content, 'db.conf') + plugin = GeneralSecurityPlugin() + findings = plugin.scan(str(tmp_path)) + assert any('DB connection' in f.title or 'DB connection' in f.description or 'connection string' in f.description for f in findings) diff --git a/Vulnerability_Tool_V2/tools/render_from_json.py b/Vulnerability_Tool_V2/tools/render_from_json.py new file mode 100644 index 0000000..359c5ea --- /dev/null +++ b/Vulnerability_Tool_V2/tools/render_from_json.py @@ -0,0 +1,35 @@ +#!/usr/bin/env python3 +""" +Helper: render JSON scan result to HTML using the project's renderer (render_html_report). +Usage: render_from_json.py +""" +import sys +import json +import os + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +from core.report_renderer import render_html_report + + +def main(): + if len(sys.argv) < 3: + print('Usage: render_from_json.py ') + return 2 + json_file = sys.argv[1] + output_file = sys.argv[2] + + with open(json_file, 'r', encoding='utf-8') as f: + data = json.load(f) + + # config manager optional; pass None + html = render_html_report(data, None) + + with open(output_file, 'w', encoding='utf-8') as f: + f.write(html) + + print(output_file) + return 0 + +if __name__ == '__main__': + sys.exit(main()) diff --git a/Vulnerability_Tool_V2/verify_phase1.py b/Vulnerability_Tool_V2/verify_phase1.py new file mode 100644 index 0000000..8deb14d --- /dev/null +++ b/Vulnerability_Tool_V2/verify_phase1.py @@ -0,0 +1,250 @@ +#!/usr/bin/env python3 +""" +Phase 1 Quick verification script +Verify that the modular infrastructure is built correctly +""" + +import os +import sys +import subprocess +from pathlib import Path + + +def check_file_exists(file_path, description): + """Check if a file exists""" + if os.path.exists(file_path): + print(f"βœ… {description}: {file_path}") + return True + else: + print(f"❌ {description}: {file_path} (MISSING)") + return False + +def check_directory_structure(): + """Check directory structure""" + print("πŸ—οΈ Checking directory structure...") + + required_dirs = [ + ("core", "Core engine directory"), + ("plugins", "Plugins directory"), + ("plugins/jwt_security", "JWT Security plugin directory"), + ("plugins/rls_security", "RLS Security plugin directory"), + ("config", "Configuration directory"), + ("tests", "Tests directory"), + ("reports", "Reports directory"), + ] + + all_exist = True + for dir_path, description in required_dirs: + if os.path.exists(dir_path): + print(f"βœ… {description}: {dir_path}/") + else: + print(f"❌ {description}: {dir_path}/ (MISSING)") + all_exist = False + + return all_exist + +def check_core_files(): + """Check core files""" + print("\nπŸ”§ Checking core files...") + + required_files = [ + ("plugins/base_plugin.py", "Base plugin class"), + ("core/scanner_engine.py", "Scanner engine"), + ("core/config_manager.py", "Configuration manager"), + ("config/scanner_config.yaml", "Scanner configuration"), + ("scanner_v2.py", "Main program entry"), + ("requirements.txt", "Dependencies file"), + ] + + all_exist = True + for file_path, description in required_files: + if not check_file_exists(file_path, description): + all_exist = False + + return all_exist + +def check_python_syntax(): + """Check Python syntax""" + print("\n🐍 Checking Python syntax...") + + python_files = [ + "plugins/base_plugin.py", + "core/scanner_engine.py", + "core/config_manager.py", + "scanner_v2.py", + "tests/test_basic_functionality.py" + ] + + all_valid = True + for file_path in python_files: + if os.path.exists(file_path): + try: + with open(file_path, 'r', encoding='utf-8') as f: + compile(f.read(), file_path, 'exec') + print(f"βœ… Syntax check passed: {file_path}") + except SyntaxError as e: + print(f"❌ Syntax error {file_path}: {e}") + all_valid = False + else: + print(f"⚠️ File not found: {file_path}") + + return all_valid + +def test_basic_imports(): + """Test basic imports""" + print("\nπŸ“¦ Testing module imports...") + + import_tests = [ + ("from plugins.base_plugin import BaseSecurityPlugin", "Base plugin class"), + ("from core.config_manager import ConfigManager", "Configuration manager"), + ("from core.scanner_engine import SecurityScannerEngine", "Scanner engine"), + ] + + all_imported = True + for import_stmt, description in import_tests: + try: + exec(import_stmt) + print(f"βœ… Import successful: {description}") + except ImportError as e: + print(f"❌ Import failed {description}: {e}") + all_imported = False + except Exception as e: + print(f"❌ Error {description}: {e}") + all_imported = False + + return all_imported + +def test_basic_functionality(): + """Test basic functionality""" + print("\nβš™οΈ Testing basic functionality...") + + try: + # Test configuration manager + from core.config_manager import ConfigManager + config_manager = ConfigManager() + print("βœ… Configuration manager initialized successfully") + + # Test scanner engine + from core.scanner_engine import SecurityScannerEngine + engine = SecurityScannerEngine() + print("βœ… Scanner engine initialized successfully") + + # Test base plugin + from plugins.base_plugin import BaseSecurityPlugin + print("βœ… Base plugin class imported successfully") + + return True + + except Exception as e: + print(f"❌ Functionality test failed: {e}") + return False + +def test_cli_interface(): + """Test command line interface""" + print("\nπŸ–₯️ Testing command line interface...") + + try: + # Test help information + result = subprocess.run([ + sys.executable, 'scanner_v2.py', '--help' + ], capture_output=True, text=True, timeout=10) + + if result.returncode == 0: + print("βœ… Help information displayed correctly") + return True + else: + print(f"❌ Help information failed: {result.stderr}") + return False + + except subprocess.TimeoutExpired: + print("❌ Command line test timed out") + return False + except Exception as e: + print(f"❌ Command line test failed: {e}") + return False + +def run_unit_tests(): + """Run unit tests""" + print("\nπŸ§ͺ Running unit tests...") + + if not os.path.exists('tests/test_basic_functionality.py'): + print("⚠️ Test file not found, skipping unit tests") + return True + + try: + result = subprocess.run([ + sys.executable, 'tests/test_basic_functionality.py' + ], capture_output=True, text=True, timeout=30) + + if result.returncode == 0: + print("βœ… Unit tests passed") + print("πŸ“Š Test output:") + for line in result.stdout.split('\n')[-10:]: # Show last 10 lines + if line.strip(): + print(f" {line}") + return True + else: + print("❌ Unit tests failed") + print("πŸ“Š Test output:", result.stderr) + return False + + except subprocess.TimeoutExpired: + print("❌ Unit tests timed out") + return False + except Exception as e: + print(f"❌ Unit tests failed: {e}") + return False + +def main(): + """Main verification function""" + print("πŸš€ Phase 1 verification started...") + print("=" * 50) + + all_passed = True + + # Check project structure + checks = [ + ("Directory Structure", check_directory_structure), + ("Core Files", check_core_files), + ("Python Syntax", check_python_syntax), + ("Module Imports", test_basic_imports), + ("Basic Functionality", test_basic_functionality), + ("Command Line Interface", test_cli_interface), + ("Unit Tests", run_unit_tests), + ] + + results = {} + + for check_name, check_func in checks: + try: + result = check_func() + results[check_name] = result + if not result: + all_passed = False + except Exception as e: + print(f"❌ {check_name} check failed: {e}") + results[check_name] = False + all_passed = False + + # Output final results + print("\n" + "=" * 50) + print("πŸ“‹ Phase 1 verification results summary:") + + for check_name, passed in results.items(): + status = "βœ… Passed" if passed else "❌ Failed" + print(f" {check_name}: {status}") + + print("\n" + "=" * 50) + + if all_passed: + print("πŸŽ‰ Phase 1 verification succeeded!") + print("βœ… All checks passed") + print("πŸš€ You can proceed to Phase 2 (JWT Security Plugin Development)") + return 0 + else: + print("⚠️ Phase 1 verification failed") + print("πŸ”§ Please fix the issues based on the error messages above and re-verify") + return 1 + +if __name__ == '__main__': + sys.exit(main()) \ No newline at end of file diff --git a/index.yaml b/index.yaml index 40f769e..66ebc61 100644 --- a/index.yaml +++ b/index.yaml @@ -3,10 +3,14 @@ info: title: NutriHelp API version: 1.0.0 servers: - - url: http://localhost/api + - url: "http://localhost" + description: "Local API" + tags: - name: System description: System and security monitoringΒ endpoints + - name: Vulnerability Scanner + description: Endpoints for the vulnerability scanner paths: /system/generate-baseline: post: @@ -78,7 +82,29 @@ paths: /appointments: post: summary: Save appointment data - description: Receives a user ID, date, time, and description, and saves the appointment data + /upload: + post: + summary: Upload a file + description: Upload JPG, PNG, or PDF (max 5MB, limited to 5 uploads per 10 minutes) + security: + - BearerAuth: [] + requestBody: + required: true + content: + multipart/form-data: + schema: + type: object + properties: + file: + type: string + format: binary + responses: + '200': + description: File uploaded successfully + '400': + description: Upload failed due to size/type restriction + '429': + description: Too many uploads from this IP (rate limit exceeded) requestBody: required: true content: @@ -236,6 +262,43 @@ paths: application/json: schema: $ref: '#/components/schemas/ErrorResponse' + + /api/system/test-error/trigger: + post: + tags: + - System + summary: Trigger a simulated error for testing error logging + description: |- + This endpoint intentionally triggers an error so you can test the error logging middleware and verify entries are written to the Supabase `error_logs` table. + Use the `simulate` field in the request body to choose the behavior: `throw` (synchronous throw), `next` (pass to next), or omit for a delayed async error. + requestBody: + required: false + content: + application/json: + schema: + type: object + properties: + simulate: + type: string + example: throw + description: 'Options: "throw", "next" or omitted (delayed error)' + responses: + '200': + description: If the request unexpectedly succeeds + content: + application/json: + schema: + type: object + properties: + message: + type: string + example: Triggered error (this should not be returned) + '500': + description: Error triggered and handled by error logging middleware + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' /fooddata/spicelevels: get: summary: Get spice levels @@ -2131,6 +2194,224 @@ paths: format: date-time example: "2025-08-03T12:14:00.706Z" + /api/scanner/test: + get: + summary: Testing endpoints + tags: [Vulnerability Scanner] + responses: + '200': + description: Testing successful + content: + application/json: + schema: + type: object + properties: + message: + type: string + example: "Scanner API is working!" + timestamp: + type: string + example: "2025-09-05T19:48:20.611Z" + + /api/scanner/health: + get: + summary: Scanner health check + tags: [Vulnerability Scanner] + responses: + '200': + description: Scanner status normal + content: + application/json: + schema: + type: object + properties: + status: + type: string + example: "healthy" + version: + type: string + example: "2.0.0" + timestamp: + type: string + scanner_path: + type: string + '500': + description: Server error + + /api/scanner/plugins: + get: + summary: Get available plugin list + tags: [Vulnerability Scanner] + responses: + '200': + description: Plugin list + content: + application/json: + schema: + type: object + properties: + plugins: + type: array + items: + type: object + properties: + name: + type: string + example: "JWTMissingProtectionPlugin" + description: + type: string + example: "Detect missing JWT protection in API endpoints" + severity_level: + type: string + example: "HIGH" + + /api/scanner/scan: + post: + summary: Start security scan + tags: [Vulnerability Scanner] + security: + - BearerAuth: [] + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/ScanRequest' + responses: + '200': + description: Scan started successfully + content: + application/json: + schema: + type: object + properties: + scan_id: + type: string + example: "scan_20240906_143022" + message: + type: string + example: "Scan started successfully" + status_url: + type: string + example: "/api/scanner/scan/scan_20240906_143022/status" + '400': + description: Request parameter error + '500': + description: Server error + + /api/scanner/scan/{scanId}/status: + get: + summary: Get scan status + tags: [Vulnerability Scanner] + parameters: + - in: path + name: scanId + required: true + schema: + type: string + description: Scan ID + responses: + '200': + description: Scan status + content: + application/json: + schema: + type: object + properties: + scan_id: + type: string + status: + type: string + enum: [running, completed, failed] + progress: + type: integer + minimum: 0 + maximum: 100 + message: + type: string + '404': + description: Scan ID does not exist + + /api/scanner/scan/{scanId}/result: + get: + summary: Get scan result + tags: [Vulnerability Scanner] + parameters: + - in: path + name: scanId + required: true + schema: + type: string + description: Scan ID + responses: + '200': + description: Scan result + content: + application/json: + schema: + $ref: '#/components/schemas/ScanResult' + '202': + description: Scan not completed + '404': + description: Scan ID does not exist + + /api/scanner/scan/{scanId}/report: + get: + summary: Download scan report + tags: [Vulnerability Scanner] + parameters: + - in: path + name: scanId + required: true + schema: + type: string + description: Scan ID + - in: query + name: format + schema: + type: string + enum: [html, json] + default: html + description: Report format + responses: + '200': + description: Report file + content: + text/html: + schema: + type: string + application/json: + schema: + type: object + '202': + description: Scan not completed + '404': + description: Scan ID does not exist + + /api/scanner/quick-scan: + post: + summary: Fast sync scanning + tags: [Vulnerability Scanner] + security: + - BearerAuth: [] + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/ScanRequest' + responses: + '200': + description: Scan result + content: + application/json: + schema: + $ref: '#/components/schemas/ScanResult' + '400': + description: Request parameter error + '500': + description: Scan failed + components: securitySchemes: BearerAuth: @@ -2769,4 +3050,86 @@ components: description: Model confidence score for diabetes prediction. example: 0.798 - \ No newline at end of file + ScanRequest: + type: object + required: + - target_path + properties: + target_path: + type: string + description: Target path to scan + example: "./routes" + plugins: + type: array + items: + type: string + description: Specify the plugin to use + example: ["JWTMissingProtectionPlugin", "JWTConfigurationPlugin"] + output_format: + type: string + enum: [json, html] + default: json + description: Output format + + ScanResult: + type: object + properties: + scan_id: + type: string + description: Scan ID + example: "scan_20240906_143022" + target_path: + type: string + description: Scan target path + example: "./routes" + scan_time: + type: string + format: date-time + description: Scan time + total_files: + type: integer + description: Total number of files scanned + example: 173 + total_findings: + type: integer + description: Total number of findings + example: 28 + severity_summary: + type: object + properties: + CRITICAL: + type: integer + example: 2 + HIGH: + type: integer + example: 16 + MEDIUM: + type: integer + example: 9 + LOW: + type: integer + example: 1 + findings: + type: array + items: + type: object + properties: + title: + type: string + example: "Missing JWT Protection" + severity: + type: string + enum: [CRITICAL, HIGH, MEDIUM, LOW] + example: "CRITICAL" + file_path: + type: string + example: "routes/userprofile.js" + line_number: + type: integer + example: 42 + description: + type: string + example: "API endpoint lacks JWT authentication middleware" + plugin_name: + type: string + example: "JWTMissingProtectionPlugin" diff --git a/middleware/errorLogger.js b/middleware/errorLogger.js new file mode 100644 index 0000000..f3a30e4 --- /dev/null +++ b/middleware/errorLogger.js @@ -0,0 +1,102 @@ +// middleware/errorLogger.js +const errorLogService = require('../services/errorLogService'); + +/** + * Enhanced error logging middleware + */ +const errorLogger = (err, req, res, next) => { + // Automatically categorize errors + const classification = errorLogService.categorizeError(err, { req, res }); + + // Log the error + errorLogService.logError({ + error: err, + req, + res, + category: classification.category, + type: classification.type, + additionalContext: { + route: req.route?.path, + middleware_stack: req.route?.stack?.map(s => s.handle.name), + query_params: req.query, + path_params: req.params + } + }).catch(loggingError => { + console.error('Error in error logging middleware:', loggingError); + }); + + next(err); +}; + +/** + * Request response time tracking middleware + */ +const responseTimeLogger = (req, res, next) => { + const startTime = Date.now(); + + // Capture response end event + res.on('finish', () => { + const responseTime = Date.now() - startTime; + res.responseTime = responseTime; + + // Log slow requests + if (responseTime > 5000) { + errorLogService.logError({ + error: new Error(`Slow request detected: ${responseTime}ms`), + req, + res, + category: 'warning', + type: 'performance', + additionalContext: { + response_time_ms: responseTime, + slow_request: true + } + }); + } + }); + + next(); +}; + +/** + * Uncaught exception handler + */ +const uncaughtExceptionHandler = (error) => { + errorLogService.logError({ + error, + category: 'critical', + type: 'system', + additionalContext: { + uncaught_exception: true, + process_uptime: process.uptime() + } + }); + + console.error('Uncaught Exception:', error); + // Graceful shutdown + process.exit(1); +}; + +/** + * Unhandled Promise Rejection handler + */ +const unhandledRejectionHandler = (reason, promise) => { + errorLogService.logError({ + error: new Error(`Unhandled Promise Rejection: ${reason}`), + category: 'critical', + type: 'system', + additionalContext: { + unhandled_rejection: true, + promise_state: promise + } + }); + + console.error('Unhandled Rejection:', reason); +}; + +module.exports = { + errorLogger, + responseTimeLogger, + uncaughtExceptionHandler, + unhandledRejectionHandler +}; \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index 5b9386b..d703410 100644 --- a/package-lock.json +++ b/package-lock.json @@ -32,6 +32,7 @@ "nutrihelp-api": "file:", "sinon": "^18.0.0", "swagger-ui-express": "^5.0.0", + "uuid": "^8.3.2", "yamljs": "^0.3.0" }, "devDependencies": { @@ -3725,6 +3726,14 @@ "node": ">= 0.4.0" } }, + "node_modules/uuid": { + "version": "8.3.2", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz", + "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==", + "bin": { + "uuid": "dist/bin/uuid" + } + }, "node_modules/validator": { "version": "13.12.0", "resolved": "https://registry.npmjs.org/validator/-/validator-13.12.0.tgz", diff --git a/package.json b/package.json index c437a97..ef554e8 100644 --- a/package.json +++ b/package.json @@ -8,7 +8,9 @@ "dev": "nodemon server.js", "test:rce": "mocha ./test/costEstimationTest.js", "test": "concurrently -k \"node server.js\" \"mocha --timeout 10000 --exit\"", - "validate-env": "node scripts/validateEnv.js" + "validate-env": "node scripts/validateEnv.js", + "security-scan": "python3 scanner_v2.py --format html --output security_report.html", + "security-check": "python3 scanner_v2.py --format summary" }, "keywords": [ "NutriHelp", @@ -42,6 +44,7 @@ "nutrihelp-api": "file:", "sinon": "^18.0.0", "swagger-ui-express": "^5.0.0", + "uuid": "^8.3.2", "yamljs": "^0.3.0" }, "devDependencies": { diff --git a/reports/security_report_scan_20250907_114003.html b/reports/security_report_scan_20250907_114003.html new file mode 100644 index 0000000..29e671d --- /dev/null +++ b/reports/security_report_scan_20250907_114003.html @@ -0,0 +1,2400 @@ + + + + + + + NutriHelp Security Scanner V2.0 Report + + + +
+
+

πŸ”’ NutriHelp Security Scanner V2.0

+
+
Scan time: 2025-09-07 11:40:05
+
Target path: /Users/lichaohui/Desktop/Code/782/Nutrihelp-api
+
Scanner version: 2.0.0
+
+
+ +
+
+
0
+
Critical Issues
+
+
+
0
+
High Severity
+
+
+
69
+
Medium Severity
+
+
+
1
+
Low Severity
+
+
+ +
+
+
+
190
+
Files Scanned
+
+
+
2
+
Plugins Used
+
+
+
70
+
Total Issues
+
+
+ +

πŸ” Detailed Findings

+
+
+
Missing JWT Protection: GET /
+ MEDIUM +
+ +
+ πŸ“„ + jwt server.js + (Line 11) +
+ +
API endpoint GET / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /scanner/plugins
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/api/scanner_api.py + (Line 148) +
+ +
API endpoint GET /scanner/plugins lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /scanner/plugins endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/scanner/plugins', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/scanner/plugins', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /scanner/scan
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/api/scanner_api.py + (Line 167) +
+ +
API endpoint POST /scanner/scan lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST /scanner/scan endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/scanner/scan', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/scanner/scan', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /scanner/scan/{scan_id}/status
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/api/scanner_api.py + (Line 198) +
+ +
API endpoint GET /scanner/scan/{scan_id}/status lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /scanner/scan/{scan_id}/status endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/scanner/scan/{scan_id}/status', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/scanner/scan/{scan_id}/status', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /scanner/scan/{scan_id}/result
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/api/scanner_api.py + (Line 213) +
+ +
API endpoint GET /scanner/scan/{scan_id}/result lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /scanner/scan/{scan_id}/result endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/scanner/scan/{scan_id}/result', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/scanner/scan/{scan_id}/result', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /scanner/scan/{scan_id}/report
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/api/scanner_api.py + (Line 230) +
+ +
API endpoint GET /scanner/scan/{scan_id}/report lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /scanner/scan/{scan_id}/report endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/scanner/scan/{scan_id}/report', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/scanner/scan/{scan_id}/report', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /scanner/scan/quick
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/api/scanner_api.py + (Line 353) +
+ +
API endpoint POST /scanner/scan/quick lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST /scanner/scan/quick endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/scanner/scan/quick', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/scanner/scan/quick', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /users/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/applications.py + (Line 235) +
+ +
API endpoint GET /users/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /users/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/users/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/users/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /items/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/applications.py + (Line 236) +
+ +
API endpoint GET /items/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /items/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/items/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/items/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /items/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/applications.py + (Line 388) +
+ +
API endpoint GET /items/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /items/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/items/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/items/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /items/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/applications.py + (Line 1802) +
+ +
API endpoint GET /items/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /items/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/items/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/items/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: PUT /items/{item_id}
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/applications.py + (Line 2180) +
+ +
API endpoint PUT /items/{item_id} lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the PUT /items/{item_id} endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.put('/items/{item_id}', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.put('/items/{item_id}', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /items/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/applications.py + (Line 2558) +
+ +
API endpoint POST /items/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST /items/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/items/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/items/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: DELETE /items/{item_id}
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/applications.py + (Line 2931) +
+ +
API endpoint DELETE /items/{item_id} lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the DELETE /items/{item_id} endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.delete('/items/{item_id}', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.delete('/items/{item_id}', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: PATCH /items/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/applications.py + (Line 4055) +
+ +
API endpoint PATCH /items/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the PATCH /items/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.patch('/items/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.patch('/items/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /send-notification/{email}
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/background.py + (Line 31) +
+ +
API endpoint POST /send-notification/{email} lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST /send-notification/{email} endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/send-notification/{email}', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/send-notification/{email}', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /users/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/routing.py + (Line 614) +
+ +
API endpoint GET /users/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /users/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/users/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/users/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /users/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/routing.py + (Line 1250) +
+ +
API endpoint GET /users/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /users/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/users/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/users/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /items/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/routing.py + (Line 1710) +
+ +
API endpoint GET /items/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /items/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/items/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/items/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: PUT /items/{item_id}
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/routing.py + (Line 2092) +
+ +
API endpoint PUT /items/{item_id} lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the PUT /items/{item_id} endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.put('/items/{item_id}', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.put('/items/{item_id}', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /items/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/routing.py + (Line 2474) +
+ +
API endpoint POST /items/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST /items/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/items/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/items/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: DELETE /items/{item_id}
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/routing.py + (Line 2851) +
+ +
API endpoint DELETE /items/{item_id} lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the DELETE /items/{item_id} endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.delete('/items/{item_id}', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.delete('/items/{item_id}', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: PATCH /items/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/routing.py + (Line 3992) +
+ +
API endpoint PATCH /items/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the PATCH /items/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.patch('/items/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.patch('/items/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /items/{item_id}
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/exceptions.py + (Line 29) +
+ +
API endpoint GET /items/{item_id} lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /items/{item_id} endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/items/{item_id}', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/items/{item_id}', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /items/{item_id}
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/param_functions.py + (Line 299) +
+ +
API endpoint GET /items/{item_id} lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /items/{item_id} endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/items/{item_id}', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/items/{item_id}', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /items/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/param_functions.py + (Line 2272) +
+ +
API endpoint GET /items/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /items/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/items/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/items/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /users/me/items/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/param_functions.py + (Line 2353) +
+ +
API endpoint GET /users/me/items/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /users/me/items/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/users/me/items/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/users/me/items/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /files/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/datastructures.py + (Line 53) +
+ +
API endpoint POST /files/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST /files/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/files/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/files/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /uploadfile/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/datastructures.py + (Line 58) +
+ +
API endpoint POST /uploadfile/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST /uploadfile/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/uploadfile/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/uploadfile/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /items/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/security/api_key.py + (Line 49) +
+ +
API endpoint GET /items/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /items/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/items/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/items/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /items/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/security/api_key.py + (Line 141) +
+ +
API endpoint GET /items/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /items/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/items/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/items/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /items/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/security/api_key.py + (Line 229) +
+ +
API endpoint GET /items/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /items/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/items/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/items/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /users/me
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/security/http.py + (Line 124) +
+ +
API endpoint GET /users/me lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /users/me endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/users/me', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/users/me', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /users/me
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/security/http.py + (Line 244) +
+ +
API endpoint GET /users/me lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /users/me endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/users/me', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/users/me', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /users/me
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/security/http.py + (Line 348) +
+ +
API endpoint GET /users/me lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /users/me endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/users/me', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/users/me', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /
+ MEDIUM +
+ +
+ πŸ“„ + routes/imageClassification.js + (Line 19) +
+ +
API endpoint POST / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /test
+ MEDIUM +
+ +
+ πŸ“„ + routes/scanner.js + (Line 35) +
+ +
API endpoint GET /test lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /test endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/test', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/test', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /plugins
+ MEDIUM +
+ +
+ πŸ“„ + routes/scanner.js + (Line 177) +
+ +
API endpoint GET /plugins lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /plugins endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/plugins', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/plugins', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /scan
+ MEDIUM +
+ +
+ πŸ“„ + routes/scanner.js + (Line 234) +
+ +
API endpoint POST /scan lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST /scan endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/scan', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/scan', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /scan/:scanId/status
+ MEDIUM +
+ +
+ πŸ“„ + routes/scanner.js + (Line 306) +
+ +
API endpoint GET /scan/:scanId/status lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /scan/:scanId/status endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/scan/:scanId/status', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/scan/:scanId/status', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /scan/:scanId/result
+ MEDIUM +
+ +
+ πŸ“„ + routes/scanner.js + (Line 386) +
+ +
API endpoint GET /scan/:scanId/result lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /scan/:scanId/result endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/scan/:scanId/result', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/scan/:scanId/result', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /scan/:scanId/report
+ MEDIUM +
+ +
+ πŸ“„ + routes/scanner.js + (Line 464) +
+ +
API endpoint GET /scan/:scanId/report lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /scan/:scanId/report endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/scan/:scanId/report', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/scan/:scanId/report', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /scan/:scanId/raw
+ MEDIUM +
+ +
+ πŸ“„ + routes/scanner.js + (Line 587) +
+ +
API endpoint GET /scan/:scanId/raw lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /scan/:scanId/raw endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/scan/:scanId/raw', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/scan/:scanId/raw', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /quick-scan
+ MEDIUM +
+ +
+ πŸ“„ + routes/scanner.js + (Line 621) +
+ +
API endpoint POST /quick-scan lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST /quick-scan endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/quick-scan', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/quick-scan', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: PUT /update-by-identifier
+ MEDIUM +
+ +
+ πŸ“„ + routes/userprofile.js + (Line 14) +
+ +
API endpoint PUT /update-by-identifier lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the PUT /update-by-identifier endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.put('/update-by-identifier', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.put('/update-by-identifier', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /
+ MEDIUM +
+ +
+ πŸ“„ + routes/upload.js + (Line 5) +
+ +
API endpoint POST / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /
+ MEDIUM +
+ +
+ πŸ“„ + routes/waterIntake.js + (Line 5) +
+ +
API endpoint POST / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /
+ MEDIUM +
+ +
+ πŸ“„ + routes/signup.js + (Line 11) +
+ +
API endpoint POST / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /
+ MEDIUM +
+ +
+ πŸ“„ + routes/login.js + (Line 11) +
+ +
API endpoint POST / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /mfa
+ MEDIUM +
+ +
+ πŸ“„ + routes/login.js + (Line 16) +
+ +
API endpoint POST /mfa lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST /mfa endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/mfa', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/mfa', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /createRecipe
+ MEDIUM +
+ +
+ πŸ“„ + routes/recipe.js + (Line 8) +
+ +
API endpoint POST /createRecipe lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST /createRecipe endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/createRecipe', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/createRecipe', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /
+ MEDIUM +
+ +
+ πŸ“„ + routes/recipe.js + (Line 10) +
+ +
API endpoint POST / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: DELETE /
+ MEDIUM +
+ +
+ πŸ“„ + routes/recipe.js + (Line 11) +
+ +
API endpoint DELETE / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the DELETE / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.delete('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.delete('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /
+ MEDIUM +
+ +
+ πŸ“„ + routes/recipeNutritionlog.js + (Line 27) +
+ +
API endpoint GET / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /classify
+ MEDIUM +
+ +
+ πŸ“„ + routes/routes.js + (Line 32) +
+ +
API endpoint POST /classify lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST /classify endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/classify', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/classify', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /
+ MEDIUM +
+ +
+ πŸ“„ + routes/userfeedback.js + (Line 8) +
+ +
API endpoint POST / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /
+ MEDIUM +
+ +
+ πŸ“„ + routes/healthNews.js + (Line 44) +
+ +
API endpoint GET / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /
+ MEDIUM +
+ +
+ πŸ“„ + routes/healthNews.js + (Line 156) +
+ +
API endpoint POST / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: PUT /
+ MEDIUM +
+ +
+ πŸ“„ + routes/healthNews.js + (Line 214) +
+ +
API endpoint PUT / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the PUT / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.put('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.put('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: DELETE /
+ MEDIUM +
+ +
+ πŸ“„ + routes/healthNews.js + (Line 238) +
+ +
API endpoint DELETE / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the DELETE / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.delete('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.delete('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /generate-baseline
+ MEDIUM +
+ +
+ πŸ“„ + routes/systemRoutes.js + (Line 50) +
+ +
API endpoint POST /generate-baseline lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST /generate-baseline endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/generate-baseline', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/generate-baseline', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /integrity-check
+ MEDIUM +
+ +
+ πŸ“„ + routes/systemRoutes.js + (Line 59) +
+ +
API endpoint GET /integrity-check lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /integrity-check endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/integrity-check', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/integrity-check', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /
+ MEDIUM +
+ +
+ πŸ“„ + routes/filter.js + (Line 7) +
+ +
API endpoint GET / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /
+ MEDIUM +
+ +
+ πŸ“„ + routes/articles.js + (Line 5) +
+ +
API endpoint GET / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /:user_id
+ MEDIUM +
+ +
+ πŸ“„ + routes/notifications.js + (Line 21) +
+ +
API endpoint GET /:user_id lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /:user_id endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/:user_id', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/:user_id', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /
+ MEDIUM +
+ +
+ πŸ“„ + routes/contactus.js + (Line 14) +
+ +
API endpoint POST / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Low Entropy JWT Secret
+ MEDIUM +
+ +
+ πŸ“„ + .env + (Line 8) +
+ +
JWT secret appears to have low entropy (predictable patterns).
+ +
+ πŸ’‘ Recommendation: + Improve JWT secret security:
1. Generate a strong secret using crypto:
const crypto = require('crypto');
const secret = crypto.randomBytes(64).toString('hex');

2. Use environment-specific secrets
3. Implement secret rotation
4. Consider using asymmetric keys for larger systems +

+ +
+ Plugin: JWTConfigurationPlugin +
+
+ +
+
+
Low Entropy JWT Secret
+ MEDIUM +
+ +
+ πŸ“„ + .env + (Line 10) +
+ +
JWT secret appears to have low entropy (predictable patterns).
+ +
+ πŸ’‘ Recommendation: + Improve JWT secret security:
1. Generate a strong secret using crypto:
const crypto = require('crypto');
const secret = crypto.randomBytes(64).toString('hex');

2. Use environment-specific secrets
3. Implement secret rotation
4. Consider using asymmetric keys for larger systems +

+ +
+ Plugin: JWTConfigurationPlugin +
+
+ +
+
+
Direct JWT Usage Instead of AuthService
+ MEDIUM +
+ +
+ πŸ“„ + middleware.js + +
+ +
Direct jwt.verify() usage detected instead of centralized authService.
+ +
+ πŸ’‘ Recommendation: + Centralize JWT verification:
1. Create AuthService class
2. Move all JWT operations to AuthService
3. Use AuthService.verifyToken() in middleware
4. Add comprehensive error handling +
+ +
+ Plugin: JWTConfigurationPlugin +
+
+ +
+
+
Incomplete JWT Error Handling
+ LOW +
+ +
+ πŸ“„ + middleware.js + +
+ +
JWT verification lacks comprehensive error handling.
+ +
+ πŸ’‘ Recommendation: + Implement proper JWT error handling:
1. Handle TokenExpiredError
2. Handle JsonWebTokenError
3. Handle NotBeforeError
4. Add logging for security events
5. Return appropriate status codes +
+ +
+ Plugin: JWTConfigurationPlugin +
+
+ +
+ + +
+ + + \ No newline at end of file diff --git a/reports/security_report_scan_20250907_130446.html b/reports/security_report_scan_20250907_130446.html new file mode 100644 index 0000000..8f1c78c --- /dev/null +++ b/reports/security_report_scan_20250907_130446.html @@ -0,0 +1,2732 @@ + + + + + + + NutriHelp Security Scanner V2.0 Report + + + +
+
+

πŸ”’ NutriHelp Security Scanner V2.0

+
+
Scan time: 2025-09-07 13:04:48
+
Target path: /Users/lichaohui/Desktop/Code/782/Nutrihelp-api
+
Scanner version: 2.0.0
+
+
+ +
+
+
8
+
Critical Issues
+
+
+
3
+
High Severity
+
+
+
70
+
Medium Severity
+
+
+
1
+
Low Severity
+
+
+ +
+
+
+
193
+
Files Scanned
+
+
+
3
+
Plugins Used
+
+
+
82
+
Total Issues
+
+
+ +

πŸ” Detailed Findings

+
+
+
Hardcoded secret: password
+ CRITICAL +
+ +
+ πŸ“„ + /Users/lichaohui/Desktop/Code/782/Nutrihelp-api/test/logintest.js + (Line 43) +
+ +
Found likely hardcoded secret key "password" in file. Value length: 20
+ +
+ πŸ’‘ Recommendation: +

Remove hardcoded secrets and use environment variables or a secrets manager.

+
    +
  1. Move the secret into an environment variable or encrypted store.
  2. +
  3. Rotate the exposed secret immediately if used in production.
  4. +
  5. Ensure secrets are not committed to VCS.
  6. +
+
+ +
+ Plugin: general_security +
+
+ +
+
+
Hardcoded secret: password
+ CRITICAL +
+ +
+ πŸ“„ + /Users/lichaohui/Desktop/Code/782/Nutrihelp-api/test/logintest.js + (Line 62) +
+ +
Found likely hardcoded secret key "password" in file. Value length: 15
+ +
+ πŸ’‘ Recommendation: +

Remove hardcoded secrets and use environment variables or a secrets manager.

+
    +
  1. Move the secret into an environment variable or encrypted store.
  2. +
  3. Rotate the exposed secret immediately if used in production.
  4. +
  5. Ensure secrets are not committed to VCS.
  6. +
+
+ +
+ Plugin: general_security +
+
+ +
+
+
Hardcoded secret: password
+ CRITICAL +
+ +
+ πŸ“„ + /Users/lichaohui/Desktop/Code/782/Nutrihelp-api/test/logintest.js + (Line 81) +
+ +
Found likely hardcoded secret key "password" in file. Value length: 11
+ +
+ πŸ’‘ Recommendation: +

Remove hardcoded secrets and use environment variables or a secrets manager.

+
    +
  1. Move the secret into an environment variable or encrypted store.
  2. +
  3. Rotate the exposed secret immediately if used in production.
  4. +
  5. Ensure secrets are not committed to VCS.
  6. +
+
+ +
+ Plugin: general_security +
+
+ +
+
+
Hardcoded secret: password
+ CRITICAL +
+ +
+ πŸ“„ + /Users/lichaohui/Desktop/Code/782/Nutrihelp-api/test/logintest.js + (Line 97) +
+ +
Found likely hardcoded secret key "password" in file. Value length: 11
+ +
+ πŸ’‘ Recommendation: +

Remove hardcoded secrets and use environment variables or a secrets manager.

+
    +
  1. Move the secret into an environment variable or encrypted store.
  2. +
  3. Rotate the exposed secret immediately if used in production.
  4. +
  5. Ensure secrets are not committed to VCS.
  6. +
+
+ +
+ Plugin: general_security +
+
+ +
+
+
Hardcoded secret: password
+ CRITICAL +
+ +
+ πŸ“„ + /Users/lichaohui/Desktop/Code/782/Nutrihelp-api/test/userPreferencesTests.js + (Line 32) +
+ +
Found likely hardcoded secret key "password" in file. Value length: 11
+ +
+ πŸ’‘ Recommendation: +

Remove hardcoded secrets and use environment variables or a secrets manager.

+
    +
  1. Move the secret into an environment variable or encrypted store.
  2. +
  3. Rotate the exposed secret immediately if used in production.
  4. +
  5. Ensure secrets are not committed to VCS.
  6. +
+
+ +
+ Plugin: general_security +
+
+ +
+
+
Hardcoded secret: password
+ CRITICAL +
+ +
+ πŸ“„ + /Users/lichaohui/Desktop/Code/782/Nutrihelp-api/test/signuptest.js + (Line 63) +
+ +
Found likely hardcoded secret key "password" in file. Value length: 18
+ +
+ πŸ’‘ Recommendation: +

Remove hardcoded secrets and use environment variables or a secrets manager.

+
    +
  1. Move the secret into an environment variable or encrypted store.
  2. +
  3. Rotate the exposed secret immediately if used in production.
  4. +
  5. Ensure secrets are not committed to VCS.
  6. +
+
+ +
+ Plugin: general_security +
+
+ +
+
+
Hardcoded secret: jwt
+ CRITICAL +
+ +
+ πŸ“„ + /Users/lichaohui/Desktop/Code/782/Nutrihelp-api/Vulnerability_Tool_V2/plugins/jwt_security/jwt_config.py + (Line 235) +
+ +
Found likely hardcoded secret key "jwt" in file. Value length: 10
+ +
+ πŸ’‘ Recommendation: +

Remove hardcoded secrets and use environment variables or a secrets manager.

+
    +
  1. Move the secret into an environment variable or encrypted store.
  2. +
  3. Rotate the exposed secret immediately if used in production.
  4. +
  5. Ensure secrets are not committed to VCS.
  6. +
+
+ +
+ Plugin: general_security +
+
+ +
+
+
Hardcoded secret: Token
+ CRITICAL +
+ +
+ πŸ“„ + /Users/lichaohui/Desktop/Code/782/Nutrihelp-api/scripts/testAuthAPI.js + (Line 225) +
+ +
Found likely hardcoded secret key "Token" in file. Value length: 25
+ +
+ πŸ’‘ Recommendation: +

Remove hardcoded secrets and use environment variables or a secrets manager.

+
    +
  1. Move the secret into an environment variable or encrypted store.
  2. +
  3. Rotate the exposed secret immediately if used in production.
  4. +
  5. Ensure secrets are not committed to VCS.
  6. +
+
+ +
+ Plugin: general_security +
+
+ +
+
+
Hardcoded DB connection string
+ HIGH +
+ +
+ πŸ“„ + /Users/lichaohui/Desktop/Code/782/Nutrihelp-api/Vulnerability_Tool_V2/plugins/general_security/__init__.py + (Line 90) +
+ +
Found a database connection string in code or config which may contain credentials.
+ +
+ πŸ’‘ Recommendation: + Move DB credentials to environment variables and avoid committing connection strings. +
+ +
+ Plugin: general_security +
+
+ +
+
+
Hardcoded DB connection string
+ HIGH +
+ +
+ πŸ“„ + /Users/lichaohui/Desktop/Code/782/Nutrihelp-api/Vulnerability_Tool_V2/plugins/general_security/__init__.py + (Line 90) +
+ +
Found a database connection string in code or config which may contain credentials.
+ +
+ πŸ’‘ Recommendation: + Move DB credentials to environment variables and avoid committing connection strings. +
+ +
+ Plugin: general_security +
+
+ +
+
+
Hardcoded DB connection string
+ HIGH +
+ +
+ πŸ“„ + /Users/lichaohui/Desktop/Code/782/Nutrihelp-api/Vulnerability_Tool_V2/tests/test_general_security_plugin.py + (Line 28) +
+ +
Found a database connection string in code or config which may contain credentials.
+ +
+ πŸ’‘ Recommendation: + Move DB credentials to environment variables and avoid committing connection strings. +
+ +
+ Plugin: general_security +
+
+ +
+
+
Missing JWT Protection: GET /
+ MEDIUM +
+ +
+ πŸ“„ + jwt server.js + (Line 11) +
+ +
API endpoint GET / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /scanner/plugins
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/api/scanner_api.py + (Line 148) +
+ +
API endpoint GET /scanner/plugins lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /scanner/plugins endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/scanner/plugins', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/scanner/plugins', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /scanner/scan
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/api/scanner_api.py + (Line 167) +
+ +
API endpoint POST /scanner/scan lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST /scanner/scan endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/scanner/scan', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/scanner/scan', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /scanner/scan/{scan_id}/status
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/api/scanner_api.py + (Line 198) +
+ +
API endpoint GET /scanner/scan/{scan_id}/status lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /scanner/scan/{scan_id}/status endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/scanner/scan/{scan_id}/status', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/scanner/scan/{scan_id}/status', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /scanner/scan/{scan_id}/result
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/api/scanner_api.py + (Line 213) +
+ +
API endpoint GET /scanner/scan/{scan_id}/result lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /scanner/scan/{scan_id}/result endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/scanner/scan/{scan_id}/result', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/scanner/scan/{scan_id}/result', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /scanner/scan/{scan_id}/report
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/api/scanner_api.py + (Line 230) +
+ +
API endpoint GET /scanner/scan/{scan_id}/report lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /scanner/scan/{scan_id}/report endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/scanner/scan/{scan_id}/report', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/scanner/scan/{scan_id}/report', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /scanner/scan/quick
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/api/scanner_api.py + (Line 353) +
+ +
API endpoint POST /scanner/scan/quick lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST /scanner/scan/quick endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/scanner/scan/quick', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/scanner/scan/quick', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /users/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/applications.py + (Line 235) +
+ +
API endpoint GET /users/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /users/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/users/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/users/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /items/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/applications.py + (Line 236) +
+ +
API endpoint GET /items/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /items/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/items/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/items/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /items/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/applications.py + (Line 388) +
+ +
API endpoint GET /items/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /items/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/items/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/items/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /items/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/applications.py + (Line 1802) +
+ +
API endpoint GET /items/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /items/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/items/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/items/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: PUT /items/{item_id}
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/applications.py + (Line 2180) +
+ +
API endpoint PUT /items/{item_id} lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the PUT /items/{item_id} endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.put('/items/{item_id}', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.put('/items/{item_id}', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /items/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/applications.py + (Line 2558) +
+ +
API endpoint POST /items/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST /items/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/items/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/items/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: DELETE /items/{item_id}
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/applications.py + (Line 2931) +
+ +
API endpoint DELETE /items/{item_id} lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the DELETE /items/{item_id} endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.delete('/items/{item_id}', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.delete('/items/{item_id}', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: PATCH /items/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/applications.py + (Line 4055) +
+ +
API endpoint PATCH /items/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the PATCH /items/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.patch('/items/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.patch('/items/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /send-notification/{email}
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/background.py + (Line 31) +
+ +
API endpoint POST /send-notification/{email} lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST /send-notification/{email} endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/send-notification/{email}', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/send-notification/{email}', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /users/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/routing.py + (Line 614) +
+ +
API endpoint GET /users/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /users/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/users/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/users/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /users/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/routing.py + (Line 1250) +
+ +
API endpoint GET /users/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /users/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/users/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/users/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /items/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/routing.py + (Line 1710) +
+ +
API endpoint GET /items/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /items/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/items/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/items/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: PUT /items/{item_id}
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/routing.py + (Line 2092) +
+ +
API endpoint PUT /items/{item_id} lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the PUT /items/{item_id} endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.put('/items/{item_id}', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.put('/items/{item_id}', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /items/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/routing.py + (Line 2474) +
+ +
API endpoint POST /items/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST /items/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/items/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/items/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: DELETE /items/{item_id}
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/routing.py + (Line 2851) +
+ +
API endpoint DELETE /items/{item_id} lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the DELETE /items/{item_id} endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.delete('/items/{item_id}', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.delete('/items/{item_id}', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: PATCH /items/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/routing.py + (Line 3992) +
+ +
API endpoint PATCH /items/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the PATCH /items/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.patch('/items/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.patch('/items/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /items/{item_id}
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/exceptions.py + (Line 29) +
+ +
API endpoint GET /items/{item_id} lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /items/{item_id} endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/items/{item_id}', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/items/{item_id}', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /items/{item_id}
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/param_functions.py + (Line 299) +
+ +
API endpoint GET /items/{item_id} lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /items/{item_id} endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/items/{item_id}', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/items/{item_id}', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /items/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/param_functions.py + (Line 2272) +
+ +
API endpoint GET /items/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /items/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/items/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/items/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /users/me/items/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/param_functions.py + (Line 2353) +
+ +
API endpoint GET /users/me/items/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /users/me/items/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/users/me/items/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/users/me/items/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /files/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/datastructures.py + (Line 53) +
+ +
API endpoint POST /files/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST /files/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/files/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/files/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /uploadfile/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/datastructures.py + (Line 58) +
+ +
API endpoint POST /uploadfile/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST /uploadfile/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/uploadfile/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/uploadfile/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /items/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/security/api_key.py + (Line 49) +
+ +
API endpoint GET /items/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /items/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/items/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/items/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /items/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/security/api_key.py + (Line 141) +
+ +
API endpoint GET /items/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /items/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/items/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/items/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /items/
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/security/api_key.py + (Line 229) +
+ +
API endpoint GET /items/ lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /items/ endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/items/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/items/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /users/me
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/security/http.py + (Line 124) +
+ +
API endpoint GET /users/me lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /users/me endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/users/me', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/users/me', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /users/me
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/security/http.py + (Line 244) +
+ +
API endpoint GET /users/me lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /users/me endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/users/me', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/users/me', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /users/me
+ MEDIUM +
+ +
+ πŸ“„ + Vulnerability_Tool_V2/venv/lib/python3.11/site-packages/fastapi/security/http.py + (Line 348) +
+ +
API endpoint GET /users/me lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /users/me endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/users/me', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/users/me', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /
+ MEDIUM +
+ +
+ πŸ“„ + routes/imageClassification.js + (Line 19) +
+ +
API endpoint POST / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /test
+ MEDIUM +
+ +
+ πŸ“„ + routes/scanner.js + (Line 35) +
+ +
API endpoint GET /test lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /test endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/test', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/test', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /plugins
+ MEDIUM +
+ +
+ πŸ“„ + routes/scanner.js + (Line 177) +
+ +
API endpoint GET /plugins lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /plugins endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/plugins', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/plugins', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /scan
+ MEDIUM +
+ +
+ πŸ“„ + routes/scanner.js + (Line 234) +
+ +
API endpoint POST /scan lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST /scan endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/scan', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/scan', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /scan/:scanId/status
+ MEDIUM +
+ +
+ πŸ“„ + routes/scanner.js + (Line 306) +
+ +
API endpoint GET /scan/:scanId/status lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /scan/:scanId/status endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/scan/:scanId/status', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/scan/:scanId/status', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /scan/:scanId/result
+ MEDIUM +
+ +
+ πŸ“„ + routes/scanner.js + (Line 386) +
+ +
API endpoint GET /scan/:scanId/result lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /scan/:scanId/result endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/scan/:scanId/result', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/scan/:scanId/result', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /scan/:scanId/report
+ MEDIUM +
+ +
+ πŸ“„ + routes/scanner.js + (Line 464) +
+ +
API endpoint GET /scan/:scanId/report lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /scan/:scanId/report endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/scan/:scanId/report', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/scan/:scanId/report', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /scan/:scanId/raw
+ MEDIUM +
+ +
+ πŸ“„ + routes/scanner.js + (Line 587) +
+ +
API endpoint GET /scan/:scanId/raw lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /scan/:scanId/raw endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/scan/:scanId/raw', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/scan/:scanId/raw', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /quick-scan
+ MEDIUM +
+ +
+ πŸ“„ + routes/scanner.js + (Line 621) +
+ +
API endpoint POST /quick-scan lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST /quick-scan endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/quick-scan', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/quick-scan', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: PUT /update-by-identifier
+ MEDIUM +
+ +
+ πŸ“„ + routes/userprofile.js + (Line 14) +
+ +
API endpoint PUT /update-by-identifier lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the PUT /update-by-identifier endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.put('/update-by-identifier', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.put('/update-by-identifier', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /
+ MEDIUM +
+ +
+ πŸ“„ + routes/upload.js + (Line 5) +
+ +
API endpoint POST / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /
+ MEDIUM +
+ +
+ πŸ“„ + routes/waterIntake.js + (Line 5) +
+ +
API endpoint POST / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /
+ MEDIUM +
+ +
+ πŸ“„ + routes/signup.js + (Line 11) +
+ +
API endpoint POST / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /
+ MEDIUM +
+ +
+ πŸ“„ + routes/login.js + (Line 11) +
+ +
API endpoint POST / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /mfa
+ MEDIUM +
+ +
+ πŸ“„ + routes/login.js + (Line 16) +
+ +
API endpoint POST /mfa lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST /mfa endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/mfa', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/mfa', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /createRecipe
+ MEDIUM +
+ +
+ πŸ“„ + routes/recipe.js + (Line 8) +
+ +
API endpoint POST /createRecipe lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST /createRecipe endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/createRecipe', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/createRecipe', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /
+ MEDIUM +
+ +
+ πŸ“„ + routes/recipe.js + (Line 10) +
+ +
API endpoint POST / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: DELETE /
+ MEDIUM +
+ +
+ πŸ“„ + routes/recipe.js + (Line 11) +
+ +
API endpoint DELETE / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the DELETE / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.delete('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.delete('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /
+ MEDIUM +
+ +
+ πŸ“„ + routes/recipeNutritionlog.js + (Line 27) +
+ +
API endpoint GET / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /classify
+ MEDIUM +
+ +
+ πŸ“„ + routes/routes.js + (Line 32) +
+ +
API endpoint POST /classify lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST /classify endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/classify', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/classify', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /
+ MEDIUM +
+ +
+ πŸ“„ + routes/userfeedback.js + (Line 8) +
+ +
API endpoint POST / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /
+ MEDIUM +
+ +
+ πŸ“„ + routes/healthNews.js + (Line 44) +
+ +
API endpoint GET / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /
+ MEDIUM +
+ +
+ πŸ“„ + routes/healthNews.js + (Line 156) +
+ +
API endpoint POST / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: PUT /
+ MEDIUM +
+ +
+ πŸ“„ + routes/healthNews.js + (Line 214) +
+ +
API endpoint PUT / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the PUT / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.put('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.put('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: DELETE /
+ MEDIUM +
+ +
+ πŸ“„ + routes/healthNews.js + (Line 238) +
+ +
API endpoint DELETE / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the DELETE / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.delete('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.delete('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /generate-baseline
+ MEDIUM +
+ +
+ πŸ“„ + routes/systemRoutes.js + (Line 50) +
+ +
API endpoint POST /generate-baseline lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST /generate-baseline endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/generate-baseline', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/generate-baseline', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /integrity-check
+ MEDIUM +
+ +
+ πŸ“„ + routes/systemRoutes.js + (Line 59) +
+ +
API endpoint GET /integrity-check lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /integrity-check endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/integrity-check', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/integrity-check', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /
+ MEDIUM +
+ +
+ πŸ“„ + routes/filter.js + (Line 7) +
+ +
API endpoint GET / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /
+ MEDIUM +
+ +
+ πŸ“„ + routes/articles.js + (Line 5) +
+ +
API endpoint GET / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: GET /:user_id
+ MEDIUM +
+ +
+ πŸ“„ + routes/notifications.js + (Line 21) +
+ +
API endpoint GET /:user_id lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the GET /:user_id endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.get('/:user_id', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.get('/:user_id', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Missing JWT Protection: POST /
+ MEDIUM +
+ +
+ πŸ“„ + routes/contactus.js + (Line 14) +
+ +
API endpoint POST / lacks JWT authentication middleware
+ +
+ πŸ’‘ Recommendation: +

Protect the POST / endpoint with authentication middleware.

+
    +
  1. Import authentication middleware: const authenticateToken = require('../middleware/authenticateToken');
  2. +
  3. Add middleware to route: router.post('/', authenticateToken, (req, res) => { /* handler */ });
  4. +
  5. Ensure JWT configuration is secure: use strong secrets, set appropriate expiration, and handle errors properly.
  6. +
+
router.post('/', authenticateToken, (req, res) => {
+  // Your route handler
+});
+
+ +
+ Plugin: JWTMissingProtectionPlugin +
+
+ +
+
+
Low Entropy JWT Secret
+ MEDIUM +
+ +
+ πŸ“„ + .env + (Line 8) +
+ +
JWT secret appears to have low entropy (predictable patterns).
+ +
+ πŸ’‘ Recommendation: + Improve JWT secret security:
1. Generate a strong secret using crypto:
const crypto = require('crypto');
const secret = crypto.randomBytes(64).toString('hex');

2. Use environment-specific secrets
3. Implement secret rotation
4. Consider using asymmetric keys for larger systems +

+ +
+ Plugin: JWTConfigurationPlugin +
+
+ +
+
+
Low Entropy JWT Secret
+ MEDIUM +
+ +
+ πŸ“„ + .env + (Line 10) +
+ +
JWT secret appears to have low entropy (predictable patterns).
+ +
+ πŸ’‘ Recommendation: + Improve JWT secret security:
1. Generate a strong secret using crypto:
const crypto = require('crypto');
const secret = crypto.randomBytes(64).toString('hex');

2. Use environment-specific secrets
3. Implement secret rotation
4. Consider using asymmetric keys for larger systems +

+ +
+ Plugin: JWTConfigurationPlugin +
+
+ +
+
+
Direct JWT Usage Instead of AuthService
+ MEDIUM +
+ +
+ πŸ“„ + middleware.js + +
+ +
Direct jwt.verify() usage detected instead of centralized authService.
+ +
+ πŸ’‘ Recommendation: + Centralize JWT verification:
1. Create AuthService class
2. Move all JWT operations to AuthService
3. Use AuthService.verifyToken() in middleware
4. Add comprehensive error handling +
+ +
+ Plugin: JWTConfigurationPlugin +
+
+ +
+
+
Permissive CORS configuration
+ MEDIUM +
+ +
+ πŸ“„ + /Users/lichaohui/Desktop/Code/782/Nutrihelp-api/Vulnerability_Tool_V2/plugins/general_security/__init__.py + +
+ +
Detected wildcard CORS origin which allows any origin to access resources.
+ +
+ πŸ’‘ Recommendation: +

Restrict CORS origins to a specific allowlist.

+
    +
  1. Replace wildcard origin with an explicit list of allowed origins.
  2. +
  3. If dynamic, validate and sanitize the Origin header before echoing it back.
  4. +
+
+ +
+ Plugin: general_security +
+
+ +
+
+
Incomplete JWT Error Handling
+ LOW +
+ +
+ πŸ“„ + middleware.js + +
+ +
JWT verification lacks comprehensive error handling.
+ +
+ πŸ’‘ Recommendation: + Implement proper JWT error handling:
1. Handle TokenExpiredError
2. Handle JsonWebTokenError
3. Handle NotBeforeError
4. Add logging for security events
5. Return appropriate status codes +
+ +
+ Plugin: JWTConfigurationPlugin +
+
+ +
+ + +
+ + + \ No newline at end of file diff --git a/routes/index.js b/routes/index.js index 92b9edb..7b65e7c 100644 --- a/routes/index.js +++ b/routes/index.js @@ -29,5 +29,6 @@ module.exports = app => { app.use('/api/recipe/scale', require('./recipeScaling')); app.use('/api/water-intake', require('./waterIntake')); app.use('/api/health-news', require('./healthNews')); + app.use('/api/scanner', require('./scanner')); // Vulnerability Scanner API }; \ No newline at end of file diff --git a/routes/scanner.js b/routes/scanner.js new file mode 100644 index 0000000..120a5c5 --- /dev/null +++ b/routes/scanner.js @@ -0,0 +1,1003 @@ +// routes/scanner.js +const express = require('express'); +const router = express.Router(); +const { spawn, spawnSync } = require('child_process'); +const path = require('path'); +const fs = require('fs').promises; +const { v4: uuidv4 } = require('uuid'); + +// Storage Scan Status +const activeScanners = new Map(); + +// Generate scan id in style: scan_YYYYMMDD_HHMMSS_ +function generateScanId() { + const now = new Date(); + const pad = (n) => String(n).padStart(2, '0'); + const YYYY = now.getFullYear(); + const MM = pad(now.getMonth() + 1); + const DD = pad(now.getDate()); + const hh = pad(now.getHours()); + const mm = pad(now.getMinutes()); + const ss = pad(now.getSeconds()); + return `scan_${YYYY}${MM}${DD}_${hh}${mm}${ss}`; +} + +/** + * @swagger + * /api/scanner/test: + * get: + * summary: Test endpoint + * tags: [Vulnerability Scanner] + * responses: + * 200: + * description: Test successful + */ +router.get('/test', (req, res) => { + res.json({ message: 'Scanner API is working!', timestamp: new Date().toISOString() }); +}); + +/** + * @swagger + * components: + * schemas: + * ScanRequest: + * type: object + * required: + * - target_path + * properties: + * target_path: + * type: string + * description: Target path to scan + * example: "./routes" + * plugins: + * type: array + * items: + * type: string + * description: Specify the plugin to use + * example: ["JWTMissingProtectionPlugin", "JWTConfigurationPlugin"] + * output_format: + * type: string + * enum: [json, html] + * default: json + * description: Output format + * ScanResult: + * type: object + * properties: + * scan_id: + * type: string + * description: Scan ID + * target_path: + * type: string + * description: Scan target path + * scan_time: + * type: string + * format: date-time + * description: Scan time + * total_files: + * type: integer + * description: Total number of files scanned + * total_findings: + * type: integer + * description: Total number of findings + * severity_summary: + * type: object + * properties: + * CRITICAL: + * type: integer + * HIGH: + * type: integer + * MEDIUM: + * type: integer + * LOW: + * type: integer + * findings: + * type: array + * items: + * type: object + * properties: + * title: + * type: string + * severity: + * type: string + * file_path: + * type: string + * description: + * type: string + * securitySchemes: + * BearerAuth: + * type: http + * scheme: bearer + * bearerFormat: JWT + */ + +/** + * @swagger + * /api/scanner/health: + * get: + * summary: Scanner health check + * tags: [Vulnerability Scanner] + * responses: + * 200: + * description: Scanner is healthy + * content: + * application/json: + * schema: + * type: object + * properties: + * status: + * type: string + * example: healthy + * version: + * type: string + * example: "2.0.0" + */ +router.get('/health', async (req, res) => { + try { + const scannerPath = path.join(__dirname, '../Vulnerability_Tool_V2'); + const exists = await fs.access(scannerPath).then(() => true).catch(() => false); + + res.json({ + status: exists ? 'healthy' : 'scanner_not_found', + version: '2.0.0', + timestamp: new Date().toISOString(), + scanner_path: scannerPath + }); + } catch (error) { + res.status(500).json({ + status: 'error', + message: error.message + }); + } +}); + +/** + * @swagger + * /api/scanner/plugins: + * get: + * summary: Get available plugin list + * tags: [Vulnerability Scanner] + * responses: + * 200: + * description: Plugin list + * content: + * application/json: + * schema: + * type: object + * properties: + * plugins: + * type: array + * items: + * type: object + * properties: + * name: + * type: string + * description: + * type: string + */ +router.get('/plugins', async (req, res) => { + try { + const plugins = [ + { + name: "JWTMissingProtectionPlugin", + description: "Detect missing JWT protection in API endpoints", + severity_level: "HIGH" + }, + { + name: "JWTConfigurationPlugin", + description: "Validate JWT configuration security", + severity_level: "MEDIUM" + } + ]; + + res.json({ plugins }); + } catch (error) { + res.status(500).json({ + success: false, + error: error.message + }); + } +}); + +/** + * @swagger + * /api/scanner/scan: + * post: + * summary: Start security scan + * tags: [Vulnerability Scanner] + * security: + * - BearerAuth: [] + * requestBody: + * required: true + * content: + * application/json: + * schema: + * $ref: '#/components/schemas/ScanRequest' + * responses: + * 200: + * description: Scan started successfully + * content: + * application/json: + * schema: + * type: object + * properties: + * scan_id: + * type: string + * message: + * type: string + * status_url: + * type: string + * 400: + * description: Request parameter error + * 500: + * description: Server error + */ +router.post('/scan', async (req, res) => { + try { + const { target_path, plugins, output_format = 'json' } = req.body; + + if (!target_path) { + return res.status(400).json({ + success: false, + error: 'target_path is required' + }); + } + + // Validate target path + const targetExists = await fs.access(target_path).then(() => true).catch(() => false); + if (!targetExists) { + return res.status(400).json({ + success: false, + error: `Target path does not exist: ${target_path}` + }); + } + + const scanId = generateScanId(); + + // Start asynchronous scan + startPythonScan(scanId, target_path, plugins, output_format); + + res.json({ + scan_id: scanId, + message: 'Scan started successfully', + status_url: `/api/scanner/scan/${scanId}/status` + }); + + } catch (error) { + res.status(500).json({ + success: false, + error: error.message + }); + } +}); + +/** + * @swagger + * /api/scanner/scan/{scanId}/status: + * get: + * summary: Get scan status + * tags: [Vulnerability Scanner] + * parameters: + * - in: path + * name: scanId + * required: true + * schema: + * type: string + * description: 扫描ID + * responses: + * 200: + * description: ζ‰«ζηŠΆζ€ + * content: + * application/json: + * schema: + * type: object + * properties: + * scan_id: + * type: string + * status: + * type: string + * enum: [running, completed, failed] + * progress: + * type: integer + * message: + * type: string + * 404: + * description: Scan ID does not exist + */ +router.get('/scan/:scanId/status', async (req, res) => { + const { scanId } = req.params; + let scanInfo = activeScanners.get(scanId); + + if (!scanInfo) { + // Try to load persisted report files as a fallback (project reports or scanner reports) + const projectReportJson = path.join(process.cwd(), 'reports', `security_result_${scanId}.json`); + const scannerReportHtml = path.join(process.cwd(), 'Vulnerability_Tool_V2', 'reports', `security_report_${scanId}.html`); + try { + // try json first + if (fs) { + const jsonExists = await fs.access(projectReportJson).then(() => true).catch(() => false); + if (jsonExists) { + const data = await fs.readFile(projectReportJson, 'utf8'); + scanInfo = { status: 'completed', result: JSON.parse(data) }; + } else { + const htmlExists = await fs.access(scannerReportHtml).then(() => true).catch(() => false); + if (htmlExists) { + const html = await fs.readFile(scannerReportHtml, 'utf8'); + // crude extraction: count finding blocks and try to read embedded summary JSON + const findings = []; + const findingRegex = /
([\s\S]*?)<\/div>/g; + let m; + while ((m = findingRegex.exec(html)) !== null) { + findings.push({ title: m[1].trim() }); + } + // try to extract a summary JSON blob if present + const jsonBlobMatch = html.match(/\{[\s\S]*?\}/); + let summary = {}; + if (jsonBlobMatch) { + try { summary = JSON.parse(jsonBlobMatch[0]); } catch (e) { summary = {}; } + } + scanInfo = { status: 'completed', result: { scan_info: summary.scan_info || {}, summary: summary.summary || {}, findings: findings } }; + } + } + } + } catch (e) { + // ignore and fall through to 404 + } + } + if (!scanInfo) { + return res.status(404).json({ + success: false, + error: 'Scan ID not found' + }); + } + + res.json({ + scan_id: scanId, + status: scanInfo.status, + progress: scanInfo.progress, + message: scanInfo.message + }); +}); + +/** + * @swagger + * /api/scanner/scan/{scanId}/result: + * get: + * summary: Get scan result + * tags: [Vulnerability Scanner] + * parameters: + * - in: path + * name: scanId + * required: true + * schema: + * type: string + * description: Scan ID + * responses: + * 200: + * description: Scan result + * content: + * application/json: + * schema: + * $ref: '#/components/schemas/ScanResult' + * 202: + * description: Scan not completed yet + * 404: + * description: Scan ID does not exist + */ +router.get('/scan/:scanId/result', async (req, res) => { + const { scanId } = req.params; + const scanInfo = activeScanners.get(scanId); + + if (!scanInfo) { + return res.status(404).json({ + success: false, + error: 'Scan ID not found' + }); + } + + if (scanInfo.status !== 'completed') { + return res.status(202).json({ + success: false, + error: 'Scan not completed yet', + status: scanInfo.status + }); + } + + if (!scanInfo.result) { + return res.status(500).json({ + success: false, + error: 'Scan result not available' + }); + } + + // Normalize response: ensure scan_id matches requested scanId and return summary before findings + const fullResult = scanInfo.result || {}; + const summary = fullResult.summary || fullResult.scan_info || {}; + const findings = fullResult.findings || fullResult.issues || []; + + const responsePayload = { + scan_id: scanId, + summary: { + total_findings: summary.total || summary.total_findings || (Array.isArray(findings) ? findings.length : 0), + files_scanned: summary.files_scanned || (summary.stats && summary.stats.files_scanned) || (fullResult.scan_info && fullResult.scan_info.stats && fullResult.scan_info.stats.files_scanned) || null, + by_severity: summary.by_severity || summary.severity_summary || fullResult.by_severity || null, + by_plugin: summary.by_plugin || fullResult.by_plugin || null + }, + findings: findings + }; + + res.json(responsePayload); +}); + +/** + * @swagger + * /api/scanner/scan/{scanId}/report: + * get: + * summary: Download scan report + * tags: [Vulnerability Scanner] + * parameters: + * - in: path + * name: scanId + * required: true + * schema: + * type: string + * description: Scan ID + * - in: query + * name: format + * schema: + * type: string + * enum: [html, json] + * default: html + * description: Report format + * responses: + * 200: + * description: Report file + * content: + * text/html: + * schema: + * type: string + * application/json: + * schema: + * type: object + * 404: + * description: Scan ID does not exist + */ +router.get('/scan/:scanId/report', async (req, res) => { + const { scanId } = req.params; + const { format = 'html' } = req.query; + console.log('REPORT request:', { scanId, format, query: req.query }); + const scanInfo = activeScanners.get(scanId); + + if (!scanInfo) { + return res.status(404).json({ + success: false, + error: 'Scan ID not found' + }); + } + + if (scanInfo.status !== 'completed') { + return res.status(202).json({ + success: false, + error: 'Scan not completed yet' + }); + } + + if (format === 'html' && scanInfo.result) { + // Persist and return HTML report. Prefer project's Python renderer for exact parity if available. + try { + const reportsDir = path.join(__dirname, '../reports'); + await fs.mkdir(reportsDir, { recursive: true }); + const htmlPath = path.join(reportsDir, `security_report_${scanId}.html`); + + // First try to use Python renderer if present + const pythonRenderer = path.join(__dirname, '../Vulnerability_Tool_V2/tools/render_from_json.py'); + const scannerPath = path.join(__dirname, '../Vulnerability_Tool_V2'); + const projectRoot = path.join(__dirname, '..'); + + if (await fs.access(pythonRenderer).then(() => true).catch(() => false)) { + // write JSON temp file (in project reports dir) + const tmpJson = path.join(reportsDir, `tmp_${scanId}.json`); + await fs.writeFile(tmpJson, JSON.stringify(scanInfo.result, null, 2)); + + // Try venv python first, then system python3, then python + const pythonCandidates = [ + path.join(scannerPath, 'venv', 'bin', 'python'), + 'python3', + 'python' + ]; + + let spawnRes = null; + let usedPython = null; + for (const py of pythonCandidates) { + try { + spawnRes = spawnSync(py, [pythonRenderer, tmpJson, htmlPath], { cwd: projectRoot, encoding: 'utf8' }); + } catch (e) { + spawnRes = { error: e }; + } + if (spawnRes && !spawnRes.error && spawnRes.status === 0) { + usedPython = py; + break; + } + } + + // remove tmp + try { await fs.unlink(tmpJson); } catch (e) {} + + // If helper succeeded but file somehow ended up under the scanner's own reports folder, + // move it into the project reports dir so we have a single canonical location. + const altPath = path.join(scannerPath, 'reports', path.basename(htmlPath)); + const altExists = await fs.access(altPath).then(() => true).catch(() => false); + const htmlExists = await fs.access(htmlPath).then(() => true).catch(() => false); + + if (!htmlExists && altExists) { + // move into expected reportsDir + try { + await fs.mkdir(reportsDir, { recursive: true }); + await fs.rename(altPath, htmlPath); + } catch (moveErr) { + // ignore move error and keep track of alt path + } + } + + // if python helper failed or file still missing, fallback to JS renderer + const finalHtmlExists = await fs.access(htmlPath).then(() => true).catch(() => false); + if (!finalHtmlExists || !usedPython) { + const html = generateHTMLReport(scanInfo.result); + await fs.writeFile(htmlPath, html); + } + } else { + // No python helper available; use JS renderer + const html = generateHTMLReport(scanInfo.result); + await fs.writeFile(htmlPath, html); + } + + // Attach path to scanInfo and send as downloadable file + // Prefer project reports dir, but if missing, check scanner's own reports folder + const projectHtmlPath = path.join(__dirname, '../reports', `security_report_${scanId}.html`); + const scannerHtmlPath = path.join(__dirname, '../Vulnerability_Tool_V2/reports', `security_report_${scanId}.html`); + const projectExists = await fs.access(projectHtmlPath).then(() => true).catch(() => false); + const scannerExists = await fs.access(scannerHtmlPath).then(() => true).catch(() => false); + let finalPath = null; + if (projectExists) finalPath = projectHtmlPath; + else if (scannerExists) finalPath = scannerHtmlPath; + else finalPath = htmlPath; // fallback to whatever we wrote earlier + + // record chosen path + scanInfo.reportPath = finalPath; + const htmlContent = await fs.readFile(finalPath, 'utf-8'); + res.setHeader('Content-Type', 'text/html'); + res.setHeader('Content-Disposition', `attachment; filename="security_report_${scanId}.html"`); + res.send(htmlContent); + return; + } catch (err) { + res.status(500).json({ success: false, error: 'Failed to generate HTML report', details: err.message }); + return; + } + } else if (format === 'json') { + res.setHeader('Content-Disposition', `attachment; filename="security_report_${scanId}.json"`); + res.json(scanInfo.result); + } else { + res.status(400).json({ + success: false, + error: 'Invalid format or report not available' + }); + } +}); + +// Debug endpoint: return raw python stdout and JSON candidates for a scan (useful for diagnosing parsing issues) +router.get('/scan/:scanId/raw', (req, res) => { + const { scanId } = req.params; + const scanInfo = activeScanners.get(scanId); + if (!scanInfo) { + return res.status(404).json({ success: false, error: 'Scan ID not found' }); + } + + const raw = scanInfo.rawOutput || ''; + const candidates = collectJSONCandidates(raw); + res.json({ scan_id: scanId, status: scanInfo.status, progress: scanInfo.progress, raw_preview: raw.slice(0, 4000), candidate_count: candidates.length, candidates: candidates.slice(-3) }); +}); + +/** + * @swagger + * /api/scanner/quick-scan: + * post: + * summary: Quick synchronous scan + * tags: [Vulnerability Scanner] + * security: + * - BearerAuth: [] + * requestBody: + * required: true + * content: + * application/json: + * schema: + * $ref: '#/components/schemas/ScanRequest' + * responses: + * 200: + * description: Scan result + * content: + * application/json: + * schema: + * $ref: '#/components/schemas/ScanResult' + */ +router.post('/quick-scan', async (req, res) => { + try { + const { target_path, plugins, output_format = 'json' } = req.body; + + if (!target_path) { + return res.status(400).json({ + success: false, + error: 'target_path is required' + }); + } + // Validate target path exists (same as the async /scan endpoint) + const targetExists = await fs.access(target_path).then(() => true).catch(() => false); + if (!targetExists) { + return res.status(400).json({ + success: false, + error: `Target path does not exist: ${target_path}` + }); + } + + const scanId = generateScanId(); + const result = await runPythonScanSync(target_path, plugins, output_format); + + res.json({ + scan_id: scanId, + target_path: target_path, + scan_time: new Date().toISOString(), + ...result + }); + + } catch (error) { + res.status(500).json({ + success: false, + error: error.message + }); + } +}); + +// Start asynchronous Python scan +function startPythonScan(scanId, targetPath, plugins, outputFormat) { + activeScanners.set(scanId, { + status: 'running', + progress: 0, + message: 'Scan initiated' + }); + + const scannerPath = path.join(__dirname, '../Vulnerability_Tool_V2'); + const pythonPath = path.join(scannerPath, 'venv/bin/python'); + const scriptPath = path.join(scannerPath, 'scanner_v2.py'); + + const args = ['--target', targetPath, '--format', outputFormat]; + + let pythonProcess; + try { + pythonProcess = spawn(pythonPath, [scriptPath, ...args], { + cwd: scannerPath + }); + } catch (spawnErr) { + const scanInfo = activeScanners.get(scanId); + if (scanInfo) { + scanInfo.status = 'failed'; + scanInfo.progress = 0; + scanInfo.message = `Failed to start python scanner: ${spawnErr.message || String(spawnErr)}`; + scanInfo.rawOutput = (scanInfo.rawOutput || '') + '\n\nSPAWN_ERROR:\n' + (spawnErr.stack || String(spawnErr)); + } + return; + } + + // handle runtime errors from the child process (e.g., exec failures) + pythonProcess.on('error', (err) => { + const scanInfo = activeScanners.get(scanId); + if (scanInfo) { + scanInfo.status = 'failed'; + scanInfo.progress = 0; + scanInfo.message = `Python process error: ${err.message || String(err)}`; + scanInfo.rawOutput = (scanInfo.rawOutput || '') + '\n\nPROCESS_ERROR:\n' + (err.stack || String(err)); + // persist raw output for post-mortem + (async () => { + try { + const reportsDir = path.join(__dirname, '../reports'); + await fs.mkdir(reportsDir, { recursive: true }); + const rawPath = path.join(reportsDir, `raw_${scanId}.log`); + await fs.writeFile(rawPath, scanInfo.rawOutput || (err.stack || String(err))); + scanInfo.rawOutputPath = rawPath; + } catch (e) { + // nothing else to do + } + })(); + } + }); + + let outputData = ''; + let errorData = ''; + // save raw output for debugging + + pythonProcess.stdout.on('data', (data) => { + outputData += data.toString(); + // Update progress + const scanInfo = activeScanners.get(scanId); + console.log('Python output chunk:', data.toString()); // Debug output + }); + + pythonProcess.stderr.on('data', (data) => { + errorData += data.toString(); + }); + + pythonProcess.on('close', (code) => { + console.log('Full Python output:', outputData); + + const scanInfo = activeScanners.get(scanId); + if (scanInfo) scanInfo.rawOutput = outputData; + if (!scanInfo) return; + + if (code === 0) { + try { + const result = parseBestJSON(outputData); + scanInfo.status = 'completed'; + scanInfo.progress = 100; + scanInfo.message = 'Scan completed successfully'; + scanInfo.result = result; + + // If there is HTML output, save it as well + if (outputFormat === 'html') { + scanInfo.htmlReport = generateHTMLReport(result); + // persist into project reports dir for easy discovery (async IIFE) + (async () => { + try { + const reportsDir = path.join(__dirname, '../reports'); + await fs.mkdir(reportsDir, { recursive: true }); + const htmlPath = path.join(reportsDir, `security_report_${scanId}.html`); + await fs.writeFile(htmlPath, scanInfo.htmlReport); + scanInfo.reportPath = htmlPath; + } catch (e) { + // if writing to project reports fails, leave as-is and record message + scanInfo.message = (scanInfo.message || '') + `; Failed to persist html report: ${e.message}`; + } + })(); + } + } catch (error) { + // Persist raw output to disk for post-mortem analysis + (async () => { + try { + const reportsDir = path.join(__dirname, '../reports'); + await fs.mkdir(reportsDir, { recursive: true }); + const rawPath = path.join(reportsDir, `raw_${scanId}.log`); + await fs.writeFile(rawPath, outputData); + scanInfo.rawOutputPath = rawPath; + scanInfo.status = 'failed'; + scanInfo.message = `Failed to parse scan result: ${error.message}. Raw output saved to: ${rawPath}`; + } catch (fsErr) { + scanInfo.status = 'failed'; + scanInfo.message = `Failed to parse scan result: ${error.message}. Also failed to write raw output: ${fsErr.message}`; + } + })(); + } + } else { + // Try to salvage a result if the python process printed JSON despite non-zero exit + try { + const maybeResult = parseBestJSON(outputData); + scanInfo.status = 'completed'; + scanInfo.progress = 100; + scanInfo.message = `Scan completed with non-zero exit code ${code} but output parsed successfully`; + scanInfo.result = maybeResult; + } catch (parseErr) { + // Save raw output for non-zero exit as well + (async () => { + try { + const reportsDir = path.join(__dirname, '../reports'); + await fs.mkdir(reportsDir, { recursive: true }); + const rawPath = path.join(reportsDir, `raw_${scanId}.log`); + await fs.writeFile(rawPath, outputData + '\n\nSTDERR:\n' + errorData); + scanInfo.rawOutputPath = rawPath; + scanInfo.status = 'failed'; + scanInfo.message = `Scan failed with code ${code}. Raw output saved to: ${rawPath}`; + } catch (fsErr) { + scanInfo.status = 'failed'; + scanInfo.message = `Scan failed with code ${code}: ${errorData}. Also failed to write raw output: ${fsErr.message}`; + } + })(); + } + } + }); +} + +// Run Python scan synchronously +function runPythonScanSync(targetPath, plugins, outputFormat) { + return new Promise((resolve, reject) => { + const scannerPath = path.join(__dirname, '../Vulnerability_Tool_V2'); + const pythonPath = path.join(scannerPath, 'venv/bin/python'); + const scriptPath = path.join(scannerPath, 'scanner_v2.py'); + + // Use the requested output format (was hard-coded to 'json') + const args = ['--target', targetPath, '--format', outputFormat || 'json']; + + const pythonProcess = spawn(pythonPath, [scriptPath, ...args], { + cwd: scannerPath + }); + + let outputData = ''; + let errorData = ''; + + pythonProcess.stdout.on('data', (data) => { + outputData += data.toString(); + }); + + pythonProcess.stderr.on('data', (data) => { + errorData += data.toString(); + }); + + pythonProcess.on('close', (code) => { + if (code === 0) { + try { + const result = parseBestJSON(outputData); + resolve(result); + } catch (error) { + // persist raw output to disk for debugging + (async () => { + try { + const reportsDir = path.join(__dirname, '../reports'); + await fs.mkdir(reportsDir, { recursive: true }); + const rawPath = path.join(reportsDir, `raw_sync_${Date.now()}.log`); + await fs.writeFile(rawPath, outputData); + reject(new Error(`Failed to parse scan result: ${error.message}. Raw output saved to: ${rawPath}`)); + } catch (fsErr) { + reject(new Error(`Failed to parse scan result: ${error.message}. Also failed to write raw output: ${fsErr.message}`)); + } + })(); + } + } else { + // Attempt to salvage a valid JSON result even when the process exited with non-zero code. + try { + const maybeResult = parseBestJSON(outputData); + // resolved with parsed result; caller will treat as successful quick-scan + resolve(maybeResult); + return; + } catch (parseErr) { + // if parsing fails, persist raw output and reject as before + (async () => { + try { + const reportsDir = path.join(__dirname, '../reports'); + await fs.mkdir(reportsDir, { recursive: true }); + const rawPath = path.join(reportsDir, `raw_sync_${Date.now()}.log`); + await fs.writeFile(rawPath, outputData + '\n\nSTDERR:\n' + errorData); + reject(new Error(`Scan failed with code ${code}. Raw output saved to: ${rawPath}`)); + } catch (fsErr) { + reject(new Error(`Scan failed with code ${code}: ${errorData}. Also failed to write raw output: ${fsErr.message}`)); + } + })(); + } + } + }); + }); +} + +// Collect JSON candidates from text by tracking balanced braces/brackets +function collectJSONCandidates(text) { + if (!text || typeof text !== 'string') return []; + + const candidates = []; + const len = text.length; + let inString = false; + let escape = false; + let depth = 0; + let start = -1; + + for (let i = 0; i < len; i++) { + const ch = text[i]; + if (inString) { + if (escape) { escape = false; } + else if (ch === '\\') { escape = true; } + else if (ch === '"') { inString = false; } + continue; + } + if (ch === '"') { inString = true; continue; } + + if ((ch === '{' || ch === '[') && start === -1) { + start = i; + depth = 1; + continue; + } + + if (start !== -1) { + if (ch === '{' || ch === '[') depth++; + else if (ch === '}' || ch === ']') { + depth--; + if (depth === 0) { + candidates.push(text.substring(start, i + 1).trim()); + start = -1; + } + } + } + } + return candidates; +} + +// Attempt to parse the best JSON candidate from text, with progressive trimming if needed +function parseBestJSON(text) { + const candidates = collectJSONCandidates(text); + if (!candidates || candidates.length === 0) throw new Error('No JSON object or array found in output'); + + const maxTrimAttempts = 200; // bounded attempts to trim tail + for (let ci = candidates.length - 1; ci >= 0; ci--) { + let cand = candidates[ci]; + // try direct parse + try { + return JSON.parse(cand); + } catch (err) { + // if parse failed, try trimming tail progressively (but bounded) + for (let t = 0; t < maxTrimAttempts && cand.length > 2; t++) { + // remove up to t+1 chars from end + const newLen = Math.max(0, cand.length - (t + 1)); + const substr = cand.substring(0, newLen).trim(); + try { + return JSON.parse(substr); + } catch (e2) { + // continue trimming + } + } + } + } + + throw new Error('Failed to parse any JSON candidate from output'); +} + +// Generate HTML report +function generateHTMLReport(scanResult) { + const { summary, findings } = scanResult; + + return ` + + + + NutriHelp Security Scan Report + + + +
+

πŸ”’ NutriHelp Vulnerability Scanner V2.0

+

Scan Time: ${new Date().toISOString()}

+
+ +
+
+

${summary.files_scanned}

+

Files Scanned

+
+
+

${findings.length}

+

Total Issues

+
+
+

${summary.by_severity.CRITICAL || 0}

+

Critical

+
+
+

${summary.by_severity.HIGH || 0}

+

High

+
+
+ +

πŸ“‹ Detailed Findings

+ ${findings.map(finding => ` +
+

${finding.title} (${finding.severity})

+

File: ${finding.file_path}

+

Description: ${finding.description}

+

Plugin: ${finding.plugin_name}

+
+ `).join('')} + +`; +} + +module.exports = router; \ No newline at end of file diff --git a/routes/systemRoutes.js b/routes/systemRoutes.js index 9a528e2..2bca4ba 100644 --- a/routes/systemRoutes.js +++ b/routes/systemRoutes.js @@ -1,6 +1,7 @@ const express = require('express'); const router = express.Router(); const { checkFileIntegrity, generateBaseline } = require('../tools/integrity/integrityService'); +const testErrorRouter = require('./testError'); /** * @swagger @@ -65,5 +66,8 @@ router.get('/integrity-check', (req, res) => { } }); +// Mount test error router for triggering errors (used for demo/testing) +router.use('/test-error', testErrorRouter); + module.exports = router; \ No newline at end of file diff --git a/routes/testError.js b/routes/testError.js new file mode 100644 index 0000000..4010cb6 --- /dev/null +++ b/routes/testError.js @@ -0,0 +1,24 @@ +const express = require('express'); +const router = express.Router(); + +// Intentionally trigger an error to test error logging +router.post('/trigger', (req, res, next) => { + const simulate = req.body && req.body.simulate ? req.body.simulate : 'basic'; + + if (simulate === 'throw') { + // throw synchronously + throw new Error('Simulated synchronous error from /api/system/test-error/trigger'); + } + + if (simulate === 'next') { + // pass to next error handler + return next(new Error('Simulated async error via next() from /api/system/test-error/trigger')); + } + + // default: create an error after a tick (simulate async failure) + setTimeout(() => { + next(new Error('Simulated delayed error from /api/system/test-error/trigger')); + }, 10); +}); + +module.exports = router; diff --git a/server.js b/server.js index 184df51..6e4fb67 100644 --- a/server.js +++ b/server.js @@ -1,6 +1,6 @@ require("dotenv").config(); const express = require("express"); - +const { errorLogger, responseTimeLogger } = require('./middleware/errorLogger'); const FRONTEND_ORIGIN = "http://localhost:3000"; const helmet = require('helmet'); @@ -138,8 +138,13 @@ app.use(limiter); // apply globally // Swagger Docs const swaggerDocument = yaml.load("./index.yaml"); +// Remove externalDocs if present to avoid CORS issues +if (swaggerDocument && swaggerDocument.externalDocs) { + delete swaggerDocument.externalDocs; +} app.use("/api-docs", swaggerUi.serve, swaggerUi.setup(swaggerDocument)); - +// Response time monitoring +app.use(responseTimeLogger); // JSON & URL parser app.use(express.json({ limit: "50mb" })); app.use(express.urlencoded({ limit: "50mb", extended: true })); @@ -155,19 +160,26 @@ app.use("/uploads", express.static("uploads")); app.use("/api/signup", require("./routes/signup")); // Error handler +app.use(errorLogger); + +// Final error handler app.use((err, req, res, next) => { - if (err) { - res.status(400).json({ error: err.message }); - } else { - next(); - } + const status = err.status || 500; + const message = process.env.NODE_ENV === 'production' + ? 'Internal Server Error' + : err.message; + + res.status(status).json({ + success: false, + error: message, + timestamp: new Date().toISOString() + }); }); // Global error handler -app.use((err, req, res, next) => { - console.error("Unhandled error:", err); - res.status(500).json({ error: "Internal server error" }); -}); +const { uncaughtExceptionHandler, unhandledRejectionHandler } = require('./middleware/errorLogger'); +process.on('uncaughtException', uncaughtExceptionHandler); +process.on('unhandledRejection', unhandledRejectionHandler); // Start server app.listen(port, async () => { diff --git a/services/.DS_Store b/services/.DS_Store deleted file mode 100644 index 3eea6aa..0000000 Binary files a/services/.DS_Store and /dev/null differ diff --git a/services/errorLogService.js b/services/errorLogService.js new file mode 100644 index 0000000..f1ead2e --- /dev/null +++ b/services/errorLogService.js @@ -0,0 +1,229 @@ +const { createClient } = require('@supabase/supabase-js'); +const supabase = createClient(process.env.SUPABASE_URL, process.env.SUPABASE_ANON_KEY); + +class ErrorLogService { + constructor() { + this.severityLevels = { + critical: 4, + warning: 3, + info: 2, + minor: 1 + }; + } + + /** Record error logs + */ + async logError({ + error, + req = null, + res = null, + category = 'warning', + type = 'system', + additionalContext = {} + }) { + try { + const logEntry = { + error_type: type, + error_message: error.message || error.toString(), + stack_trace: error.stack, + endpoint: req?.originalUrl || req?.url, + method: req?.method, + request_body: req?.body ? JSON.stringify(this.sanitizeRequestBody(req.body)) : null, + user_id: req?.user?.userId || null, + ip_address: this.getClientIP(req), + created_at: new Date().toISOString() + }; + + const { data, error: insertError } = await supabase + .from('error_logs') + .insert([logEntry]) + .select() + .single(); + + if (insertError) { + console.error('Failed to log error:', insertError); + // Fallback logging to file or console + this.fallbackLogging(logEntry); + } + + // Real-time alerting for critical errors + if (category === 'critical') { + await this.triggerCriticalAlert(logEntry); + } + + return data; + } catch (loggingError) { + console.error('Error logging service failed:', loggingError); + this.fallbackLogging({ error, req, res, category, type }); + } + } + + /** + * Extract request context + */ + extractRequestContext(req) { + return { + request_id: req.id || req.headers['x-request-id'], + request_method: req.method, + request_url: req.originalUrl || req.url, + request_origin: req.headers.origin || req.headers.referer, + request_user_agent: req.headers['user-agent'], + request_ip_address: this.getClientIP(req), + request_headers: this.sanitizeHeaders(req.headers), + request_body: this.sanitizeRequestBody(req.body) + }; + } + + /** + * Extract user context + */ + extractUserContext(req) { + const user = req.user || {}; + return { + user_id: user.userId || user.id, + session_id: req.sessionID || req.headers['x-session-id'], + user_role: user.role + }; + } + + /** + * Get system context + */ + getSystemContext() { + const memUsage = process.memoryUsage(); + return { + server_instance: process.env.SERVER_INSTANCE || 'unknown', + node_env: process.env.NODE_ENV, + memory_usage: { + rss: memUsage.rss, + heapTotal: memUsage.heapTotal, + heapUsed: memUsage.heapUsed, + external: memUsage.external + }, + cpu_usage: process.cpuUsage ? this.getCPUUsage() : null + }; + } + + /** + * Extract response context + */ + extractResponseContext(res) { + return { + response_status: res.statusCode, + response_time_ms: res.responseTime || null + }; + } + + /** + * Get client IP + */ + getClientIP(req) { + if (!req) return null; + return req.ip || + (req.connection && req.connection.remoteAddress) || + (req.socket && req.socket.remoteAddress) || + (req.connection && req.connection.socket ? req.connection.socket.remoteAddress : null) || null; + } + + /** + * Sanitize sensitive request headers + */ + sanitizeHeaders(headers) { + if (!headers || typeof headers !== 'object') return headers; + const sanitized = { ...headers }; + const sensitiveHeaders = ['authorization', 'cookie', 'x-api-key']; + + sensitiveHeaders.forEach(header => { + // header keys may be in different cases + const key = Object.keys(sanitized).find(k => k.toLowerCase() === header); + if (key && sanitized[key]) { + sanitized[key] = '[REDACTED]'; + } + }); + + return sanitized; + } + + /** + * Sanitize sensitive request body + */ + sanitizeRequestBody(body) { + if (!body || typeof body !== 'object') return body; + + const sanitized = { ...body }; + const sensitiveFields = ['password', 'token', 'secret', 'key']; + + sensitiveFields.forEach(field => { + if (sanitized[field]) { + sanitized[field] = '[REDACTED]'; + } + }); + + return sanitized; + } + + /** + * Get CPU usage + */ + getCPUUsage() { + const startUsage = process.cpuUsage(); + setTimeout(() => { + const usage = process.cpuUsage(startUsage); + return (usage.user + usage.system) / 1000000; // Convert to seconds + }, 100); + } + + /** + * Trigger critical error alert + */ + async triggerCriticalAlert(logEntry) { + // Here you can integrate email, Slack, SMS and other alert mechanisms + console.error('🚨 CRITICAL ERROR ALERT:', { + message: logEntry.error_message, + type: logEntry.error_type, + timestamp: new Date().toISOString(), + user_id: logEntry.user_id, + url: logEntry.request_url + }); + + // You can add more alerting logic here + // await this.sendSlackAlert(logEntry); + // await this.sendEmailAlert(logEntry); + } + + /** + * Fallback logging + */ + fallbackLogging(logData) { + const timestamp = new Date().toISOString(); + console.error(`[${timestamp}] FALLBACK ERROR LOG:`, JSON.stringify(logData, null, 2)); + } + + /** + * Error classification + */ + categorizeError(error, context = {}) { + // Automatically categorize based on error type and context + if (error.message.includes('ECONNREFUSED') || + error.message.includes('database') || + error.code === 'ENOTFOUND') { + return { category: 'critical', type: 'database' }; + } + + if (error.status === 401 || error.status === 403) { + return { category: 'warning', type: 'authentication' }; + } + + if (error.status >= 400 && error.status < 500) { + return { category: 'info', type: 'validation' }; + } + + if (error.status >= 500) { + return { category: 'critical', type: 'system' }; + } + + return { category: 'warning', type: 'system' }; + } +} + +module.exports = new ErrorLogService(); diff --git a/testErrorLogging.js b/testErrorLogging.js new file mode 100644 index 0000000..4af91d9 --- /dev/null +++ b/testErrorLogging.js @@ -0,0 +1,70 @@ +// testErrorLogging.js +// Load .env: try multiple likely locations (script dir, project root, process.cwd()) +const path = require('path'); +const dotenv = require('dotenv'); + +const tryPaths = [ + path.resolve(__dirname, '.env'), + path.resolve(__dirname, '..', '.env'), + path.resolve(process.cwd(), '.env') +]; + +let loaded = false; +for (const p of tryPaths) { + try { + const result = dotenv.config({ path: p }); + if (result.parsed) { + console.log(`Loaded .env from ${p}`); + loaded = true; + break; + } + } catch (e) { + // ignore + } +} + +if (!loaded) { + console.warn('Warning: .env not found in standard locations; relying on process.env'); +} + +// Delay requiring the service until after env is (attempted) loaded to avoid early Supabase client initialization errors +const errorLogService = require('./services/errorLogService'); + +async function testErrorLogging() { + console.log('πŸ§ͺ Testing Error Logging...'); + + // Check if environment variables are loaded + if (!process.env.SUPABASE_URL) { + console.error('❌ SUPABASE_URL not found in environment variables'); + return; + } + + // Testing basic error logging + const testError = new Error('Test error logging'); + testError.code = 'TEST_ERROR'; + + try { + await errorLogService.logError({ + error: testError, + category: 'info', + type: 'system' + }); + + console.log('βœ… Basic error logging test passed'); + + // Testing critical error alerting + const criticalError = new Error('Critical test error'); + await errorLogService.logError({ + error: criticalError, + category: 'critical', + type: 'system' + }); + + console.log('βœ… Critical error logging test passed'); + + } catch (error) { + console.error('❌ Test failed:', error); + } +} + +testErrorLogging(); \ No newline at end of file