From 3ea7bf5fb389e2569bcd8b7851e3fc390503ff66 Mon Sep 17 00:00:00 2001 From: ChaohuiLi0321 Date: Fri, 5 Sep 2025 21:44:19 +1000 Subject: [PATCH 01/39] Install basic dependencies --- Vulnerability_Tool_V2/requirements.txt | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 Vulnerability_Tool_V2/requirements.txt diff --git a/Vulnerability_Tool_V2/requirements.txt b/Vulnerability_Tool_V2/requirements.txt new file mode 100644 index 0000000..69ba381 --- /dev/null +++ b/Vulnerability_Tool_V2/requirements.txt @@ -0,0 +1,14 @@ +# 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 From 60c0fd0262ec2019aa0b0f7d1ff0a4df5b9fa364 Mon Sep 17 00:00:00 2001 From: ChaohuiLi0321 Date: Fri, 5 Sep 2025 21:46:34 +1000 Subject: [PATCH 02/39] Add temporary file ignore filter settings --- .gitignore | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 8668864..a930828 100644 --- a/.gitignore +++ b/.gitignore @@ -129,4 +129,20 @@ dist .pnp.* .vscode -.idea \ No newline at end of file +.idea + +# Python virtual environments +venv/ +.env/ +__pycache__/ +*.pyc + +# macOS system files +.DS_Store + +# VS Code settings +.vscode/ + +# Logs and temp files +*.log +*.tmp From e137e6ec77e31079d00cbec4185084725dd36b2f Mon Sep 17 00:00:00 2001 From: ChaohuiLi0321 Date: Fri, 5 Sep 2025 21:56:56 +1000 Subject: [PATCH 03/39] Create the plugin package initialization file plugins/base_plugin.py and implement the plugin base class system. --- Vulnerability_Tool_V2/plugins/base_plugin.py | 166 +++++++++++++++++++ 1 file changed, 166 insertions(+) create mode 100644 Vulnerability_Tool_V2/plugins/base_plugin.py diff --git a/Vulnerability_Tool_V2/plugins/base_plugin.py b/Vulnerability_Tool_V2/plugins/base_plugin.py new file mode 100644 index 0000000..5db0c85 --- /dev/null +++ b/Vulnerability_Tool_V2/plugins/base_plugin.py @@ -0,0 +1,166 @@ +#!/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 +import logging +import os +from datetime import datetime + + +class SecurityFinding: + """Standardized security discovery objects""" + + def __init__(self, title: str, description: str, file_path: str, + line_number: Optional[int] = None, severity: str = "MEDIUM", + recommendation: Optional[str] = None): + self.title = title + self.description = description + self.file_path = file_path + self.line_number = line_number + self.severity = severity.upper() + self.recommendation = recommendation + self.timestamp = datetime.now().isoformat() + self.plugin = None # Will be set by the plugin + + def to_dict(self) -> Dict[str, Any]: + """Convert to dictionary format""" + return { + 'title': self.title, + 'description': self.description, + 'file_path': self.file_path, + 'line_number': self.line_number, + 'severity': self.severity, + 'recommendation': self.recommendation, + 'timestamp': self.timestamp, + 'plugin': self.plugin + } + + +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, + description=description, + file_path=file_path, + line_number=line_number, + severity=severity, + 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 From 1c9a181e172cdd2511b62aea7849b5c35c101cbb Mon Sep 17 00:00:00 2001 From: ChaohuiLi0321 Date: Fri, 5 Sep 2025 22:03:13 +1000 Subject: [PATCH 04/39] Create the core engine core/scanner_engine.py --- Vulnerability_Tool_V2/core/scanner_engine.py | 189 +++++++++++++++++++ 1 file changed, 189 insertions(+) create mode 100644 Vulnerability_Tool_V2/core/scanner_engine.py diff --git a/Vulnerability_Tool_V2/core/scanner_engine.py b/Vulnerability_Tool_V2/core/scanner_engine.py new file mode 100644 index 0000000..be50f95 --- /dev/null +++ b/Vulnerability_Tool_V2/core/scanner_engine.py @@ -0,0 +1,189 @@ +#!/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 + +# 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', + 'rls_missing_protection': 'plugins.rls_security.rls_missing', + # can add more plugins + } + + 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 scan_target(self, target_path: str) -> Dict[str, Any]: + """Scan target path""" + if not os.path.exists(target_path): + raise FileNotFoundError(f"Target path does not exist: {target_path}") + + self.logger.info(f"Starting security scan on: {target_path}") + + # Run all plugin scans + plugin_results = self.plugin_manager.run_all_scans(target_path) + + # Consolidate results + all_findings = [] + for plugin_name, findings in plugin_results.items(): + all_findings.extend(findings) + + # Update statistics + self.stats['total_findings'] = len(all_findings) + self.stats['files_scanned'] = self._count_scannable_files(target_path) + + # Build scan result + result = { + 'scan_info': { + 'target_path': target_path, + 'timestamp': self._get_timestamp(), + 'scanner_version': '2.0.0', + 'stats': self.stats + }, + 'findings': [f.to_dict() for f in all_findings], + 'summary': self._generate_summary(all_findings) + } + + self.logger.info(f"Scan completed. Found {len(all_findings)} issues") + return result + + 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() \ No newline at end of file From 9367023f55987286132c564ccf5fd8c33c69c3a9 Mon Sep 17 00:00:00 2001 From: ChaohuiLi0321 Date: Fri, 5 Sep 2025 22:06:38 +1000 Subject: [PATCH 05/39] Create a configuration management system config/scanner_config.yaml --- .../config/scanner_config.yaml | 132 ++++++++++++++++++ 1 file changed, 132 insertions(+) create mode 100644 Vulnerability_Tool_V2/config/scanner_config.yaml diff --git a/Vulnerability_Tool_V2/config/scanner_config.yaml b/Vulnerability_Tool_V2/config/scanner_config.yaml new file mode 100644 index 0000000..b5f9013 --- /dev/null +++ b/Vulnerability_Tool_V2/config/scanner_config.yaml @@ -0,0 +1,132 @@ +# NutriHelp Security Scanner V2.0 Configuration +scanner: + name: "NutriHelp Security Scanner V2.0" + version: "2.0.0" + description: "Specialized security scanner for NutriHelp project" + + # Scan Settings + scan_settings: + max_file_size_mb: 50 + timeout_seconds: 300 + parallel_scanning: false + + # Supported File Extensions + file_extensions: + - .js + - .ts + - .py + - .sql + - .json + - .yaml + - .yml + - .env + + # Excluded Directories + exclude_directories: + - node_modules + - .git + - __pycache__ + - venv + - .venv + - dist + - build + - uploads + - temp + +# Plugin Configuration +plugins: + # JWT Security Plugin + jwt_missing_protection: + enabled: true + severity_override: null + config: + # Public endpoints (do not require JWT protection) + public_endpoints: + - "/login" + - "/register" + - "/signup" + - "/health" + - "/docs" + - "/api-docs" + - "/public" + + # JWT Middleware Patterns + jwt_middleware_patterns: + - "authenticateToken" + - "verifyToken" + - "jwtAuth" + - "requireAuth" + - "checkJWT" + + jwt_configuration: + enabled: true + severity_override: null + config: + min_secret_length: 32 + check_weak_secrets: true + validate_expiry: true + check_algorithm: true + + # RLS Security Plugin + rls_missing_protection: + enabled: true + severity_override: null + config: + # Sensitive tables (require RLS protection) + sensitive_tables: + - "users" + - "user_profiles" + - "auth_logs" + - "user_sessions" + - "recipes" + - "meal_plans" + - "appointments" + - "medical_predictions" + - "user_feedback" + - "notifications" + + # RLS Indicators + rls_indicators: + - "auth.uid()" + - "current_user" + - "user_id" + - "auth_user" + - "rls" + - "row level security" + +# Report Settings +reports: + # General Settings + include_source_snippets: true + max_snippet_lines: 5 + include_file_paths: true + include_timestamps: true + + # Grouping Settings + group_by_severity: true + sort_by_severity: true + + # Output Formats + formats: + json: + enabled: true + indent: 2 + include_metadata: true + + html: + enabled: true + template: "default" + include_css: true + include_js: false + + text: + enabled: true + max_width: 120 + include_summary: true + +# Logging Settings +logging: + level: "INFO" # DEBUG, INFO, WARNING, ERROR + format: "%(asctime)s - %(name)s - %(levelname)s - %(message)s" + file_output: false + file_path: "logs/scanner.log" \ No newline at end of file From 714d0833f1db4e4f19aa81b92fc7ed7cfcee01cf Mon Sep 17 00:00:00 2001 From: ChaohuiLi0321 Date: Fri, 5 Sep 2025 22:07:31 +1000 Subject: [PATCH 06/39] Configuration Manager - handles loading and validation of YAML configuration files. --- Vulnerability_Tool_V2/core/config_manager.py | 123 +++++++++++++++++++ 1 file changed, 123 insertions(+) create mode 100644 Vulnerability_Tool_V2/core/config_manager.py 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 From b3fe677854845f055f57483f20513c41d8b638af Mon Sep 17 00:00:00 2001 From: ChaohuiLi0321 Date: Fri, 5 Sep 2025 22:10:54 +1000 Subject: [PATCH 07/39] NutriHelp Security Scanner V2.0 - Main Entry Point: scanner_v2.py, Modular security scanner main program. --- Vulnerability_Tool_V2/scanner_v2.py | 456 ++++++++++++++++++++++++++++ 1 file changed, 456 insertions(+) create mode 100644 Vulnerability_Tool_V2/scanner_v2.py diff --git a/Vulnerability_Tool_V2/scanner_v2.py b/Vulnerability_Tool_V2/scanner_v2.py new file mode 100644 index 0000000..8d003ab --- /dev/null +++ b/Vulnerability_Tool_V2/scanner_v2.py @@ -0,0 +1,456 @@ +#!/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 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 + + +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() + 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': + return generate_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) + + +def generate_html_report(scan_results: dict, config_manager: ConfigManager) -> str: + """Generate HTML report""" + summary = scan_results['summary'] + findings = scan_results['findings'] + scan_info = scan_results['scan_info'] + + 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 discovery + 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 + }.get(x.get('severity', 'MEDIUM'), 2)) + + for finding in sorted_findings: + severity = finding.get('severity', 'MEDIUM').lower() + recommendation = finding.get('recommendation', 'Please review this security issue and take appropriate remediation steps.') + + finding_html = f""" +
+
+
{finding['title']}
+ {finding['severity']} +
+ +
+ ๐Ÿ“ {finding['file_path']} + {f" (Line {finding['line_number']})" if finding.get('line_number') else ''} +
+ +
{finding['description']}
+ +
+ ๐Ÿ’ก Recommendation: {recommendation} +
+ + {f"
Plugin: {finding['plugin']}
" if finding.get('plugin') else ''} +
+ """ + findings_html += finding_html + + # Format timestamp + from datetime import datetime + try: + timestamp_obj = datetime.fromisoformat(scan_info['timestamp'].replace('Z', '+00:00')) + formatted_timestamp = timestamp_obj.strftime('%Y-%m-%d %H:%M:%S') + except: + formatted_timestamp = scan_info['timestamp'] + + return html_template.format( + timestamp=formatted_timestamp, + target_path=scan_info['target_path'], + scanner_version=scan_info['scanner_version'], + critical_count=summary['by_severity'].get('CRITICAL', 0), + high_count=summary['by_severity'].get('HIGH', 0), + medium_count=summary['by_severity'].get('MEDIUM', 0), + low_count=summary['by_severity'].get('LOW', 0), + files_scanned=scan_info['stats']['files_scanned'], + plugins_used=scan_info['stats']['plugins_loaded'], + total_findings=summary['total'], + findings_html=findings_html + ) + + +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 From f5fde8d0ad77d4792323036c3cb5add84a0c583f Mon Sep 17 00:00:00 2001 From: ChaohuiLi0321 Date: Fri, 5 Sep 2025 22:37:17 +1000 Subject: [PATCH 08/39] =?UTF-8?q?Phase=201=20Quick=20verification=20script?= =?UTF-8?q?=E2=80=94=E2=80=94Verify=20that=20the=20modular=20infrastructur?= =?UTF-8?q?e=20is=20built=20correctly.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Vulnerability_Tool_V2/verify_phase1.py | 250 +++++++++++++++++++++++++ 1 file changed, 250 insertions(+) create mode 100644 Vulnerability_Tool_V2/verify_phase1.py 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 From fe7e9c94230c21a7a918a105421a6ad38f889710 Mon Sep 17 00:00:00 2001 From: ChaohuiLi0321 Date: Fri, 5 Sep 2025 22:59:37 +1000 Subject: [PATCH 09/39] Create a file named test_basic_functionality.py to test the basic functionality of the security scanning tool named Vulnerability_Tool_V2. --- .../tests/test_basic_functionality.py | 140 ++++++++++++++++++ 1 file changed, 140 insertions(+) create mode 100644 Vulnerability_Tool_V2/tests/test_basic_functionality.py 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 From 7a16146cf5b68351bcd8156ac912ec8815a11c64 Mon Sep 17 00:00:00 2001 From: ChaohuiLi0321 Date: Fri, 5 Sep 2025 23:50:26 +1000 Subject: [PATCH 10/39] Create a JWT missing protection plug-in plugins/jwt_security/jwt_missing.py --- .../plugins/jwt_security/jwt_missing.py | 266 ++++++++++++++++++ 1 file changed, 266 insertions(+) create mode 100644 Vulnerability_Tool_V2/plugins/jwt_security/jwt_missing.py 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..16e42b1 --- /dev/null +++ b/Vulnerability_Tool_V2/plugins/jwt_security/jwt_missing.py @@ -0,0 +1,266 @@ +#!/usr/bin/env python3 +""" +JWT Missing Protection Plugin - Updated for NutriHelp's actual architecture +Implementing a custom detection plugin based on existing JWT architecture +""" + +import os +import re +from typing import List, Dict, Any +from ..base_plugin import BaseSecurityPlugin, SecurityFinding + + +class JWTMissingProtectionPlugin(BaseSecurityPlugin): + """Detects API endpoints missing JWT protection - Optimized for NutriHelp's actual architecture""" + + def get_plugin_info(self) -> Dict[str, str]: + return { + 'name': 'JWT Missing Protection Detector', + 'version': '2.0.1', + 'description': 'Detects API endpoints missing JWT authentication middleware (NutriHelp optimized)', + 'author': 'NutriHelp Security Team' + } + + def get_severity_level(self) -> str: + return "HIGH" + + def scan(self, target_path: str) -> List[SecurityFinding]: + """Scan for missing JWT protection issues in target paths""" + self.clear_findings() + + # Scan routes directory + routes_path = os.path.join(target_path, 'routes') + + if not os.path.exists(routes_path): + self.logger.warning(f"Routes directory not found: {routes_path}") + return self.findings + + self.logger.info(f"Scanning routes directory: {routes_path}") + + # Traverse all route files + for root, dirs, files in os.walk(routes_path): + for file in files: + if file.endswith('.js'): + file_path = os.path.join(root, file) + self._analyze_route_file(file_path, target_path) + + self.logger.info(f"JWT Missing Protection scan found {len(self.findings)} issues") + return self.findings + + def _analyze_route_file(self, file_path: str, base_path: str): + """Analyze a single route file - Based on existing route structure""" + try: + content = self.read_file_safe(file_path) + if not content: + return + + lines = content.split('\n') + relative_path = self.get_relative_path(file_path, base_path) + + # Based on existing code, detect different route definition patterns + route_patterns = [ + # Express router ( auth.js, recipe.js ) + r'router\.(get|post|put|delete|patch)\s*\(\s*[\'"`]([^\'"`]+)[\'"`]', + # App.use ( index.js ) + r'app\.use\s*\(\s*[\'"`]([^\'"`]+)[\'"`]', + # Controller direct call + r'router\.(get|post|put|delete|patch)\s*\(\s*[\'"`]([^\'"`]+)[\'"`]\s*,\s*[^,]*controller' + ] + + for i, line in enumerate(lines, 1): + self._check_line_for_unprotected_routes( + line, lines, i, relative_path, route_patterns, os.path.basename(file_path) + ) + + except Exception as e: + self.logger.error(f"Error analyzing route file {file_path}: {e}") + + def _check_line_for_unprotected_routes(self, line: str, all_lines: List[str], + line_number: int, file_path: str, + route_patterns: List[str], filename: str): + """Check for unprotected routes in a single line of code - based on existing middleware names""" + + 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() if match.group(1) else 'USE' + endpoint = match.group(2) + + # Handling different endpoint formats + if not endpoint.startswith('/'): + endpoint = '/' + endpoint + else: + continue + + # Skip explicitly public endpoints + if self._is_public_endpoint(endpoint, filename): + continue + + # Check for JWT protection - using existing middleware names + if not self._has_jwt_protection(line, all_lines, line_number): + severity = self._determine_severity(endpoint, method, filename) + recommendation = self._get_recommendation(endpoint, method) + + self.add_finding( + title=f"Missing JWT Protection: {method} {endpoint}", + description=f"API endpoint {method} {endpoint} in {filename} lacks JWT authentication middleware. " + f"Based on your current architecture, this should use authenticateToken middleware.", + file_path=file_path, + line_number=line_number, + severity=severity, + recommendation=recommendation + ) + + def _is_public_endpoint(self, endpoint: str, filename: str) -> bool: + """Check if an endpoint should be public - based on existing route structure""" + + # Based on filename, determine public endpoints + if filename in ['login.js', 'signup.js']: + return True + + # Explicit public endpoints (based on existing auth.js) + public_endpoints = [ + '/register', '/login', '/health', '/api-docs', '/docs', + '/public', '/static', '/uploads', '/log-login', '/log-login-attempt' + ] + + endpoint_lower = endpoint.lower() + + # Exact match + if endpoint_lower in [ep.lower() for ep in public_endpoints]: + return True + + # Prefix match + public_prefixes = ['/public/', '/static/', '/docs/', '/uploads/', '/api-docs/'] + if any(endpoint_lower.startswith(prefix) for prefix in public_prefixes): + return True + + # Health check endpoints + if any(pattern in endpoint_lower for pattern in ['/health', '/ping', '/status']): + return True + + return False + + def _has_jwt_protection(self, current_line: str, all_lines: List[str], + line_number: int) -> bool: + """Check if a route has JWT protection - based on existing middleware""" + + # Existing JWT middleware names + jwt_patterns = [ + 'authenticateToken', + 'optionalAuth', + 'verifyToken', + 'jwtAuth', + 'requireAuth' + ] + + # Method 1: Check current line + for pattern in jwt_patterns: + if re.search(rf'\b{pattern}\b', current_line, re.IGNORECASE): + return True + + # Method 2: Check imports and usage + # Check if imported from authenticateToken module + if "require('../middleware/authenticateToken')" in current_line or \ + "require('./middleware/authenticateToken')" in current_line: + + # Check if the imported middleware is used in subsequent lines + search_range = 10 + start_line = max(0, line_number - 1) + end_line = min(len(all_lines), line_number + search_range) + + context = ' '.join(all_lines[start_line:end_line]) + for pattern in jwt_patterns: + if pattern in context: + return True + + # Method 3: Check destructured import { authenticateToken } + destructure_pattern = r'\{\s*authenticateToken\s*\}' + if re.search(destructure_pattern, current_line): + return True + + # Method 4: Check controller routes + if 'controller' in current_line.lower() and any(word in current_line.lower() + for word in ['auth', 'protected', 'secure']): + return True + + return False + + def _determine_severity(self, endpoint: str, method: str, filename: str) -> str: + """Determine severity by endpoint and method - based on existing logic""" + + endpoint_lower = endpoint.lower() + + # Based on existing route files determine critical business + critical_files = ['userprofile.js', 'userpassword.js', 'account.js', 'medicalPrediction.js'] + high_risk_files = ['recipe.js', 'mealplan.js', 'upload.js', 'notifications.js'] + + # Critical endpoint patterns + critical_patterns = [ + '/admin', '/delete', '/remove', '/password', '/profile', + '/medical', '/prediction', '/account', '/payment' + ] + + high_risk_patterns = [ + '/user', '/recipe', '/mealplan', '/upload', '/notification', + '/feedback', '/preference', '/appointment' + ] + + # File-level determination + if filename in critical_files: + return "CRITICAL" + elif filename in high_risk_files and method in ['POST', 'PUT', 'DELETE', 'PATCH']: + return "HIGH" + + # Endpoint pattern matching + if any(pattern in endpoint_lower for pattern in critical_patterns): + return "CRITICAL" + elif any(pattern in endpoint_lower for pattern in high_risk_patterns): + return "HIGH" + elif method in ['POST', 'PUT', 'DELETE', 'PATCH']: + return "HIGH" + else: + return "MEDIUM" + + def _get_recommendation(self, endpoint: str, method: str) -> str: + """Get fix suggestions based on existing architecture""" + return f""" +To fix this JWT protection issue, add the authenticateToken middleware: + +1. Import the middleware (if not already imported): + const {{ authenticateToken }} = require('../middleware/authenticateToken'); + +2. Add middleware to the route: + router.{method.lower()}('{endpoint}', authenticateToken, (req, res) => {{ ... }}); + + Or if using a controller: + router.{method.lower()}('{endpoint}', authenticateToken, controllerFunction); + +3. For optional authentication, you can use: + const {{ optionalAuth }} = require('../middleware/authenticateToken'); + router.{method.lower()}('{endpoint}', optionalAuth, (req, res) => {{ ... }}); + +4. Your current JWT setup uses: + - Access tokens (15 minutes expiry) + - Refresh tokens (7 days expiry) + - Proper error handling with specific error codes + +Example based on your auth.js pattern: +router.{method.lower()}('{endpoint}', authenticateToken, controllerFunction); + """.strip() + + +# Test function +def test_plugin(): + """Test plugin basic functionality""" + plugin = JWTMissingProtectionPlugin() + + print("Plugin Info:", plugin.get_plugin_info()) + print("Severity Level:", plugin.get_severity_level()) + print("โœ… Updated JWT Missing Protection Plugin initialized successfully") + + +if __name__ == '__main__': + test_plugin() \ No newline at end of file From d0a8f7ffae5d22747773111daca3b273ec350921 Mon Sep 17 00:00:00 2001 From: ChaohuiLi0321 Date: Fri, 5 Sep 2025 23:50:42 +1000 Subject: [PATCH 11/39] Create a JWT configuration verification plug-in plugins/jwt_security/jwt_config.py --- .../plugins/jwt_security/jwt_config.py | 330 ++++++++++++++++++ 1 file changed, 330 insertions(+) create mode 100644 Vulnerability_Tool_V2/plugins/jwt_security/jwt_config.py 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..9c9a582 --- /dev/null +++ b/Vulnerability_Tool_V2/plugins/jwt_security/jwt_config.py @@ -0,0 +1,330 @@ +#!/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]: + """Scan for JWT configuration issues""" + self.clear_findings() + + # Check environment variable files + self._check_env_files(target_path) + + # Check JWT implementation consistency + self._check_jwt_implementation_consistency(target_path) + + # Check auth service configuration + self._check_auth_service_config(target_path) + + # Check middleware configuration + self._check_middleware_configuration(target_path) + + self.logger.info(f"JWT Configuration scan found {len(self.findings)} issues") + return self.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}") + + +# 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 From 2b66c52dbbc30c32ed0136df334ab422482e3e7e Mon Sep 17 00:00:00 2001 From: ChaohuiLi0321 Date: Fri, 5 Sep 2025 23:51:18 +1000 Subject: [PATCH 12/39] Generate HTML report, view HTML report --- .../nutrihelp_jwt_security_report.html | 1263 +++++++++++++++++ 1 file changed, 1263 insertions(+) create mode 100644 Vulnerability_Tool_V2/nutrihelp_jwt_security_report.html diff --git a/Vulnerability_Tool_V2/nutrihelp_jwt_security_report.html b/Vulnerability_Tool_V2/nutrihelp_jwt_security_report.html new file mode 100644 index 0000000..670d6c7 --- /dev/null +++ b/Vulnerability_Tool_V2/nutrihelp_jwt_security_report.html @@ -0,0 +1,1263 @@ + + + + + + + NutriHelp Security Scanner V2.0 Report + + + +
+
+

๐Ÿ”’ NutriHelp Security Scanner V2.0

+
+

Scan time: 2025-09-05 23:44:45

+

Target path: ../

+

Scanner version: 2.0.0

+
+
+ +
+
+

2

+

Critical Issues

+
+
+

16

+

High Severity

+
+
+

10

+

Medium Severity

+
+
+

1

+

Low Severity

+
+
+ +
+
+
+
840
+
Files Scanned
+
+
+
2
+
Plugins Used
+
+
+
29
+
Total Issues
+
+
+ +

๐Ÿ” Detailed Findings

+
+
+
Missing JWT Protection: PUT /update-by-identifier
+ CRITICAL +
+ +
+ ๐Ÿ“ routes/userprofile.js + (Line 14) +
+ +
API endpoint PUT /update-by-identifier in userprofile.js lacks JWT authentication middleware. Based on your current architecture, this should use authenticateToken middleware.
+ +
+ ๐Ÿ’ก Recommendation: To fix this JWT protection issue, add the authenticateToken middleware: + +1. Import the middleware (if not already imported): + const { authenticateToken } = require('../middleware/authenticateToken'); + +2. Add middleware to the route: + router.put('/update-by-identifier', authenticateToken, (req, res) => { ... }); + + Or if using a controller: + router.put('/update-by-identifier', authenticateToken, controllerFunction); + +3. For optional authentication, you can use: + const { optionalAuth } = require('../middleware/authenticateToken'); + router.put('/update-by-identifier', optionalAuth, (req, res) => { ... }); + +4. Your current JWT setup uses: + - Access tokens (15 minutes expiry) + - Refresh tokens (7 days expiry) + - Proper error handling with specific error codes + +Example based on your auth.js pattern: +router.put('/update-by-identifier', authenticateToken, controllerFunction); +
+ +
Plugin: JWTMissingProtectionPlugin
+
+ +
+
+
Missing JWT Protection: PUT /update-by-identifier
+ CRITICAL +
+ +
+ ๐Ÿ“ routes/userprofile.js + (Line 14) +
+ +
API endpoint PUT /update-by-identifier in userprofile.js lacks JWT authentication middleware. Based on your current architecture, this should use authenticateToken middleware.
+ +
+ ๐Ÿ’ก Recommendation: To fix this JWT protection issue, add the authenticateToken middleware: + +1. Import the middleware (if not already imported): + const { authenticateToken } = require('../middleware/authenticateToken'); + +2. Add middleware to the route: + router.put('/update-by-identifier', authenticateToken, (req, res) => { ... }); + + Or if using a controller: + router.put('/update-by-identifier', authenticateToken, controllerFunction); + +3. For optional authentication, you can use: + const { optionalAuth } = require('../middleware/authenticateToken'); + router.put('/update-by-identifier', optionalAuth, (req, res) => { ... }); + +4. Your current JWT setup uses: + - Access tokens (15 minutes expiry) + - Refresh tokens (7 days expiry) + - Proper error handling with specific error codes + +Example based on your auth.js pattern: +router.put('/update-by-identifier', authenticateToken, controllerFunction); +
+ +
Plugin: JWTMissingProtectionPlugin
+
+ +
+
+
Missing JWT Protection: POST /
+ HIGH +
+ +
+ ๐Ÿ“ routes/imageClassification.js + (Line 19) +
+ +
API endpoint POST / in imageClassification.js lacks JWT authentication middleware. Based on your current architecture, this should use authenticateToken middleware.
+ +
+ ๐Ÿ’ก Recommendation: To fix this JWT protection issue, add the authenticateToken middleware: + +1. Import the middleware (if not already imported): + const { authenticateToken } = require('../middleware/authenticateToken'); + +2. Add middleware to the route: + router.post('/', authenticateToken, (req, res) => { ... }); + + Or if using a controller: + router.post('/', authenticateToken, controllerFunction); + +3. For optional authentication, you can use: + const { optionalAuth } = require('../middleware/authenticateToken'); + router.post('/', optionalAuth, (req, res) => { ... }); + +4. Your current JWT setup uses: + - Access tokens (15 minutes expiry) + - Refresh tokens (7 days expiry) + - Proper error handling with specific error codes + +Example based on your auth.js pattern: +router.post('/', authenticateToken, controllerFunction); +
+ +
Plugin: JWTMissingProtectionPlugin
+
+ +
+
+
Missing JWT Protection: POST /
+ HIGH +
+ +
+ ๐Ÿ“ routes/upload.js + (Line 5) +
+ +
API endpoint POST / in upload.js lacks JWT authentication middleware. Based on your current architecture, this should use authenticateToken middleware.
+ +
+ ๐Ÿ’ก Recommendation: To fix this JWT protection issue, add the authenticateToken middleware: + +1. Import the middleware (if not already imported): + const { authenticateToken } = require('../middleware/authenticateToken'); + +2. Add middleware to the route: + router.post('/', authenticateToken, (req, res) => { ... }); + + Or if using a controller: + router.post('/', authenticateToken, controllerFunction); + +3. For optional authentication, you can use: + const { optionalAuth } = require('../middleware/authenticateToken'); + router.post('/', optionalAuth, (req, res) => { ... }); + +4. Your current JWT setup uses: + - Access tokens (15 minutes expiry) + - Refresh tokens (7 days expiry) + - Proper error handling with specific error codes + +Example based on your auth.js pattern: +router.post('/', authenticateToken, controllerFunction); +
+ +
Plugin: JWTMissingProtectionPlugin
+
+ +
+
+
Missing JWT Protection: POST /
+ HIGH +
+ +
+ ๐Ÿ“ routes/upload.js + (Line 5) +
+ +
API endpoint POST / in upload.js lacks JWT authentication middleware. Based on your current architecture, this should use authenticateToken middleware.
+ +
+ ๐Ÿ’ก Recommendation: To fix this JWT protection issue, add the authenticateToken middleware: + +1. Import the middleware (if not already imported): + const { authenticateToken } = require('../middleware/authenticateToken'); + +2. Add middleware to the route: + router.post('/', authenticateToken, (req, res) => { ... }); + + Or if using a controller: + router.post('/', authenticateToken, controllerFunction); + +3. For optional authentication, you can use: + const { optionalAuth } = require('../middleware/authenticateToken'); + router.post('/', optionalAuth, (req, res) => { ... }); + +4. Your current JWT setup uses: + - Access tokens (15 minutes expiry) + - Refresh tokens (7 days expiry) + - Proper error handling with specific error codes + +Example based on your auth.js pattern: +router.post('/', authenticateToken, controllerFunction); +
+ +
Plugin: JWTMissingProtectionPlugin
+
+ +
+
+
Missing JWT Protection: POST /
+ HIGH +
+ +
+ ๐Ÿ“ routes/waterIntake.js + (Line 5) +
+ +
API endpoint POST / in waterIntake.js lacks JWT authentication middleware. Based on your current architecture, this should use authenticateToken middleware.
+ +
+ ๐Ÿ’ก Recommendation: To fix this JWT protection issue, add the authenticateToken middleware: + +1. Import the middleware (if not already imported): + const { authenticateToken } = require('../middleware/authenticateToken'); + +2. Add middleware to the route: + router.post('/', authenticateToken, (req, res) => { ... }); + + Or if using a controller: + router.post('/', authenticateToken, controllerFunction); + +3. For optional authentication, you can use: + const { optionalAuth } = require('../middleware/authenticateToken'); + router.post('/', optionalAuth, (req, res) => { ... }); + +4. Your current JWT setup uses: + - Access tokens (15 minutes expiry) + - Refresh tokens (7 days expiry) + - Proper error handling with specific error codes + +Example based on your auth.js pattern: +router.post('/', authenticateToken, controllerFunction); +
+ +
Plugin: JWTMissingProtectionPlugin
+
+ +
+
+
Missing JWT Protection: POST /createRecipe
+ HIGH +
+ +
+ ๐Ÿ“ routes/recipe.js + (Line 8) +
+ +
API endpoint POST /createRecipe in recipe.js lacks JWT authentication middleware. Based on your current architecture, this should use authenticateToken middleware.
+ +
+ ๐Ÿ’ก Recommendation: To fix this JWT protection issue, add the authenticateToken middleware: + +1. Import the middleware (if not already imported): + const { authenticateToken } = require('../middleware/authenticateToken'); + +2. Add middleware to the route: + router.post('/createRecipe', authenticateToken, (req, res) => { ... }); + + Or if using a controller: + router.post('/createRecipe', authenticateToken, controllerFunction); + +3. For optional authentication, you can use: + const { optionalAuth } = require('../middleware/authenticateToken'); + router.post('/createRecipe', optionalAuth, (req, res) => { ... }); + +4. Your current JWT setup uses: + - Access tokens (15 minutes expiry) + - Refresh tokens (7 days expiry) + - Proper error handling with specific error codes + +Example based on your auth.js pattern: +router.post('/createRecipe', authenticateToken, controllerFunction); +
+ +
Plugin: JWTMissingProtectionPlugin
+
+ +
+
+
Missing JWT Protection: POST /
+ HIGH +
+ +
+ ๐Ÿ“ routes/recipe.js + (Line 10) +
+ +
API endpoint POST / in recipe.js lacks JWT authentication middleware. Based on your current architecture, this should use authenticateToken middleware.
+ +
+ ๐Ÿ’ก Recommendation: To fix this JWT protection issue, add the authenticateToken middleware: + +1. Import the middleware (if not already imported): + const { authenticateToken } = require('../middleware/authenticateToken'); + +2. Add middleware to the route: + router.post('/', authenticateToken, (req, res) => { ... }); + + Or if using a controller: + router.post('/', authenticateToken, controllerFunction); + +3. For optional authentication, you can use: + const { optionalAuth } = require('../middleware/authenticateToken'); + router.post('/', optionalAuth, (req, res) => { ... }); + +4. Your current JWT setup uses: + - Access tokens (15 minutes expiry) + - Refresh tokens (7 days expiry) + - Proper error handling with specific error codes + +Example based on your auth.js pattern: +router.post('/', authenticateToken, controllerFunction); +
+ +
Plugin: JWTMissingProtectionPlugin
+
+ +
+
+
Missing JWT Protection: POST /
+ HIGH +
+ +
+ ๐Ÿ“ routes/recipe.js + (Line 10) +
+ +
API endpoint POST / in recipe.js lacks JWT authentication middleware. Based on your current architecture, this should use authenticateToken middleware.
+ +
+ ๐Ÿ’ก Recommendation: To fix this JWT protection issue, add the authenticateToken middleware: + +1. Import the middleware (if not already imported): + const { authenticateToken } = require('../middleware/authenticateToken'); + +2. Add middleware to the route: + router.post('/', authenticateToken, (req, res) => { ... }); + + Or if using a controller: + router.post('/', authenticateToken, controllerFunction); + +3. For optional authentication, you can use: + const { optionalAuth } = require('../middleware/authenticateToken'); + router.post('/', optionalAuth, (req, res) => { ... }); + +4. Your current JWT setup uses: + - Access tokens (15 minutes expiry) + - Refresh tokens (7 days expiry) + - Proper error handling with specific error codes + +Example based on your auth.js pattern: +router.post('/', authenticateToken, controllerFunction); +
+ +
Plugin: JWTMissingProtectionPlugin
+
+ +
+
+
Missing JWT Protection: DELETE /
+ HIGH +
+ +
+ ๐Ÿ“ routes/recipe.js + (Line 11) +
+ +
API endpoint DELETE / in recipe.js lacks JWT authentication middleware. Based on your current architecture, this should use authenticateToken middleware.
+ +
+ ๐Ÿ’ก Recommendation: To fix this JWT protection issue, add the authenticateToken middleware: + +1. Import the middleware (if not already imported): + const { authenticateToken } = require('../middleware/authenticateToken'); + +2. Add middleware to the route: + router.delete('/', authenticateToken, (req, res) => { ... }); + + Or if using a controller: + router.delete('/', authenticateToken, controllerFunction); + +3. For optional authentication, you can use: + const { optionalAuth } = require('../middleware/authenticateToken'); + router.delete('/', optionalAuth, (req, res) => { ... }); + +4. Your current JWT setup uses: + - Access tokens (15 minutes expiry) + - Refresh tokens (7 days expiry) + - Proper error handling with specific error codes + +Example based on your auth.js pattern: +router.delete('/', authenticateToken, controllerFunction); +
+ +
Plugin: JWTMissingProtectionPlugin
+
+ +
+
+
Missing JWT Protection: DELETE /
+ HIGH +
+ +
+ ๐Ÿ“ routes/recipe.js + (Line 11) +
+ +
API endpoint DELETE / in recipe.js lacks JWT authentication middleware. Based on your current architecture, this should use authenticateToken middleware.
+ +
+ ๐Ÿ’ก Recommendation: To fix this JWT protection issue, add the authenticateToken middleware: + +1. Import the middleware (if not already imported): + const { authenticateToken } = require('../middleware/authenticateToken'); + +2. Add middleware to the route: + router.delete('/', authenticateToken, (req, res) => { ... }); + + Or if using a controller: + router.delete('/', authenticateToken, controllerFunction); + +3. For optional authentication, you can use: + const { optionalAuth } = require('../middleware/authenticateToken'); + router.delete('/', optionalAuth, (req, res) => { ... }); + +4. Your current JWT setup uses: + - Access tokens (15 minutes expiry) + - Refresh tokens (7 days expiry) + - Proper error handling with specific error codes + +Example based on your auth.js pattern: +router.delete('/', authenticateToken, controllerFunction); +
+ +
Plugin: JWTMissingProtectionPlugin
+
+ +
+
+
Missing JWT Protection: POST /classify
+ HIGH +
+ +
+ ๐Ÿ“ routes/routes.js + (Line 32) +
+ +
API endpoint POST /classify in routes.js lacks JWT authentication middleware. Based on your current architecture, this should use authenticateToken middleware.
+ +
+ ๐Ÿ’ก Recommendation: To fix this JWT protection issue, add the authenticateToken middleware: + +1. Import the middleware (if not already imported): + const { authenticateToken } = require('../middleware/authenticateToken'); + +2. Add middleware to the route: + router.post('/classify', authenticateToken, (req, res) => { ... }); + + Or if using a controller: + router.post('/classify', authenticateToken, controllerFunction); + +3. For optional authentication, you can use: + const { optionalAuth } = require('../middleware/authenticateToken'); + router.post('/classify', optionalAuth, (req, res) => { ... }); + +4. Your current JWT setup uses: + - Access tokens (15 minutes expiry) + - Refresh tokens (7 days expiry) + - Proper error handling with specific error codes + +Example based on your auth.js pattern: +router.post('/classify', authenticateToken, controllerFunction); +
+ +
Plugin: JWTMissingProtectionPlugin
+
+ +
+
+
Missing JWT Protection: POST /
+ HIGH +
+ +
+ ๐Ÿ“ routes/userfeedback.js + (Line 8) +
+ +
API endpoint POST / in userfeedback.js lacks JWT authentication middleware. Based on your current architecture, this should use authenticateToken middleware.
+ +
+ ๐Ÿ’ก Recommendation: To fix this JWT protection issue, add the authenticateToken middleware: + +1. Import the middleware (if not already imported): + const { authenticateToken } = require('../middleware/authenticateToken'); + +2. Add middleware to the route: + router.post('/', authenticateToken, (req, res) => { ... }); + + Or if using a controller: + router.post('/', authenticateToken, controllerFunction); + +3. For optional authentication, you can use: + const { optionalAuth } = require('../middleware/authenticateToken'); + router.post('/', optionalAuth, (req, res) => { ... }); + +4. Your current JWT setup uses: + - Access tokens (15 minutes expiry) + - Refresh tokens (7 days expiry) + - Proper error handling with specific error codes + +Example based on your auth.js pattern: +router.post('/', authenticateToken, controllerFunction); +
+ +
Plugin: JWTMissingProtectionPlugin
+
+ +
+
+
Missing JWT Protection: POST /
+ HIGH +
+ +
+ ๐Ÿ“ routes/healthNews.js + (Line 156) +
+ +
API endpoint POST / in healthNews.js lacks JWT authentication middleware. Based on your current architecture, this should use authenticateToken middleware.
+ +
+ ๐Ÿ’ก Recommendation: To fix this JWT protection issue, add the authenticateToken middleware: + +1. Import the middleware (if not already imported): + const { authenticateToken } = require('../middleware/authenticateToken'); + +2. Add middleware to the route: + router.post('/', authenticateToken, (req, res) => { ... }); + + Or if using a controller: + router.post('/', authenticateToken, controllerFunction); + +3. For optional authentication, you can use: + const { optionalAuth } = require('../middleware/authenticateToken'); + router.post('/', optionalAuth, (req, res) => { ... }); + +4. Your current JWT setup uses: + - Access tokens (15 minutes expiry) + - Refresh tokens (7 days expiry) + - Proper error handling with specific error codes + +Example based on your auth.js pattern: +router.post('/', authenticateToken, controllerFunction); +
+ +
Plugin: JWTMissingProtectionPlugin
+
+ +
+
+
Missing JWT Protection: PUT /
+ HIGH +
+ +
+ ๐Ÿ“ routes/healthNews.js + (Line 214) +
+ +
API endpoint PUT / in healthNews.js lacks JWT authentication middleware. Based on your current architecture, this should use authenticateToken middleware.
+ +
+ ๐Ÿ’ก Recommendation: To fix this JWT protection issue, add the authenticateToken middleware: + +1. Import the middleware (if not already imported): + const { authenticateToken } = require('../middleware/authenticateToken'); + +2. Add middleware to the route: + router.put('/', authenticateToken, (req, res) => { ... }); + + Or if using a controller: + router.put('/', authenticateToken, controllerFunction); + +3. For optional authentication, you can use: + const { optionalAuth } = require('../middleware/authenticateToken'); + router.put('/', optionalAuth, (req, res) => { ... }); + +4. Your current JWT setup uses: + - Access tokens (15 minutes expiry) + - Refresh tokens (7 days expiry) + - Proper error handling with specific error codes + +Example based on your auth.js pattern: +router.put('/', authenticateToken, controllerFunction); +
+ +
Plugin: JWTMissingProtectionPlugin
+
+ +
+
+
Missing JWT Protection: DELETE /
+ HIGH +
+ +
+ ๐Ÿ“ routes/healthNews.js + (Line 238) +
+ +
API endpoint DELETE / in healthNews.js lacks JWT authentication middleware. Based on your current architecture, this should use authenticateToken middleware.
+ +
+ ๐Ÿ’ก Recommendation: To fix this JWT protection issue, add the authenticateToken middleware: + +1. Import the middleware (if not already imported): + const { authenticateToken } = require('../middleware/authenticateToken'); + +2. Add middleware to the route: + router.delete('/', authenticateToken, (req, res) => { ... }); + + Or if using a controller: + router.delete('/', authenticateToken, controllerFunction); + +3. For optional authentication, you can use: + const { optionalAuth } = require('../middleware/authenticateToken'); + router.delete('/', optionalAuth, (req, res) => { ... }); + +4. Your current JWT setup uses: + - Access tokens (15 minutes expiry) + - Refresh tokens (7 days expiry) + - Proper error handling with specific error codes + +Example based on your auth.js pattern: +router.delete('/', authenticateToken, controllerFunction); +
+ +
Plugin: JWTMissingProtectionPlugin
+
+ +
+
+
Missing JWT Protection: POST /generate-baseline
+ HIGH +
+ +
+ ๐Ÿ“ routes/systemRoutes.js + (Line 50) +
+ +
API endpoint POST /generate-baseline in systemRoutes.js lacks JWT authentication middleware. Based on your current architecture, this should use authenticateToken middleware.
+ +
+ ๐Ÿ’ก Recommendation: To fix this JWT protection issue, add the authenticateToken middleware: + +1. Import the middleware (if not already imported): + const { authenticateToken } = require('../middleware/authenticateToken'); + +2. Add middleware to the route: + router.post('/generate-baseline', authenticateToken, (req, res) => { ... }); + + Or if using a controller: + router.post('/generate-baseline', authenticateToken, controllerFunction); + +3. For optional authentication, you can use: + const { optionalAuth } = require('../middleware/authenticateToken'); + router.post('/generate-baseline', optionalAuth, (req, res) => { ... }); + +4. Your current JWT setup uses: + - Access tokens (15 minutes expiry) + - Refresh tokens (7 days expiry) + - Proper error handling with specific error codes + +Example based on your auth.js pattern: +router.post('/generate-baseline', authenticateToken, controllerFunction); +
+ +
Plugin: JWTMissingProtectionPlugin
+
+ +
+
+
Missing JWT Protection: POST /
+ HIGH +
+ +
+ ๐Ÿ“ routes/contactus.js + (Line 14) +
+ +
API endpoint POST / in contactus.js lacks JWT authentication middleware. Based on your current architecture, this should use authenticateToken middleware.
+ +
+ ๐Ÿ’ก Recommendation: To fix this JWT protection issue, add the authenticateToken middleware: + +1. Import the middleware (if not already imported): + const { authenticateToken } = require('../middleware/authenticateToken'); + +2. Add middleware to the route: + router.post('/', authenticateToken, (req, res) => { ... }); + + Or if using a controller: + router.post('/', authenticateToken, controllerFunction); + +3. For optional authentication, you can use: + const { optionalAuth } = require('../middleware/authenticateToken'); + router.post('/', optionalAuth, (req, res) => { ... }); + +4. Your current JWT setup uses: + - Access tokens (15 minutes expiry) + - Refresh tokens (7 days expiry) + - Proper error handling with specific error codes + +Example based on your auth.js pattern: +router.post('/', authenticateToken, controllerFunction); +
+ +
Plugin: JWTMissingProtectionPlugin
+
+ +
+
+
Missing JWT Protection: GET /
+ MEDIUM +
+ +
+ ๐Ÿ“ routes/recipeNutritionlog.js + (Line 27) +
+ +
API endpoint GET / in recipeNutritionlog.js lacks JWT authentication middleware. Based on your current architecture, this should use authenticateToken middleware.
+ +
+ ๐Ÿ’ก Recommendation: To fix this JWT protection issue, add the authenticateToken middleware: + +1. Import the middleware (if not already imported): + const { authenticateToken } = require('../middleware/authenticateToken'); + +2. Add middleware to the route: + router.get('/', authenticateToken, (req, res) => { ... }); + + Or if using a controller: + router.get('/', authenticateToken, controllerFunction); + +3. For optional authentication, you can use: + const { optionalAuth } = require('../middleware/authenticateToken'); + router.get('/', optionalAuth, (req, res) => { ... }); + +4. Your current JWT setup uses: + - Access tokens (15 minutes expiry) + - Refresh tokens (7 days expiry) + - Proper error handling with specific error codes + +Example based on your auth.js pattern: +router.get('/', authenticateToken, controllerFunction); +
+ +
Plugin: JWTMissingProtectionPlugin
+
+ +
+
+
Missing JWT Protection: GET /
+ MEDIUM +
+ +
+ ๐Ÿ“ routes/healthNews.js + (Line 44) +
+ +
API endpoint GET / in healthNews.js lacks JWT authentication middleware. Based on your current architecture, this should use authenticateToken middleware.
+ +
+ ๐Ÿ’ก Recommendation: To fix this JWT protection issue, add the authenticateToken middleware: + +1. Import the middleware (if not already imported): + const { authenticateToken } = require('../middleware/authenticateToken'); + +2. Add middleware to the route: + router.get('/', authenticateToken, (req, res) => { ... }); + + Or if using a controller: + router.get('/', authenticateToken, controllerFunction); + +3. For optional authentication, you can use: + const { optionalAuth } = require('../middleware/authenticateToken'); + router.get('/', optionalAuth, (req, res) => { ... }); + +4. Your current JWT setup uses: + - Access tokens (15 minutes expiry) + - Refresh tokens (7 days expiry) + - Proper error handling with specific error codes + +Example based on your auth.js pattern: +router.get('/', authenticateToken, controllerFunction); +
+ +
Plugin: JWTMissingProtectionPlugin
+
+ +
+
+
Missing JWT Protection: GET /integrity-check
+ MEDIUM +
+ +
+ ๐Ÿ“ routes/systemRoutes.js + (Line 59) +
+ +
API endpoint GET /integrity-check in systemRoutes.js lacks JWT authentication middleware. Based on your current architecture, this should use authenticateToken middleware.
+ +
+ ๐Ÿ’ก Recommendation: To fix this JWT protection issue, add the authenticateToken middleware: + +1. Import the middleware (if not already imported): + const { authenticateToken } = require('../middleware/authenticateToken'); + +2. Add middleware to the route: + router.get('/integrity-check', authenticateToken, (req, res) => { ... }); + + Or if using a controller: + router.get('/integrity-check', authenticateToken, controllerFunction); + +3. For optional authentication, you can use: + const { optionalAuth } = require('../middleware/authenticateToken'); + router.get('/integrity-check', optionalAuth, (req, res) => { ... }); + +4. Your current JWT setup uses: + - Access tokens (15 minutes expiry) + - Refresh tokens (7 days expiry) + - Proper error handling with specific error codes + +Example based on your auth.js pattern: +router.get('/integrity-check', authenticateToken, controllerFunction); +
+ +
Plugin: JWTMissingProtectionPlugin
+
+ +
+
+
Missing JWT Protection: GET /
+ MEDIUM +
+ +
+ ๐Ÿ“ routes/filter.js + (Line 7) +
+ +
API endpoint GET / in filter.js lacks JWT authentication middleware. Based on your current architecture, this should use authenticateToken middleware.
+ +
+ ๐Ÿ’ก Recommendation: To fix this JWT protection issue, add the authenticateToken middleware: + +1. Import the middleware (if not already imported): + const { authenticateToken } = require('../middleware/authenticateToken'); + +2. Add middleware to the route: + router.get('/', authenticateToken, (req, res) => { ... }); + + Or if using a controller: + router.get('/', authenticateToken, controllerFunction); + +3. For optional authentication, you can use: + const { optionalAuth } = require('../middleware/authenticateToken'); + router.get('/', optionalAuth, (req, res) => { ... }); + +4. Your current JWT setup uses: + - Access tokens (15 minutes expiry) + - Refresh tokens (7 days expiry) + - Proper error handling with specific error codes + +Example based on your auth.js pattern: +router.get('/', authenticateToken, controllerFunction); +
+ +
Plugin: JWTMissingProtectionPlugin
+
+ +
+
+
Missing JWT Protection: GET /
+ MEDIUM +
+ +
+ ๐Ÿ“ routes/articles.js + (Line 5) +
+ +
API endpoint GET / in articles.js lacks JWT authentication middleware. Based on your current architecture, this should use authenticateToken middleware.
+ +
+ ๐Ÿ’ก Recommendation: To fix this JWT protection issue, add the authenticateToken middleware: + +1. Import the middleware (if not already imported): + const { authenticateToken } = require('../middleware/authenticateToken'); + +2. Add middleware to the route: + router.get('/', authenticateToken, (req, res) => { ... }); + + Or if using a controller: + router.get('/', authenticateToken, controllerFunction); + +3. For optional authentication, you can use: + const { optionalAuth } = require('../middleware/authenticateToken'); + router.get('/', optionalAuth, (req, res) => { ... }); + +4. Your current JWT setup uses: + - Access tokens (15 minutes expiry) + - Refresh tokens (7 days expiry) + - Proper error handling with specific error codes + +Example based on your auth.js pattern: +router.get('/', authenticateToken, controllerFunction); +
+ +
Plugin: JWTMissingProtectionPlugin
+
+ +
+
+
Missing JWT Protection: GET /:user_id
+ MEDIUM +
+ +
+ ๐Ÿ“ routes/notifications.js + (Line 21) +
+ +
API endpoint GET /:user_id in notifications.js lacks JWT authentication middleware. Based on your current architecture, this should use authenticateToken middleware.
+ +
+ ๐Ÿ’ก Recommendation: To fix this JWT protection issue, add the authenticateToken middleware: + +1. Import the middleware (if not already imported): + const { authenticateToken } = require('../middleware/authenticateToken'); + +2. Add middleware to the route: + router.get('/:user_id', authenticateToken, (req, res) => { ... }); + + Or if using a controller: + router.get('/:user_id', authenticateToken, controllerFunction); + +3. For optional authentication, you can use: + const { optionalAuth } = require('../middleware/authenticateToken'); + router.get('/:user_id', optionalAuth, (req, res) => { ... }); + +4. Your current JWT setup uses: + - Access tokens (15 minutes expiry) + - Refresh tokens (7 days expiry) + - Proper error handling with specific error codes + +Example based on your auth.js pattern: +router.get('/:user_id', authenticateToken, controllerFunction); +
+ +
Plugin: JWTMissingProtectionPlugin
+
+ +
+
+
Missing JWT Protection: GET /:user_id
+ MEDIUM +
+ +
+ ๐Ÿ“ routes/notifications.js + (Line 21) +
+ +
API endpoint GET /:user_id in notifications.js lacks JWT authentication middleware. Based on your current architecture, this should use authenticateToken middleware.
+ +
+ ๐Ÿ’ก Recommendation: To fix this JWT protection issue, add the authenticateToken middleware: + +1. Import the middleware (if not already imported): + const { authenticateToken } = require('../middleware/authenticateToken'); + +2. Add middleware to the route: + router.get('/:user_id', authenticateToken, (req, res) => { ... }); + + Or if using a controller: + router.get('/:user_id', authenticateToken, controllerFunction); + +3. For optional authentication, you can use: + const { optionalAuth } = require('../middleware/authenticateToken'); + router.get('/:user_id', optionalAuth, (req, res) => { ... }); + +4. Your current JWT setup uses: + - Access tokens (15 minutes expiry) + - Refresh tokens (7 days expiry) + - Proper error handling with specific error codes + +Example based on your auth.js pattern: +router.get('/:user_id', authenticateToken, controllerFunction); +
+ +
Plugin: JWTMissingProtectionPlugin
+
+ +
+
+
Low Entropy JWT Secret
+ MEDIUM +
+ +
+ ๐Ÿ“ .env + (Line 10) +
+ +
JWT secret appears to have low entropy (predictable patterns). This could make the secret easier to guess.
+ +
+ ๐Ÿ’ก Recommendation: Use cryptographically secure random generation for JWT secrets. +
+ +
Plugin: JWTConfigurationPlugin
+
+ +
+
+
Direct JWT Usage Instead of AuthService
+ MEDIUM +
+ +
+ ๐Ÿ“ middleware.js + +
+ +
File middleware.js uses direct jwt.verify() instead of the centralized authService. This bypasses your unified authentication logic.
+ +
+ ๐Ÿ’ก Recommendation: Consider updating this file to use authService.verifyAccessToken() for consistent authentication behavior. +
+ +
Plugin: JWTConfigurationPlugin
+
+ +
+
+
Multiple JWT Implementation Files Detected
+ MEDIUM +
+ +
+ ๐Ÿ“ Multiple files + +
+ +
Found 2 different JWT middleware files: middleware.js, authenticateToken.js. This could lead to inconsistent authentication behavior.
+ +
+ ๐Ÿ’ก Recommendation: Consider consolidating to a single JWT middleware implementation to avoid confusion and ensure consistent behavior. +
+ +
Plugin: JWTConfigurationPlugin
+
+ +
+
+
Incomplete JWT Error Handling
+ LOW +
+ +
+ ๐Ÿ“ middleware.js + +
+ +
JWT verification code lacks comprehensive error handling. Should handle TokenExpiredError, JsonWebTokenError, and other JWT-related errors.
+ +
+ ๐Ÿ’ก Recommendation: Add comprehensive error handling for different JWT error types to provide better user experience and security. +
+ +
Plugin: JWTConfigurationPlugin
+
+ +
+ + +
+ + + \ No newline at end of file From f637efd75004cd1b846f21695cc5daa044f52fe7 Mon Sep 17 00:00:00 2001 From: ChaohuiLi0321 Date: Sun, 7 Sep 2025 02:48:18 +1000 Subject: [PATCH 13/39] Temporarily add a Scanner to http://localhost/api-docs/ --- .../nutrihelp_jwt_security_report.html | 2 +- Vulnerability_Tool_V2/templates/report.html | 183 +++++ index.yaml | 311 ++++++++- package-lock.json | 9 + package.json | 5 +- routes/index.js | 1 + routes/scanner.js | 647 ++++++++++++++++++ 7 files changed, 1154 insertions(+), 4 deletions(-) create mode 100644 Vulnerability_Tool_V2/templates/report.html create mode 100644 routes/scanner.js diff --git a/Vulnerability_Tool_V2/nutrihelp_jwt_security_report.html b/Vulnerability_Tool_V2/nutrihelp_jwt_security_report.html index 670d6c7..dc77831 100644 --- a/Vulnerability_Tool_V2/nutrihelp_jwt_security_report.html +++ b/Vulnerability_Tool_V2/nutrihelp_jwt_security_report.html @@ -1,6 +1,6 @@ - + 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/index.yaml b/index.yaml index 978b542..a6d551d 100644 --- a/index.yaml +++ b/index.yaml @@ -3,10 +3,17 @@ info: title: NutriHelp API version: 1.0.0 servers: - - url: http://localhost/api + - url: "http://localhost" + description: "Local API" + +externalDocs: + description: "Open Vulnerability Scanner UI" + url: "http://localhost:8001/scanner/docs" tags: - name: System description: System and security monitoringย endpoints + - name: Vulnerability Scanner + description: Endpoints for the vulnerability scanner paths: /system/generate-baseline: post: @@ -2102,6 +2109,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: @@ -2740,4 +2965,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/package-lock.json b/package-lock.json index cec8191..88cc625 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": { @@ -3350,6 +3351,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 5b0f63d..d780570 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/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..c0ec8d9 --- /dev/null +++ b/routes/scanner.js @@ -0,0 +1,647 @@ +// routes/scanner.js +const express = require('express'); +const router = express.Router(); +const { spawn } = require('child_process'); +const path = require('path'); +const fs = require('fs').promises; +const { v4: uuidv4 } = require('uuid'); + +// Storage Scan Status +const activeScanners = new Map(); + +/** + * @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 = uuidv4(); + + // 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', (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' + }); + } + + 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', (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' + }); + } + + res.json(scanInfo.result); +}); + +/** + * @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', (req, res) => { + const { scanId } = req.params; + const { format = 'html' } = 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.htmlReport) { + res.setHeader('Content-Type', 'text/html'); + res.setHeader('Content-Disposition', `attachment; filename="security_report_${scanId}.html"`); + res.send(scanInfo.htmlReport); + } 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' + }); + } +}); + +/** + * @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' + }); + } + + const scanId = uuidv4(); + 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]; + + const pythonProcess = spawn(pythonPath, [scriptPath, ...args], { + cwd: scannerPath + }); + + let outputData = ''; + let errorData = ''; + + 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) return; + + if (code === 0) { + try { + const jsonStart = outputData.lastIndexOf('{'); + const jsonEnd = outputData.lastIndexOf('}') + 1; + const jsonPart = outputData.substring(jsonStart, jsonEnd); + + const result = JSON.parse(jsonPart); + 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); + } + } catch (error) { + scanInfo.status = 'failed'; + scanInfo.message = `Failed to parse scan result: ${error.message}`; + } + } else { + scanInfo.status = 'failed'; + scanInfo.message = `Scan failed with code ${code}: ${errorData}`; + } + }); +} + +// 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'); + + const args = ['--target', targetPath, '--format', '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 = JSON.parse(outputData); + resolve(result); + } catch (error) { + reject(new Error(`Failed to parse scan result: ${error.message}`)); + } + } else { + reject(new Error(`Scan failed with code ${code}: ${errorData}`)); + } + }); + }); +} + +// 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 From f0995aa6282801c1b0234ae1f8d2ee83ad549331 Mon Sep 17 00:00:00 2001 From: ChaohuiLi0321 Date: Sun, 7 Sep 2025 01:48:16 +1000 Subject: [PATCH 14/39] Integrate Vulnerability_Scanner_V2.0 into Swagger UI, with the URL: http://localhost:8001/scanner/docs. Run the following command: python -m uvicorn api.scanner_api:app --host 0.0.0.0 --port 8001 --reload --- Vulnerability_Tool_V2/api/__init__.py | 6 + Vulnerability_Tool_V2/api/scanner_api.py | 520 ++++++++++++++++++ Vulnerability_Tool_V2/core/scanner_engine.py | 145 ++++- Vulnerability_Tool_V2/plugins/base_plugin.py | 27 +- .../plugins/jwt_security/jwt_config.py | 144 ++++- .../plugins/jwt_security/jwt_missing.py | 315 +++++++---- .../plugins/rls_security/rls_missing.py | 186 +++++++ Vulnerability_Tool_V2/requirements.txt | 7 + 8 files changed, 1178 insertions(+), 172 deletions(-) create mode 100644 Vulnerability_Tool_V2/api/__init__.py create mode 100644 Vulnerability_Tool_V2/api/scanner_api.py create mode 100644 Vulnerability_Tool_V2/plugins/rls_security/rls_missing.py 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..41153ed --- /dev/null +++ b/Vulnerability_Tool_V2/api/scanner_api.py @@ -0,0 +1,520 @@ +#!/usr/bin/env python3 +""" +Security Scanner V2.0 - FastAPI + Swagger UI ้›†ๆˆ +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 + + +# 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, # ๅฑ•ๅผ€ๅŽŸๅง‹ๆ•ฐๆฎ + "recommendation": f.get("recommendation", "") # ็กฎไฟๅŒ…ๅซ recommendation + } + 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": + html_or_path = generate_html_report(scan_results) + + # normalize bytes -> str + if isinstance(html_or_path, (bytes, bytearray)): + try: + html_or_path = html_or_path.decode("utf-8") + except Exception: + html_or_path = str(html_or_path) + + # 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" + + # if generator returned a path-like and file exists, serve it + candidate = Path(str(html_or_path)) + if isinstance(html_or_path, str) and not html_or_path.lstrip().startswith("<") and candidate.exists(): + return FileResponse(str(candidate), media_type="text/html", filename=f"security_report_{scan_id}.html") + + # otherwise write HTML string to file and return + report_path.write_text(str(html_or_path), encoding="utf-8") + return FileResponse(str(report_path), media_type="text/html", filename=f"security_report_{scan_id}.html") + + # Not download: if HTML string -> inject a download button and return inline HTML + if isinstance(html_or_path, str) and html_or_path.lstrip().startswith("<"): + download_url = f"/scanner/scan/{scan_id}/report?format=html&download=1" + # small floating button HTML + download_button = ( + f'
' + f'Download HTML' + f'
' + ) + # try to insert button before first main container div, fallback prepend + if "
" in html_or_path: + modified = html_or_path.replace("
", download_button + "
", 1) + else: + modified = download_button + html_or_path + return HTMLResponse(content=modified, media_type="text/html") + + # Otherwise treat as path-like: check if file exists and serve inline + candidate = Path(str(html_or_path)) + if candidate.exists() and candidate.is_file(): + return FileResponse(str(candidate), media_type="text/html", filename=f"security_report_{scan_id}.html") + + # Fallback: write whatever we got into reports dir and serve inline HTML + 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_or_path), encoding="utf-8") + return FileResponse(str(report_path), media_type="text/html", filename=f"security_report_{scan_id}.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.""" + # ็›ดๆŽฅไปŽ scan_info ไธญ่Žทๅ–ๆ–‡ไปถๆ•ฐ + total_files = scan_results.get("scan_info", {}).get("stats", {}).get("files_scanned") + + # ๅฆ‚ๆžœไธŠ้ข่Žทๅ–ไธๅˆฐ๏ผŒไปŽ summary ไธญ่Žทๅ– + if total_files is None: + total_files = scan_results.get("summary", {}).get("files_scanned") + + # ็กฎไฟ่ฟ”ๅ›žไธ€ไธชๆœ‰ๆ•ˆ็š„ๆ•ฐๅญ— + 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") + } + 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 + } + + 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", "") # ๆทปๅŠ  recommendation + } + for f in findings + ] + ) + + 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 + +# ๆ›ดๆ–ฐๆจกๆฟ็›ฎๅฝ•้…็ฝฎ๏ผˆๅœจๆ–‡ไปถๅผ€ๅคด็š„ๅฏผๅ…ฅ่ฏญๅฅๅŽๆทปๅŠ ๏ผ‰ +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') + + # ่ฝฌๆข findings ็กฎไฟๅŒ…ๅซ recommendation + 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', '') # ็กฎไฟๅŒ…ๅซ recommendation + } + 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 # ไฝฟ็”จๅค„็†ๅŽ็š„ 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/core/scanner_engine.py b/Vulnerability_Tool_V2/core/scanner_engine.py index be50f95..9798f0a 100644 --- a/Vulnerability_Tool_V2/core/scanner_engine.py +++ b/Vulnerability_Tool_V2/core/scanner_engine.py @@ -9,6 +9,8 @@ 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__), '..')) @@ -93,39 +95,104 @@ def load_plugins(self, plugin_configs: Optional[Dict[str, Any]] = None): self.stats['plugins_loaded'] = plugins_loaded self.logger.info(f"Loaded {plugins_loaded} plugins") - def scan_target(self, target_path: str) -> Dict[str, Any]: - """Scan target path""" - if not os.path.exists(target_path): - raise FileNotFoundError(f"Target path does not exist: {target_path}") - - self.logger.info(f"Starting security scan on: {target_path}") + 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 - # Run all plugin scans - plugin_results = self.plugin_manager.run_all_scans(target_path) + 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 - # Consolidate results + 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 = [] - for plugin_name, findings in plugin_results.items(): - all_findings.extend(findings) - - # Update statistics - self.stats['total_findings'] = len(all_findings) - self.stats['files_scanned'] = self._count_scannable_files(target_path) - - # Build scan result - result = { + + # ็กฎไฟๅ…ˆ่ฎก็ฎ—ๆ–‡ไปถๆ•ฐ้‡ + 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: + # ๅค„็†ๆฏไธช finding + for finding in findings: + # ็”ŸๆˆๅนถๆทปๅŠ ๅปบ่ฎฎ + 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', '') + ) + + # ๅฆ‚ๆžœ finding ๆ˜ฏๅฏน่ฑก + if hasattr(finding, 'recommendation'): + finding.recommendation = recommendation + # ๅฆ‚ๆžœ finding ๆ˜ฏๅญ—ๅ…ธ + elif isinstance(finding, dict): + finding['recommendation'] = recommendation + + # ็กฎไฟๅ…ถไป–ๅฑžๆ€งๅญ˜ๅœจ + if hasattr(finding, 'plugin') and not finding.plugin: + finding.plugin = plugin.__class__.__name__ + if hasattr(finding, 'file_path') and not finding.file_path: + finding.file_path = target_path + + all_findings.extend(findings) + except Exception as e: + self.logger.error(f"Plugin {plugin.__class__.__name__} failed: {e}") + + # ๅœจ findings ่ฝฌๆขไธบๅญ—ๅ…ธๆ—ถไฟ็•™ recommendation + findings_dict = [] + for f in all_findings: + if hasattr(f, 'to_dict'): + finding_dict = f.to_dict() + # ็กฎไฟ recommendation ่ขซๅŒ…ๅซๅœจๅญ—ๅ…ธไธญ + 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, # ไฝฟ็”จๅŒ…ๅซ recommendation ็š„่ฝฌๆขๅŽ็š„ๅˆ—่กจ + '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, - 'timestamp': self._get_timestamp(), - 'scanner_version': '2.0.0', - 'stats': self.stats - }, - 'findings': [f.to_dict() for f in all_findings], - 'summary': self._generate_summary(all_findings) + 'scanner_version': "2.0.0", + 'stats': { + 'files_scanned': files_scanned, + 'plugins_loaded': len(self.plugin_manager.plugins), + 'total_findings': len(all_findings) + } + } } - - self.logger.info(f"Scan completed. Found {len(all_findings)} issues") - return result def _count_scannable_files(self, target_path: str) -> int: """Count scannable files""" @@ -186,4 +253,26 @@ def _get_timestamp(self) -> str: def get_scan_stats(self) -> Dict[str, Any]: """Get scan statistics""" - return self.stats.copy() \ No newline at end of file + return self.stats.copy() + + def _generate_recommendation(self, finding_type: str, file_path: str) -> str: + """Generate specific recommendations based on finding type.""" + if "JWT" in finding_type: + return """To fix this JWT protection issue, add the authenticateToken middleware: + +1. Import the middleware (if not already imported): + const { authenticateToken } = require('../middleware/authenticateToken'); + +2. Add middleware to the route: + router.post('/', authenticateToken, (req, res) => { ... }); + +3. For optional authentication, you can use: + const { optionalAuth } = require('../middleware/authenticateToken'); + +4. Your current JWT setup uses: + - Access tokens (15 minutes expiry) + - Refresh tokens (7 days expiry) + - Proper error handling with specific error codes""" + + # Add more recommendation types as needed + return "" \ No newline at end of file diff --git a/Vulnerability_Tool_V2/plugins/base_plugin.py b/Vulnerability_Tool_V2/plugins/base_plugin.py index 5db0c85..326eb5e 100644 --- a/Vulnerability_Tool_V2/plugins/base_plugin.py +++ b/Vulnerability_Tool_V2/plugins/base_plugin.py @@ -13,29 +13,26 @@ class SecurityFinding: """Standardized security discovery objects""" - def __init__(self, title: str, description: str, file_path: str, - line_number: Optional[int] = None, severity: str = "MEDIUM", - recommendation: Optional[str] = None): + def __init__(self, title: str, severity: str, file_path: str, + description: str, line_number: Optional[int] = None, + plugin: Optional[str] = None, recommendation: Optional[str] = None): self.title = title - self.description = description + self.severity = severity self.file_path = file_path + self.description = description self.line_number = line_number - self.severity = severity.upper() + self.plugin = plugin self.recommendation = recommendation - self.timestamp = datetime.now().isoformat() - self.plugin = None # Will be set by the plugin def to_dict(self) -> Dict[str, Any]: - """Convert to dictionary format""" return { 'title': self.title, - 'description': self.description, + 'severity': self.severity, 'file_path': self.file_path, 'line_number': self.line_number, - 'severity': self.severity, - 'recommendation': self.recommendation, - 'timestamp': self.timestamp, - 'plugin': self.plugin + 'description': self.description, + 'plugin_name': self.plugin, + 'recommendation': self.recommendation } @@ -84,10 +81,10 @@ def add_finding(self, title: str, description: str, file_path: str, finding = SecurityFinding( title=title, - description=description, + severity=severity, file_path=file_path, + description=description, line_number=line_number, - severity=severity, recommendation=recommendation ) finding.plugin = self.name diff --git a/Vulnerability_Tool_V2/plugins/jwt_security/jwt_config.py b/Vulnerability_Tool_V2/plugins/jwt_security/jwt_config.py index 9c9a582..50fd32c 100644 --- a/Vulnerability_Tool_V2/plugins/jwt_security/jwt_config.py +++ b/Vulnerability_Tool_V2/plugins/jwt_security/jwt_config.py @@ -24,23 +24,65 @@ def get_severity_level(self) -> str: return "HIGH" def scan(self, target_path: str) -> List[SecurityFinding]: - """Scan for JWT configuration issues""" - self.clear_findings() - - # Check environment variable files - self._check_env_files(target_path) - - # Check JWT implementation consistency - self._check_jwt_implementation_consistency(target_path) - - # Check auth service configuration - self._check_auth_service_config(target_path) + 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'); - # Check middleware configuration - self._check_middleware_configuration(target_path) +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""" + )) - self.logger.info(f"JWT Configuration scan found {len(self.findings)} issues") - return self.findings + return findings def _check_env_files(self, target_path: str): """Check environment variable configuration""" @@ -314,6 +356,78 @@ def _check_middleware_configuration(self, target_path: str): 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 diff --git a/Vulnerability_Tool_V2/plugins/jwt_security/jwt_missing.py b/Vulnerability_Tool_V2/plugins/jwt_security/jwt_missing.py index 16e42b1..a81effb 100644 --- a/Vulnerability_Tool_V2/plugins/jwt_security/jwt_missing.py +++ b/Vulnerability_Tool_V2/plugins/jwt_security/jwt_missing.py @@ -6,6 +6,8 @@ import os import re +import glob # ๆทปๅŠ ่ฟ™่กŒ +import fnmatch from typing import List, Dict, Any from ..base_plugin import BaseSecurityPlugin, SecurityFinding @@ -13,6 +15,10 @@ class JWTMissingProtectionPlugin(BaseSecurityPlugin): """Detects API endpoints missing JWT protection - Optimized for NutriHelp's actual architecture""" + def __init__(self, *args, **kwargs): # ไฟฎๆ”น่ฟ™้‡Œ๏ผŒๆทปๅŠ *args, **kwargs + super().__init__(*args, **kwargs) # ไฟฎๆ”น่ฟ™้‡Œ๏ผŒไผ ้€’ๅ‚ๆ•ฐ็ป™็ˆถ็ฑป + self._findings_cache = set() # ็”จไบŽ็ผ“ๅญ˜ๅทฒๅ‘็Žฐ็š„้—ฎ้ข˜ + def get_plugin_info(self) -> Dict[str, str]: return { 'name': 'JWT Missing Protection Detector', @@ -25,30 +31,16 @@ def get_severity_level(self) -> str: return "HIGH" def scan(self, target_path: str) -> List[SecurityFinding]: - """Scan for missing JWT protection issues in target paths""" - self.clear_findings() - - # Scan routes directory - routes_path = os.path.join(target_path, 'routes') - - if not os.path.exists(routes_path): - self.logger.warning(f"Routes directory not found: {routes_path}") - return self.findings + """Scan for missing JWT protection.""" + findings = [] - self.logger.info(f"Scanning routes directory: {routes_path}") - - # Traverse all route files - for root, dirs, files in os.walk(routes_path): - for file in files: - if file.endswith('.js'): - file_path = os.path.join(root, file) - self._analyze_route_file(file_path, target_path) + for route_file in self._find_route_files(target_path): + self._analyze_route_file(route_file, target_path) - self.logger.info(f"JWT Missing Protection scan found {len(self.findings)} issues") - return self.findings - + return self.findings # ่ฟ”ๅ›žๆ”ถ้›†ๅˆฐ็š„ๆ‰€ๆœ‰ findings + def _analyze_route_file(self, file_path: str, base_path: str): - """Analyze a single route file - Based on existing route structure""" + """Analyze a single route file.""" try: content = self.read_file_safe(file_path) if not content: @@ -57,24 +49,34 @@ def _analyze_route_file(self, file_path: str, base_path: str): lines = content.split('\n') relative_path = self.get_relative_path(file_path, base_path) - # Based on existing code, detect different route definition patterns route_patterns = [ - # Express router ( auth.js, recipe.js ) - r'router\.(get|post|put|delete|patch)\s*\(\s*[\'"`]([^\'"`]+)[\'"`]', - # App.use ( index.js ) - r'app\.use\s*\(\s*[\'"`]([^\'"`]+)[\'"`]', - # Controller direct call - r'router\.(get|post|put|delete|patch)\s*\(\s*[\'"`]([^\'"`]+)[\'"`]\s*,\s*[^,]*controller' + r'router\.(get|post|put|delete|patch)\s*\(\s*[\'"`]([^\'"`]+)[\'"`]' ] for i, line in enumerate(lines, 1): - self._check_line_for_unprotected_routes( - line, lines, i, relative_path, route_patterns, os.path.basename(file_path) - ) - + for pattern in route_patterns: + matches = re.finditer(pattern, line, re.IGNORECASE) + + for match in matches: + method = match.group(1).upper() + path = match.group(2) + + if not self._has_jwt_protection(line, lines, i): + severity = self._determine_severity(path, method, os.path.basename(file_path)) + recommendation = self._get_recommendation(method, path) + + self.add_finding( + title=f"Missing JWT Protection: {method} {path}", + description=f"API endpoint {method} {path} in {os.path.basename(file_path)} lacks JWT authentication middleware. Based on your current architecture, this should use authenticateToken middleware.", + file_path=relative_path, + line_number=i, + severity=severity, + recommendation=recommendation + ) + except Exception as e: self.logger.error(f"Error analyzing route file {file_path}: {e}") - + def _check_line_for_unprotected_routes(self, line: str, all_lines: List[str], line_number: int, file_path: str, route_patterns: List[str], filename: str): @@ -143,91 +145,76 @@ def _is_public_endpoint(self, endpoint: str, filename: str) -> bool: return False - def _has_jwt_protection(self, current_line: str, all_lines: List[str], - line_number: int) -> bool: - """Check if a route has JWT protection - based on existing middleware""" - - # Existing JWT middleware names - jwt_patterns = [ - 'authenticateToken', - 'optionalAuth', - 'verifyToken', - 'jwtAuth', - 'requireAuth' + def _has_jwt_protection(self, current_line: str, all_lines: List[str], line_number: int) -> bool: + """Check if route has JWT protection.""" + # ้ข„ๅฎšไน‰่ฑๅ…่ทฏ็”ฑ + exempt_routes = [ + '/health', + '/status', + '/login', + '/register', + '/public', + '/docs' ] - # Method 1: Check current line - for pattern in jwt_patterns: - if re.search(rf'\b{pattern}\b', current_line, re.IGNORECASE): - return True - - # Method 2: Check imports and usage - # Check if imported from authenticateToken module - if "require('../middleware/authenticateToken')" in current_line or \ - "require('./middleware/authenticateToken')" in current_line: - - # Check if the imported middleware is used in subsequent lines - search_range = 10 - start_line = max(0, line_number - 1) - end_line = min(len(all_lines), line_number + search_range) - - context = ' '.join(all_lines[start_line:end_line]) - for pattern in jwt_patterns: - if pattern in context: - return True - - # Method 3: Check destructured import { authenticateToken } - destructure_pattern = r'\{\s*authenticateToken\s*\}' - if re.search(destructure_pattern, current_line): - return True - - # Method 4: Check controller routes - if 'controller' in current_line.lower() and any(word in current_line.lower() - for word in ['auth', 'protected', 'secure']): + # ๆฃ€ๆŸฅๆ˜ฏๅฆๆ˜ฏ่ฑๅ…่ทฏ็”ฑ + if any(route in current_line for route in exempt_routes): return True - return False - - def _determine_severity(self, endpoint: str, method: str, filename: str) -> str: - """Determine severity by endpoint and method - based on existing logic""" + # ๆฃ€ๆŸฅไธŠไธ‹ๆ–‡ไธญ็š„JWTไฟๆŠค + context_start = max(0, line_number - 5) + context_end = min(len(all_lines), line_number + 5) + context = '\n'.join(all_lines[context_start:context_end]) - endpoint_lower = endpoint.lower() - - # Based on existing route files determine critical business - critical_files = ['userprofile.js', 'userpassword.js', 'account.js', 'medicalPrediction.js'] - high_risk_files = ['recipe.js', 'mealplan.js', 'upload.js', 'notifications.js'] - - # Critical endpoint patterns - critical_patterns = [ - '/admin', '/delete', '/remove', '/password', '/profile', - '/medical', '/prediction', '/account', '/payment' + # JWTไฟๆŠคๆจกๅผ + protection_patterns = [ + 'authenticateToken', + 'requireAuth', + 'isAuthenticated', + 'checkJwt', + 'verifyToken' ] - high_risk_patterns = [ - '/user', '/recipe', '/mealplan', '/upload', '/notification', - '/feedback', '/preference', '/appointment' - ] + # ๆฃ€ๆŸฅ่ทฏ็”ฑๆ˜ฏๅฆๆœ‰JWTไฟๆŠค + return any(pattern in context for pattern in protection_patterns) + + def _determine_severity(self, endpoint: str, method: str, filename: str) -> str: + """Determine severity based on endpoint and method.""" + endpoint_lower = endpoint.lower() - # File-level determination - if filename in critical_files: + # CRITICAL - ๆถ‰ๅŠ็”จๆˆทๆ•ฐๆฎๅ’Œๆ•ๆ„Ÿๆ“ไฝœ + if any(sensitive in endpoint_lower for sensitive in [ + 'user', 'profile', 'password', 'admin', 'token', + 'auth', 'key', 'secret', 'credential' + ]): return "CRITICAL" - elif filename in high_risk_files and method in ['POST', 'PUT', 'DELETE', 'PATCH']: - return "HIGH" - # Endpoint pattern matching - if any(pattern in endpoint_lower for pattern in critical_patterns): - return "CRITICAL" - elif any(pattern in endpoint_lower for pattern in high_risk_patterns): - return "HIGH" - elif method in ['POST', 'PUT', 'DELETE', 'PATCH']: + # HIGH - ๆ•ฐๆฎไฟฎๆ”นๆ“ไฝœ + if method in ['POST', 'PUT', 'DELETE', 'PATCH'] and not any( + safe in endpoint_lower for safe in [ + 'login', 'register', 'public', 'health' + ] + ): return "HIGH" - else: + + # MEDIUM - ๆ•ฐๆฎ่ฏปๅ–ๆ“ไฝœ + if method == 'GET' and any(sensitive in endpoint_lower for sensitive in [ + 'user', 'data', 'profile', 'report', 'log' + ]): return "MEDIUM" - - def _get_recommendation(self, endpoint: str, method: str) -> str: - """Get fix suggestions based on existing architecture""" - return f""" -To fix this JWT protection issue, add the authenticateToken middleware: + + # LOW - ๅ…ถไป–ๆ“ไฝœ + if method == 'GET' and any(public in endpoint_lower for public in [ + 'public', 'health', 'status', 'version' + ]): + return "LOW" + + # ้ป˜่ฎคไธบ MEDIUM + return "MEDIUM" + + def _get_recommendation(self, method: str, endpoint: str) -> str: + """Generate specific recommendation.""" + return f"""To fix this JWT protection issue, add the authenticateToken middleware: 1. Import the middleware (if not already imported): const {{ authenticateToken }} = require('../middleware/authenticateToken'); @@ -235,21 +222,121 @@ def _get_recommendation(self, endpoint: str, method: str) -> str: 2. Add middleware to the route: router.{method.lower()}('{endpoint}', authenticateToken, (req, res) => {{ ... }}); - Or if using a controller: - router.{method.lower()}('{endpoint}', authenticateToken, controllerFunction); - 3. For optional authentication, you can use: const {{ optionalAuth }} = require('../middleware/authenticateToken'); - router.{method.lower()}('{endpoint}', optionalAuth, (req, res) => {{ ... }}); 4. Your current JWT setup uses: - Access tokens (15 minutes expiry) - Refresh tokens (7 days expiry) - - Proper error handling with specific error codes + - Proper error handling with specific error codes""" + + def _find_route_files(self, base_path: str) -> List[str]: + """Find all route files in the project.""" + route_files = set() # ไฝฟ็”จ้›†ๅˆๅŽป้‡ + + # ๅฎšไน‰่ฆๆ‰ซๆ็š„็›ฎๅฝ•ๅ’Œๆ–‡ไปถๆจกๅผ + scan_patterns = [ + 'routes/*.js', # ไธป่ทฏ็”ฑ็›ฎๅฝ• + 'src/routes/*.js', # srcไธ‹็š„่ทฏ็”ฑ + 'api/routes/*.js', # apiไธ‹็š„่ทฏ็”ฑ + '**/routes/*.js', # ไปปๆ„ๆทฑๅบฆ็š„routes็›ฎๅฝ• + ] + + # ๅฎšไน‰่ฆๆŽ’้™ค็š„ๆจกๅผ + exclude_patterns = [ + '**/node_modules/**', # ๆŽ’้™คnode_modules + '**/test/**', # ๆŽ’้™คๆต‹่ฏ•ๆ–‡ไปถ + '**/tests/**', + '**/mock/**', # ๆŽ’้™คmockๆ–‡ไปถ + '**/*.test.js', + '**/*.spec.js' + ] + + try: + for pattern in scan_patterns: + full_pattern = os.path.join(base_path, pattern) + matches = glob.glob(full_pattern, recursive=True) + + # ่ฟ‡ๆปคๆŽ’้™ค็š„ๆ–‡ไปถ + filtered_matches = [ + f for f in matches + if not any(fnmatch.fnmatch(f, os.path.join(base_path, ep)) + for ep in exclude_patterns) + ] + + route_files.update(filtered_matches) + + self.logger.info(f"Found {len(route_files)} route files to scan") + + except Exception as e: + self.logger.error(f"Error finding route files: {e}") + + return list(route_files) + + def _cache_key(self, finding: dict) -> str: + """Generate a unique key for finding.""" + return f"{finding['file_path']}:{finding['line_number']}:{finding['title']}" + + def add_finding(self, **kwargs): + """Add finding with deduplication.""" + cache_key = self._cache_key(kwargs) + + if cache_key not in self._findings_cache: + self._findings_cache.add(cache_key) + self.findings.append(SecurityFinding(**kwargs)) + + def generate_recommendation(self, route_info: dict) -> str: + """Generate specific recommendation based on route info""" + method = route_info['method'] + path = route_info['path'] + file_name = os.path.basename(route_info.get('file_path', '')) + + # ไธบไธๅŒ็ฑปๅž‹็š„่ทฏ็”ฑ็”Ÿๆˆๅ…ทไฝ“็š„ๅปบ่ฎฎ + if 'user' in path.lower() or 'profile' in path.lower(): + return f"""This endpoint ({method} {path}) handles user data and requires strong authentication: + +1. Import the JWT middleware: + const {{ authenticateToken }} = require('../middleware/authenticateToken'); + +2. Add strict authentication: + router.{method.lower()}('{path}', authenticateToken, (req, res) => {{ + // Verify user ID matches authenticated user + if (req.user.id !== req.params.userId) {{ + return res.status(403).json({{ error: 'Unauthorized access' }}); + }} + // ... rest of your code + }});""" + + elif method in ['POST', 'PUT', 'DELETE']: + return f"""This endpoint ({method} {path}) modifies data and requires authentication: + +1. Import the JWT middleware: + const {{ authenticateToken }} = require('../middleware/authenticateToken'); -Example based on your auth.js pattern: -router.{method.lower()}('{endpoint}', authenticateToken, controllerFunction); - """.strip() +2. Add authentication to protect data modification: + router.{method.lower()}('{path}', authenticateToken, yourController); + +3. Verify request in controller: + function yourController(req, res) {{ + // Ensure user has required permissions + if (!req.user.permissions.includes('{path.split("/")[1]}')) {{ + return res.status(403).json({{ error: 'Insufficient permissions' }}); + }} + // ... rest of your code + }}""" + + else: + return f"""Add JWT authentication to protect this endpoint: + +1. Import the middleware: + const {{ authenticateToken }} = require('../middleware/authenticateToken'); + +2. Add middleware to route: + router.{method.lower()}('{path}', authenticateToken, (req, res) => {{ ... }}); + +3. Consider using optional authentication if this is a public endpoint: + const {{ optionalAuth }} = require('../middleware/authenticateToken'); + router.{method.lower()}('{path}', optionalAuth, (req, res) => {{ ... }});""" # Test function 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..e982b21 --- /dev/null +++ b/Vulnerability_Tool_V2/plugins/rls_security/rls_missing.py @@ -0,0 +1,186 @@ +""" +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 +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") + +# --- add a small wrapper so findings provide a to_dict() method expected by the engine --- +class Finding: + """ๅŒ…่ฃ…findingๅญ—ๅ…ธๅนถๆไพ›to_dictๆ–นๆณ•""" + def __init__(self, data: Dict): + self._data = data + self._data['plugin'] = 'RLSMissingProtectionPlugin' + # ๆทปๅŠ ้ป˜่ฎค็š„ recommendation + self._data['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""" + + def to_dict(self) -> Dict: + return self._data + + def get(self, key: str, default=None): # ๆทปๅŠ  get ๆ–นๆณ• + return self._data.get(key, default) + + @property + def severity(self) -> str: + return self._data.get('severity', '') + + @property + def plugin(self) -> str: + return self._data.get('plugin', 'RLSMissingProtectionPlugin') + + # ๆทปๅŠ ๅ…ถไป–ๅฟ…่ฆ็š„ๅฑžๆ€ง่ฎฟ้—ฎๅ™จ + @property + def recommendation(self) -> str: + return self._data.get('recommendation', '') + + @recommendation.setter + def recommendation(self, value: str): + self._data['recommendation'] = value + +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, project_root: Optional[str] = None): + super().__init__() + self.project_root = project_root or os.getcwd() + + def metadata(self) -> Dict[str, str]: + return {"name": self.name, "version": self.version, "description": self.description} + + 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[Finding]: + 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): + findings.append(Finding({ + "id": f"rls-001:{os.path.relpath(path, self.project_root)}:{i}", + "title": "Possible RLS-related statement found", + "severity": "info", + "description": f"Pattern '{pat.pattern}' matched.", + "file": os.path.relpath(path, self.project_root), + "line": i, + "match": line.strip(), + })) + break + except Exception as e: + logger.debug("Failed to read %s: %s", path, e) + return findings + + # ---------- New: Abstract interface for loaders ---------- + def get_plugin_info(self) -> Dict[str, str]: + """Return plugin information (for loader/UI use)""" + return { + "id": "rls_missing_protection", + "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 scan(self, target_path: Optional[str] = None) -> List[Finding]: + """ + Run the RLS detection. Accepts optional target_path to be compatible with + engine calls (engine may call plugin.scan(target_path)). + """ + 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: + findings.append(Finding({ + "id": "rls-000", + "title": "Potential missing Rowโ€‘Level Security (RLS)", + "severity": self.get_severity_level(), + "description": ( + "No obvious RLS-related configuration or SQL statements were detected. " + "Ensure that sensitive tables enforce row-level access controls (policies)." + ), + "file": None, + "line": None, + })) + + logger.info("RLS detector finished, findings: %d", len(findings)) + return findings + + # Keep run() for backward compatibility and call scan() + def run(self) -> List[object]: + 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/requirements.txt b/Vulnerability_Tool_V2/requirements.txt index 69ba381..ed62c91 100644 --- a/Vulnerability_Tool_V2/requirements.txt +++ b/Vulnerability_Tool_V2/requirements.txt @@ -12,3 +12,10 @@ 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 From 19bad1e86b21aea60b3546f9f261a3e031adadb7 Mon Sep 17 00:00:00 2001 From: ChaohuiLi0321 Date: Sun, 7 Sep 2025 02:34:48 +1000 Subject: [PATCH 15/39] resolve conflicts and commit --- Vulnerability_Tool_V2/api/scanner_api.py | 28 ++++++++++---------- Vulnerability_Tool_V2/core/scanner_engine.py | 24 ++++++++--------- 2 files changed, 26 insertions(+), 26 deletions(-) diff --git a/Vulnerability_Tool_V2/api/scanner_api.py b/Vulnerability_Tool_V2/api/scanner_api.py index 41153ed..cafb2a9 100644 --- a/Vulnerability_Tool_V2/api/scanner_api.py +++ b/Vulnerability_Tool_V2/api/scanner_api.py @@ -1,6 +1,6 @@ #!/usr/bin/env python3 """ -Security Scanner V2.0 - FastAPI + Swagger UI ้›†ๆˆ +Security Scanner V2.0 - FastAPI + Swagger UI integrated api/scanner_api.py """ @@ -70,7 +70,7 @@ class Config: "severity": "CRITICAL", "file_path": "routes/userprofile.js", "description": "API endpoint lacks JWT authentication middleware", - "recommendation": "Add authenticateToken middleware" # ๆทปๅŠ ็คบไพ‹ + "recommendation": "Add authenticateToken middleware" } ] } @@ -235,8 +235,8 @@ async def get_scan_report(scan_id: str, format: str = "html", download: bool = F }, "findings": [ { - **f, # ๅฑ•ๅผ€ๅŽŸๅง‹ๆ•ฐๆฎ - "recommendation": f.get("recommendation", "") # ็กฎไฟๅŒ…ๅซ recommendation + **f, # Expand the original data + "recommendation": f.get("recommendation", "") # Ensure recommendation is included } for f in result.findings ], @@ -325,14 +325,14 @@ async def get_scan_report(scan_id: str, format: str = "html", download: bool = F def _unwrap_scan_results(scan_results: dict): """Normalize scanner output into fields used by the API.""" - # ็›ดๆŽฅไปŽ scan_info ไธญ่Žทๅ–ๆ–‡ไปถๆ•ฐ + # Get the number of files directly from scan_info total_files = scan_results.get("scan_info", {}).get("stats", {}).get("files_scanned") - # ๅฆ‚ๆžœไธŠ้ข่Žทๅ–ไธๅˆฐ๏ผŒไปŽ summary ไธญ่Žทๅ– + # 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 @@ -428,7 +428,7 @@ async def perform_scan(scan_id: str, scan_request: ScanRequest): "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", "") # ๆทปๅŠ  recommendation + "recommendation": f.get("recommendation", "") # Add a recommendation } for f in findings ] @@ -457,7 +457,7 @@ async def perform_scan(scan_id: str, scan_request: ScanRequest): 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" @@ -469,8 +469,8 @@ def generate_html_report(scan_results: dict) -> str: autoescape=select_autoescape(['html', 'xml']) ) template = env.get_template('report.html') - - # ่ฝฌๆข findings ็กฎไฟๅŒ…ๅซ recommendation + + # Convert findings to ensure recommendations are included findings = [] for f in scan_results.get('findings', []): finding = { @@ -480,7 +480,7 @@ def generate_html_report(scan_results: dict) -> str: 'line_number': f.get('line_number'), 'description': f.get('description', ''), 'plugin_name': f.get('plugin_name', ''), - 'recommendation': f.get('recommendation', '') # ็กฎไฟๅŒ…ๅซ recommendation + 'recommendation': f.get('recommendation', '') # Ensure recommendation is included } findings.append(finding) @@ -488,7 +488,7 @@ def generate_html_report(scan_results: dict) -> str: 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 # ไฝฟ็”จๅค„็†ๅŽ็š„ findings + findings=findings # Use the processed findings ) except Exception as e: raise HTTPException( diff --git a/Vulnerability_Tool_V2/core/scanner_engine.py b/Vulnerability_Tool_V2/core/scanner_engine.py index 9798f0a..e0103ca 100644 --- a/Vulnerability_Tool_V2/core/scanner_engine.py +++ b/Vulnerability_Tool_V2/core/scanner_engine.py @@ -127,7 +127,7 @@ def scan_target(self, target_path: str) -> Dict: 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 @@ -135,22 +135,22 @@ def scan_target(self, target_path: str) -> Dict: try: findings = plugin.scan(target_path) if findings: - # ๅค„็†ๆฏไธช finding + # Process each finding for finding in findings: - # ็”ŸๆˆๅนถๆทปๅŠ ๅปบ่ฎฎ + # Generate and add recommendation 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', '') ) - - # ๅฆ‚ๆžœ finding ๆ˜ฏๅฏน่ฑก + + # If finding is an object if hasattr(finding, 'recommendation'): finding.recommendation = recommendation - # ๅฆ‚ๆžœ finding ๆ˜ฏๅญ—ๅ…ธ + # If finding is a dictionary elif isinstance(finding, dict): finding['recommendation'] = recommendation - - # ็กฎไฟๅ…ถไป–ๅฑžๆ€งๅญ˜ๅœจ + + # Ensure other attributes exist if hasattr(finding, 'plugin') and not finding.plugin: finding.plugin = plugin.__class__.__name__ if hasattr(finding, 'file_path') and not finding.file_path: @@ -159,13 +159,13 @@ def scan_target(self, target_path: str) -> Dict: all_findings.extend(findings) except Exception as e: self.logger.error(f"Plugin {plugin.__class__.__name__} failed: {e}") - - # ๅœจ findings ่ฝฌๆขไธบๅญ—ๅ…ธๆ—ถไฟ็•™ recommendation + + # Convert findings to ensure recommendations are included findings_dict = [] for f in all_findings: if hasattr(f, 'to_dict'): finding_dict = f.to_dict() - # ็กฎไฟ recommendation ่ขซๅŒ…ๅซๅœจๅญ—ๅ…ธไธญ + # Ensure recommendation is included in the dictionary if hasattr(f, 'recommendation'): finding_dict['recommendation'] = f.recommendation findings_dict.append(finding_dict) @@ -176,7 +176,7 @@ def scan_target(self, target_path: str) -> Dict: 'scan_id': str(uuid.uuid4()), 'target': target_path, 'timestamp': datetime.now().isoformat(), - 'findings': findings_dict, # ไฝฟ็”จๅŒ…ๅซ recommendation ็š„่ฝฌๆขๅŽ็š„ๅˆ—่กจ + 'findings': findings_dict, # Use the processed findings 'summary': { 'total': len(all_findings), 'files_scanned': files_scanned, From 1a7925e06e57d5d7d62e53738750eb98b7d32bef Mon Sep 17 00:00:00 2001 From: ChaohuiLi0321 Date: Sun, 7 Sep 2025 02:58:42 +1000 Subject: [PATCH 16/39] Change Comment --- .../plugins/jwt_security/jwt_missing.py | 78 +++++++++---------- 1 file changed, 39 insertions(+), 39 deletions(-) diff --git a/Vulnerability_Tool_V2/plugins/jwt_security/jwt_missing.py b/Vulnerability_Tool_V2/plugins/jwt_security/jwt_missing.py index a81effb..d1f439f 100644 --- a/Vulnerability_Tool_V2/plugins/jwt_security/jwt_missing.py +++ b/Vulnerability_Tool_V2/plugins/jwt_security/jwt_missing.py @@ -6,7 +6,7 @@ import os import re -import glob # ๆทปๅŠ ่ฟ™่กŒ +import glob import fnmatch from typing import List, Dict, Any from ..base_plugin import BaseSecurityPlugin, SecurityFinding @@ -15,9 +15,9 @@ class JWTMissingProtectionPlugin(BaseSecurityPlugin): """Detects API endpoints missing JWT protection - Optimized for NutriHelp's actual architecture""" - def __init__(self, *args, **kwargs): # ไฟฎๆ”น่ฟ™้‡Œ๏ผŒๆทปๅŠ *args, **kwargs - super().__init__(*args, **kwargs) # ไฟฎๆ”น่ฟ™้‡Œ๏ผŒไผ ้€’ๅ‚ๆ•ฐ็ป™็ˆถ็ฑป - self._findings_cache = set() # ็”จไบŽ็ผ“ๅญ˜ๅทฒๅ‘็Žฐ็š„้—ฎ้ข˜ + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self._findings_cache = set() def get_plugin_info(self) -> Dict[str, str]: return { @@ -37,7 +37,7 @@ def scan(self, target_path: str) -> List[SecurityFinding]: for route_file in self._find_route_files(target_path): self._analyze_route_file(route_file, target_path) - return self.findings # ่ฟ”ๅ›žๆ”ถ้›†ๅˆฐ็š„ๆ‰€ๆœ‰ findings + return self.findings # Return all collected findings def _analyze_route_file(self, file_path: str, base_path: str): """Analyze a single route file.""" @@ -147,7 +147,7 @@ def _is_public_endpoint(self, endpoint: str, filename: str) -> bool: def _has_jwt_protection(self, current_line: str, all_lines: List[str], line_number: int) -> bool: """Check if route has JWT protection.""" - # ้ข„ๅฎšไน‰่ฑๅ…่ทฏ็”ฑ + # Predefined exemption routes exempt_routes = [ '/health', '/status', @@ -156,17 +156,17 @@ def _has_jwt_protection(self, current_line: str, all_lines: List[str], line_numb '/public', '/docs' ] - - # ๆฃ€ๆŸฅๆ˜ฏๅฆๆ˜ฏ่ฑๅ…่ทฏ็”ฑ + + # Check if it's an exempt route if any(route in current_line for route in exempt_routes): return True - - # ๆฃ€ๆŸฅไธŠไธ‹ๆ–‡ไธญ็š„JWTไฟๆŠค + + # Check for JWT protection in context context_start = max(0, line_number - 5) context_end = min(len(all_lines), line_number + 5) context = '\n'.join(all_lines[context_start:context_end]) - - # JWTไฟๆŠคๆจกๅผ + + # JWT protection patterns protection_patterns = [ 'authenticateToken', 'requireAuth', @@ -174,42 +174,42 @@ def _has_jwt_protection(self, current_line: str, all_lines: List[str], line_numb 'checkJwt', 'verifyToken' ] - - # ๆฃ€ๆŸฅ่ทฏ็”ฑๆ˜ฏๅฆๆœ‰JWTไฟๆŠค + + # Check if the route has JWT protection return any(pattern in context for pattern in protection_patterns) def _determine_severity(self, endpoint: str, method: str, filename: str) -> str: """Determine severity based on endpoint and method.""" endpoint_lower = endpoint.lower() - - # CRITICAL - ๆถ‰ๅŠ็”จๆˆทๆ•ฐๆฎๅ’Œๆ•ๆ„Ÿๆ“ไฝœ + + # CRITICAL - Involves user data and sensitive operations if any(sensitive in endpoint_lower for sensitive in [ 'user', 'profile', 'password', 'admin', 'token', 'auth', 'key', 'secret', 'credential' ]): return "CRITICAL" - - # HIGH - ๆ•ฐๆฎไฟฎๆ”นๆ“ไฝœ + + # HIGH - Data modification operations if method in ['POST', 'PUT', 'DELETE', 'PATCH'] and not any( safe in endpoint_lower for safe in [ 'login', 'register', 'public', 'health' ] ): return "HIGH" - - # MEDIUM - ๆ•ฐๆฎ่ฏปๅ–ๆ“ไฝœ + + # MEDIUM - Data reading operations if method == 'GET' and any(sensitive in endpoint_lower for sensitive in [ 'user', 'data', 'profile', 'report', 'log' ]): return "MEDIUM" - - # LOW - ๅ…ถไป–ๆ“ไฝœ + + # LOW - Other operations if method == 'GET' and any(public in endpoint_lower for public in [ 'public', 'health', 'status', 'version' ]): return "LOW" - - # ้ป˜่ฎคไธบ MEDIUM + + # Default to MEDIUM return "MEDIUM" def _get_recommendation(self, method: str, endpoint: str) -> str: @@ -232,22 +232,22 @@ def _get_recommendation(self, method: str, endpoint: str) -> str: def _find_route_files(self, base_path: str) -> List[str]: """Find all route files in the project.""" - route_files = set() # ไฝฟ็”จ้›†ๅˆๅŽป้‡ - - # ๅฎšไน‰่ฆๆ‰ซๆ็š„็›ฎๅฝ•ๅ’Œๆ–‡ไปถๆจกๅผ + route_files = set() # Use collection deduplication + + # Define directories and file patterns to scan scan_patterns = [ - 'routes/*.js', # ไธป่ทฏ็”ฑ็›ฎๅฝ• - 'src/routes/*.js', # srcไธ‹็š„่ทฏ็”ฑ - 'api/routes/*.js', # apiไธ‹็š„่ทฏ็”ฑ - '**/routes/*.js', # ไปปๆ„ๆทฑๅบฆ็š„routes็›ฎๅฝ• + 'routes/*.js', # Main route directory + 'src/routes/*.js', # Routes under src + 'api/routes/*.js', # Routes under api + '**/routes/*.js', # Routes directory at any depth ] - - # ๅฎšไน‰่ฆๆŽ’้™ค็š„ๆจกๅผ + + # Define patterns to exclude exclude_patterns = [ - '**/node_modules/**', # ๆŽ’้™คnode_modules - '**/test/**', # ๆŽ’้™คๆต‹่ฏ•ๆ–‡ไปถ + '**/node_modules/**', # Exclude node_modules + '**/test/**', # Exclude test files '**/tests/**', - '**/mock/**', # ๆŽ’้™คmockๆ–‡ไปถ + '**/mock/**', # Exclude mock files '**/*.test.js', '**/*.spec.js' ] @@ -256,8 +256,8 @@ def _find_route_files(self, base_path: str) -> List[str]: for pattern in scan_patterns: full_pattern = os.path.join(base_path, pattern) matches = glob.glob(full_pattern, recursive=True) - - # ่ฟ‡ๆปคๆŽ’้™ค็š„ๆ–‡ไปถ + + # Filter out excluded files filtered_matches = [ f for f in matches if not any(fnmatch.fnmatch(f, os.path.join(base_path, ep)) @@ -291,7 +291,7 @@ def generate_recommendation(self, route_info: dict) -> str: path = route_info['path'] file_name = os.path.basename(route_info.get('file_path', '')) - # ไธบไธๅŒ็ฑปๅž‹็š„่ทฏ็”ฑ็”Ÿๆˆๅ…ทไฝ“็š„ๅปบ่ฎฎ + # Generate specific recommendations for different types of routes if 'user' in path.lower() or 'profile' in path.lower(): return f"""This endpoint ({method} {path}) handles user data and requires strong authentication: From 45c826495f871c36afe3f00e80a0be6e59be09fb Mon Sep 17 00:00:00 2001 From: ChaohuiLi0321 Date: Sun, 7 Sep 2025 03:02:12 +1000 Subject: [PATCH 17/39] Update comment --- Vulnerability_Tool_V2/plugins/rls_security/rls_missing.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Vulnerability_Tool_V2/plugins/rls_security/rls_missing.py b/Vulnerability_Tool_V2/plugins/rls_security/rls_missing.py index e982b21..8cbf293 100644 --- a/Vulnerability_Tool_V2/plugins/rls_security/rls_missing.py +++ b/Vulnerability_Tool_V2/plugins/rls_security/rls_missing.py @@ -32,7 +32,7 @@ class Finding: def __init__(self, data: Dict): self._data = data self._data['plugin'] = 'RLSMissingProtectionPlugin' - # ๆทปๅŠ ้ป˜่ฎค็š„ recommendation + # Add default recommendation self._data['recommendation'] = """To implement Row-Level Security (RLS): 1. Enable RLS on sensitive tables: @@ -51,7 +51,7 @@ def __init__(self, data: Dict): def to_dict(self) -> Dict: return self._data - def get(self, key: str, default=None): # ๆทปๅŠ  get ๆ–นๆณ• + def get(self, key: str, default=None): return self._data.get(key, default) @property @@ -62,7 +62,7 @@ def severity(self) -> str: def plugin(self) -> str: return self._data.get('plugin', 'RLSMissingProtectionPlugin') - # ๆทปๅŠ ๅ…ถไป–ๅฟ…่ฆ็š„ๅฑžๆ€ง่ฎฟ้—ฎๅ™จ + # Add other necessary property accessors @property def recommendation(self) -> str: return self._data.get('recommendation', '') From a49416ecc445aa618f3b607261c8b06f510806a7 Mon Sep 17 00:00:00 2001 From: ChaohuiLi0321 Date: Sun, 7 Sep 2025 07:38:14 +1000 Subject: [PATCH 18/39] Update - Ensure both command scanning and Swagger UI scanning are working properly. --- .../config/scanner_config.yaml | 193 +++----- Vulnerability_Tool_V2/core/scanner_engine.py | 37 +- .../plugins/jwt_security/__init__.py | 1 + .../plugins/jwt_security/jwt_missing.py | 431 ++++++------------ .../plugins/rls_security/__init__.py | 1 + .../plugins/rls_security/rls_missing.py | 183 +------- .../rls_security_disabled/rls_missing.py | 163 +++++++ Vulnerability_Tool_V2/scanner_v2.py | 226 +++++---- 8 files changed, 551 insertions(+), 684 deletions(-) create mode 100644 Vulnerability_Tool_V2/plugins/jwt_security/__init__.py create mode 100644 Vulnerability_Tool_V2/plugins/rls_security/__init__.py create mode 100644 Vulnerability_Tool_V2/plugins/rls_security_disabled/rls_missing.py diff --git a/Vulnerability_Tool_V2/config/scanner_config.yaml b/Vulnerability_Tool_V2/config/scanner_config.yaml index b5f9013..8239ee7 100644 --- a/Vulnerability_Tool_V2/config/scanner_config.yaml +++ b/Vulnerability_Tool_V2/config/scanner_config.yaml @@ -1,132 +1,89 @@ -# NutriHelp Security Scanner V2.0 Configuration -scanner: - name: "NutriHelp Security Scanner V2.0" - version: "2.0.0" - description: "Specialized security scanner for NutriHelp project" - - # Scan Settings - scan_settings: - max_file_size_mb: 50 - timeout_seconds: 300 - parallel_scanning: false - - # Supported File Extensions - file_extensions: - - .js - - .ts - - .py - - .sql - - .json - - .yaml - - .yml - - .env - - # Excluded Directories - exclude_directories: - - node_modules - - .git - - __pycache__ - - venv - - .venv - - dist - - build - - uploads - - temp - -# Plugin Configuration +logging: + file_output: false + file_path: logs/scanner.log + format: '%(asctime)s - %(name)s - %(levelname)s - %(message)s' + level: INFO plugins: - # JWT Security Plugin - jwt_missing_protection: - enabled: true - severity_override: null - config: - # Public endpoints (do not require JWT protection) - public_endpoints: - - "/login" - - "/register" - - "/signup" - - "/health" - - "/docs" - - "/api-docs" - - "/public" - - # JWT Middleware Patterns - jwt_middleware_patterns: - - "authenticateToken" - - "verifyToken" - - "jwtAuth" - - "requireAuth" - - "checkJWT" - jwt_configuration: - enabled: true - severity_override: null config: + check_env_files: true min_secret_length: 32 - check_weak_secrets: true - validate_expiry: true - check_algorithm: true - - # RLS Security Plugin - rls_missing_protection: enabled: true - severity_override: null + jwt_missing_protection: + config: + check_middleware: true + check_routes: true + exclude_paths: + - /health + - /api-docs + enabled: true + rls_missing_protection_disabled: config: - # Sensitive tables (require RLS protection) - sensitive_tables: - - "users" - - "user_profiles" - - "auth_logs" - - "user_sessions" - - "recipes" - - "meal_plans" - - "appointments" - - "medical_predictions" - - "user_feedback" - - "notifications" - - # RLS Indicators rls_indicators: - - "auth.uid()" - - "current_user" - - "user_id" - - "auth_user" - - "rls" - - "row level security" - -# Report Settings + - 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: - # General Settings - include_source_snippets: true - max_snippet_lines: 5 - include_file_paths: true - include_timestamps: true - - # Grouping Settings - group_by_severity: true - sort_by_severity: true - - # Output Formats formats: - json: - enabled: true - indent: 2 - include_metadata: true - html: - enabled: true - template: "default" + enabled: false include_css: true include_js: false - + template: default + json: + enabled: false + include_metadata: true + indent: 2 text: - enabled: true - max_width: 120 + enabled: false include_summary: true - -# Logging Settings -logging: - level: "INFO" # DEBUG, INFO, WARNING, ERROR - format: "%(asctime)s - %(name)s - %(levelname)s - %(message)s" - file_output: false - file_path: "logs/scanner.log" \ No newline at end of file + 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/scanner_engine.py b/Vulnerability_Tool_V2/core/scanner_engine.py index e0103ca..51807be 100644 --- a/Vulnerability_Tool_V2/core/scanner_engine.py +++ b/Vulnerability_Tool_V2/core/scanner_engine.py @@ -54,8 +54,7 @@ def load_plugins(self, plugin_configs: Optional[Dict[str, Any]] = None): plugin_mappings = { 'jwt_missing_protection': 'plugins.jwt_security.jwt_missing', 'jwt_configuration': 'plugins.jwt_security.jwt_config', - 'rls_missing_protection': 'plugins.rls_security.rls_missing', - # can add more plugins + # RLS plugin removed to fix dependency issues } for plugin_name, module_path in plugin_mappings.items(): @@ -137,25 +136,33 @@ def scan_target(self, target_path: str) -> Dict: if findings: # Process each finding for finding in findings: - # Generate and add recommendation - 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 + # Prefer plugin-provided recommendation; generate only if missing/empty + existing_rec = None if hasattr(finding, 'recommendation'): - finding.recommendation = recommendation - # If finding is a dictionary + existing_rec = getattr(finding, 'recommendation') elif isinstance(finding, dict): - finding['recommendation'] = recommendation + 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 finding.plugin: + if hasattr(finding, 'plugin') and not getattr(finding, 'plugin', None): finding.plugin = plugin.__class__.__name__ - if hasattr(finding, 'file_path') and not finding.file_path: + 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}") 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_missing.py b/Vulnerability_Tool_V2/plugins/jwt_security/jwt_missing.py index d1f439f..4b06a05 100644 --- a/Vulnerability_Tool_V2/plugins/jwt_security/jwt_missing.py +++ b/Vulnerability_Tool_V2/plugins/jwt_security/jwt_missing.py @@ -1,56 +1,85 @@ #!/usr/bin/env python3 """ -JWT Missing Protection Plugin - Updated for NutriHelp's actual architecture -Implementing a custom detection plugin based on existing JWT architecture +JWT Missing Protection Plugin +Detecting API endpoints missing JWT protection """ import os import re -import glob -import fnmatch -from typing import List, Dict, Any -from ..base_plugin import BaseSecurityPlugin, SecurityFinding - +import logging +from typing import List, Dict, Any, Optional +from plugins.base_plugin import BaseSecurityPlugin, SecurityFinding class JWTMissingProtectionPlugin(BaseSecurityPlugin): - """Detects API endpoints missing JWT protection - Optimized for NutriHelp's actual architecture""" - - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - self._findings_cache = set() + """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 { - 'name': 'JWT Missing Protection Detector', - 'version': '2.0.1', - 'description': 'Detects API endpoints missing JWT authentication middleware (NutriHelp optimized)', - 'author': 'NutriHelp Security Team' + "id": "jwt_missing_protection", + "name": self.name, + "version": self.version, + "description": self.description, } - + def get_severity_level(self) -> str: - return "HIGH" - - def scan(self, target_path: str) -> List[SecurityFinding]: - """Scan for missing JWT protection.""" + return "medium" + + def scan(self, target_path: str = None) -> List[SecurityFinding]: + """Scan the target path for missing JWT protection endpoints""" findings = [] - for route_file in self._find_route_files(target_path): - self._analyze_route_file(route_file, target_path) + if not target_path or not os.path.exists(target_path): + return findings - return self.findings # Return all collected 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 _analyze_route_file(self, file_path: str, base_path: str): - """Analyze a single route file.""" + def _scan_file(self, file_path: str, base_path: str) -> List[SecurityFinding]: + """Scan a single file""" + findings = [] + try: - content = self.read_file_safe(file_path) - if not content: - return + with open(file_path, 'r', encoding='utf-8', errors='ignore') as f: + content = f.read() + lines = content.split('\n') - lines = content.split('\n') - relative_path = self.get_relative_path(file_path, base_path) + relative_path = os.path.relpath(file_path, base_path) + # Check route definitions route_patterns = [ - r'router\.(get|post|put|delete|patch)\s*\(\s*[\'"`]([^\'"`]+)[\'"`]' + 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): @@ -58,296 +87,98 @@ def _analyze_route_file(self, file_path: str, base_path: str): matches = re.finditer(pattern, line, re.IGNORECASE) for match in matches: - method = match.group(1).upper() - path = match.group(2) - + 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): - severity = self._determine_severity(path, method, os.path.basename(file_path)) - recommendation = self._get_recommendation(method, path) - - self.add_finding( - title=f"Missing JWT Protection: {method} {path}", - description=f"API endpoint {method} {path} in {os.path.basename(file_path)} lacks JWT authentication middleware. Based on your current architecture, this should use authenticateToken middleware.", + 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=severity, - recommendation=recommendation + severity="MEDIUM", + plugin=self.__class__.__name__, + recommendation=self._get_recommendation(endpoint, method) ) - - except Exception as e: - self.logger.error(f"Error analyzing route file {file_path}: {e}") - - def _check_line_for_unprotected_routes(self, line: str, all_lines: List[str], - line_number: int, file_path: str, - route_patterns: List[str], filename: str): - """Check for unprotected routes in a single line of code - based on existing middleware names""" + findings.append(finding) - 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() if match.group(1) else 'USE' - endpoint = match.group(2) - - # Handling different endpoint formats - if not endpoint.startswith('/'): - endpoint = '/' + endpoint - else: - continue - - # Skip explicitly public endpoints - if self._is_public_endpoint(endpoint, filename): - continue + except Exception as e: + self.logger.error(f"Error occurred while scanning file {file_path}: {e}") - # Check for JWT protection - using existing middleware names - if not self._has_jwt_protection(line, all_lines, line_number): - severity = self._determine_severity(endpoint, method, filename) - recommendation = self._get_recommendation(endpoint, method) - - self.add_finding( - title=f"Missing JWT Protection: {method} {endpoint}", - description=f"API endpoint {method} {endpoint} in {filename} lacks JWT authentication middleware. " - f"Based on your current architecture, this should use authenticateToken middleware.", - file_path=file_path, - line_number=line_number, - severity=severity, - recommendation=recommendation - ) - - def _is_public_endpoint(self, endpoint: str, filename: str) -> bool: - """Check if an endpoint should be public - based on existing route structure""" + return findings - # Based on filename, determine public endpoints - if filename in ['login.js', 'signup.js']: - return True + 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) - # Explicit public endpoints (based on existing auth.js) - public_endpoints = [ - '/register', '/login', '/health', '/api-docs', '/docs', - '/public', '/static', '/uploads', '/log-login', '/log-login-attempt' + 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' ] - endpoint_lower = endpoint.lower() - - # Exact match - if endpoint_lower in [ep.lower() for ep in public_endpoints]: - return True - - # Prefix match - public_prefixes = ['/public/', '/static/', '/docs/', '/uploads/', '/api-docs/'] - if any(endpoint_lower.startswith(prefix) for prefix in public_prefixes): + line_lower = line.lower() + if any(pattern.lower() in line_lower for pattern in jwt_patterns): return True - # Health check endpoints - if any(pattern in endpoint_lower for pattern in ['/health', '/ping', '/status']): - return True + # Check surrounding lines + start = max(0, line_number - 3) + end = min(len(all_lines), line_number + 3) - return False - - def _has_jwt_protection(self, current_line: str, all_lines: List[str], line_number: int) -> bool: - """Check if route has JWT protection.""" - # Predefined exemption routes - exempt_routes = [ - '/health', - '/status', - '/login', - '/register', - '/public', - '/docs' - ] - - # Check if it's an exempt route - if any(route in current_line for route in exempt_routes): - return True - - # Check for JWT protection in context - context_start = max(0, line_number - 5) - context_end = min(len(all_lines), line_number + 5) - context = '\n'.join(all_lines[context_start:context_end]) - - # JWT protection patterns - protection_patterns = [ - 'authenticateToken', - 'requireAuth', - 'isAuthenticated', - 'checkJwt', - 'verifyToken' - ] - - # Check if the route has JWT protection - return any(pattern in context for pattern in protection_patterns) - - def _determine_severity(self, endpoint: str, method: str, filename: str) -> str: - """Determine severity based on endpoint and method.""" - endpoint_lower = endpoint.lower() - - # CRITICAL - Involves user data and sensitive operations - if any(sensitive in endpoint_lower for sensitive in [ - 'user', 'profile', 'password', 'admin', 'token', - 'auth', 'key', 'secret', 'credential' - ]): - return "CRITICAL" - - # HIGH - Data modification operations - if method in ['POST', 'PUT', 'DELETE', 'PATCH'] and not any( - safe in endpoint_lower for safe in [ - 'login', 'register', 'public', 'health' - ] - ): - return "HIGH" - - # MEDIUM - Data reading operations - if method == 'GET' and any(sensitive in endpoint_lower for sensitive in [ - 'user', 'data', 'profile', 'report', 'log' - ]): - return "MEDIUM" - - # LOW - Other operations - if method == 'GET' and any(public in endpoint_lower for public in [ - 'public', 'health', 'status', 'version' - ]): - return "LOW" - - # Default to MEDIUM - return "MEDIUM" - - def _get_recommendation(self, method: str, endpoint: str) -> str: - """Generate specific recommendation.""" - return f"""To fix this JWT protection issue, add the authenticateToken middleware: - -1. Import the middleware (if not already imported): - const {{ authenticateToken }} = require('../middleware/authenticateToken'); - -2. Add middleware to the route: - router.{method.lower()}('{endpoint}', authenticateToken, (req, res) => {{ ... }}); - -3. For optional authentication, you can use: - const {{ optionalAuth }} = require('../middleware/authenticateToken'); - -4. Your current JWT setup uses: - - Access tokens (15 minutes expiry) - - Refresh tokens (7 days expiry) - - Proper error handling with specific error codes""" - - def _find_route_files(self, base_path: str) -> List[str]: - """Find all route files in the project.""" - route_files = set() # Use collection deduplication - - # Define directories and file patterns to scan - scan_patterns = [ - 'routes/*.js', # Main route directory - 'src/routes/*.js', # Routes under src - 'api/routes/*.js', # Routes under api - '**/routes/*.js', # Routes directory at any depth - ] - - # Define patterns to exclude - exclude_patterns = [ - '**/node_modules/**', # Exclude node_modules - '**/test/**', # Exclude test files - '**/tests/**', - '**/mock/**', # Exclude mock files - '**/*.test.js', - '**/*.spec.js' - ] - - try: - for pattern in scan_patterns: - full_pattern = os.path.join(base_path, pattern) - matches = glob.glob(full_pattern, recursive=True) - - # Filter out excluded files - filtered_matches = [ - f for f in matches - if not any(fnmatch.fnmatch(f, os.path.join(base_path, ep)) - for ep in exclude_patterns) - ] - - route_files.update(filtered_matches) + 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 - self.logger.info(f"Found {len(route_files)} route files to scan") - - except Exception as e: - self.logger.error(f"Error finding route files: {e}") - - return list(route_files) - - def _cache_key(self, finding: dict) -> str: - """Generate a unique key for finding.""" - return f"{finding['file_path']}:{finding['line_number']}:{finding['title']}" - - def add_finding(self, **kwargs): - """Add finding with deduplication.""" - cache_key = self._cache_key(kwargs) - - if cache_key not in self._findings_cache: - self._findings_cache.add(cache_key) - self.findings.append(SecurityFinding(**kwargs)) - - def generate_recommendation(self, route_info: dict) -> str: - """Generate specific recommendation based on route info""" - method = route_info['method'] - path = route_info['path'] - file_name = os.path.basename(route_info.get('file_path', '')) - - # Generate specific recommendations for different types of routes - if 'user' in path.lower() or 'profile' in path.lower(): - return f"""This endpoint ({method} {path}) handles user data and requires strong authentication: - -1. Import the JWT middleware: - const {{ authenticateToken }} = require('../middleware/authenticateToken'); - -2. Add strict authentication: - router.{method.lower()}('{path}', authenticateToken, (req, res) => {{ - // Verify user ID matches authenticated user - if (req.user.id !== req.params.userId) {{ - return res.status(403).json({{ error: 'Unauthorized access' }}); - }} - // ... rest of your code - }});""" - - elif method in ['POST', 'PUT', 'DELETE']: - return f"""This endpoint ({method} {path}) modifies data and requires authentication: - -1. Import the JWT middleware: - const {{ authenticateToken }} = require('../middleware/authenticateToken'); - -2. Add authentication to protect data modification: - router.{method.lower()}('{path}', authenticateToken, yourController); - -3. Verify request in controller: - function yourController(req, res) {{ - // Ensure user has required permissions - if (!req.user.permissions.includes('{path.split("/")[1]}')) {{ - return res.status(403).json({{ error: 'Insufficient permissions' }}); - }} - // ... rest of your code - }}""" + return False - else: - return f"""Add JWT authentication to protect this endpoint: + def _get_recommendation(self, endpoint: str, method: str) -> str: + """Get fix recommendation""" + return f"""To protect the {method} {endpoint} endpoint: -1. Import the middleware: - const {{ authenticateToken }} = require('../middleware/authenticateToken'); +1. Import authentication middleware: + const authenticateToken = require('../middleware/authenticateToken'); 2. Add middleware to route: - router.{method.lower()}('{path}', authenticateToken, (req, res) => {{ ... }}); + router.{method.lower()}('{endpoint}', authenticateToken, (req, res) => {{ + // Your route handler + }}); -3. Consider using optional authentication if this is a public endpoint: - const {{ optionalAuth }} = require('../middleware/authenticateToken'); - router.{method.lower()}('{path}', optionalAuth, (req, res) => {{ ... }});""" +3. Ensure JWT configuration is secure: + - Use strong secrets + - Set appropriate expiration + - Handle errors properly""" + def run(self, target_path: str = None) -> List[SecurityFinding]: + """Backward compatibility method""" + return self.scan(target_path) -# Test function -def test_plugin(): - """Test plugin basic functionality""" - plugin = JWTMissingProtectionPlugin() - - print("Plugin Info:", plugin.get_plugin_info()) - print("Severity Level:", plugin.get_severity_level()) - print("โœ… Updated JWT Missing Protection Plugin initialized successfully") +# 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 index 8cbf293..f676d06 100644 --- a/Vulnerability_Tool_V2/plugins/rls_security/rls_missing.py +++ b/Vulnerability_Tool_V2/plugins/rls_security/rls_missing.py @@ -1,128 +1,23 @@ +#!/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. +Minimal RLS Missing Protection Plugin +Minimized RLS plugin to prevent dependency errors """ -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 -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") - -# --- add a small wrapper so findings provide a to_dict() method expected by the engine --- -class Finding: - """ๅŒ…่ฃ…findingๅญ—ๅ…ธๅนถๆไพ›to_dictๆ–นๆณ•""" - def __init__(self, data: Dict): - self._data = data - self._data['plugin'] = 'RLSMissingProtectionPlugin' - # Add default recommendation - self._data['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""" - - def to_dict(self) -> Dict: - return self._data - - def get(self, key: str, default=None): - return self._data.get(key, default) - - @property - def severity(self) -> str: - return self._data.get('severity', '') - - @property - def plugin(self) -> str: - return self._data.get('plugin', 'RLSMissingProtectionPlugin') - - # Add other necessary property accessors - @property - def recommendation(self) -> str: - return self._data.get('recommendation', '') - - @recommendation.setter - def recommendation(self, value: str): - self._data['recommendation'] = value +from plugins.base_plugin import BaseSecurityPlugin, SecurityFinding +from typing import List, Dict, Any class RLSMissingProtectionPlugin(BaseSecurityPlugin): - """Plugin for detecting missing Row-Level Security (RLS) protection.""" - + """Minimized RLS Missing Protection Detection Plugin""" + 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, project_root: Optional[str] = None): - super().__init__() - self.project_root = project_root or os.getcwd() - - def metadata(self) -> Dict[str, str]: - return {"name": self.name, "version": self.version, "description": self.description} + description = "Minimal RLS protection detector to prevent dependency errors" - def _is_target_file(self, path: str) -> bool: - return any(path.lower().endswith(ext) for ext in self._target_extensions) + def __init__(self, config: Dict[str, Any] = None): + super().__init__(config or {}) - def _scan_file(self, path: str) -> List[Finding]: - 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): - findings.append(Finding({ - "id": f"rls-001:{os.path.relpath(path, self.project_root)}:{i}", - "title": "Possible RLS-related statement found", - "severity": "info", - "description": f"Pattern '{pat.pattern}' matched.", - "file": os.path.relpath(path, self.project_root), - "line": i, - "match": line.strip(), - })) - break - except Exception as e: - logger.debug("Failed to read %s: %s", path, e) - return findings - - # ---------- New: Abstract interface for loaders ---------- def get_plugin_info(self) -> Dict[str, str]: - """Return plugin information (for loader/UI use)""" return { "id": "rls_missing_protection", "name": self.name, @@ -131,56 +26,16 @@ def get_plugin_info(self) -> Dict[str, str]: } def get_severity_level(self) -> str: - """Default severity level (used when no clear evidence is found)""" - return "medium" - - def scan(self, target_path: Optional[str] = None) -> List[Finding]: - """ - Run the RLS detection. Accepts optional target_path to be compatible with - engine calls (engine may call plugin.scan(target_path)). - """ - 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: - findings.append(Finding({ - "id": "rls-000", - "title": "Potential missing Rowโ€‘Level Security (RLS)", - "severity": self.get_severity_level(), - "description": ( - "No obvious RLS-related configuration or SQL statements were detected. " - "Ensure that sensitive tables enforce row-level access controls (policies)." - ), - "file": None, - "line": None, - })) - - logger.info("RLS detector finished, findings: %d", len(findings)) - return findings + return "low" - # Keep run() for backward compatibility and call scan() - def run(self) -> List[object]: - return self.scan() + 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) -# Compatible exports / convenience factory + module instance +# Export plugin class 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/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/scanner_v2.py b/Vulnerability_Tool_V2/scanner_v2.py index 8d003ab..f7fa1bf 100644 --- a/Vulnerability_Tool_V2/scanner_v2.py +++ b/Vulnerability_Tool_V2/scanner_v2.py @@ -8,6 +8,7 @@ import sys import argparse import json +import re import logging from pathlib import Path @@ -213,7 +214,7 @@ def generate_summary_report(scan_results: dict) -> str: def generate_html_report(scan_results: dict, config_manager: ConfigManager) -> str: - """Generate HTML report""" + """Generate HTML report with improved formatting and better recommendations""" summary = scan_results['summary'] findings = scan_results['findings'] scan_info = scan_results['scan_info'] @@ -239,84 +240,118 @@ def generate_html_report(scan_results: dict, config_manager: ConfigManager) -> s background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 30px; text-align: center; }} - .header h1 {{ font-size: 2.5rem; margin-bottom: 10px; }} - .header .meta {{ opacity: 0.9; font-size: 1.1rem; }} - - .summary {{ - padding: 30px; background: #f8f9fa; - display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); - gap: 20px; border-bottom: 2px solid #e9ecef; + .header h1 {{ font-size: 2.5em; margin-bottom: 10px; }} + .header .meta {{ opacity: 0.9; font-size: 1.1em; }} + .stats {{ + display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); + gap: 20px; padding: 30px; background: #f8f9fa; }} - .summary-card {{ - background: white; padding: 25px; border-radius: 10px; text-align: center; - box-shadow: 0 2px 4px rgba(0,0,0,0.1); border-left: 4px solid; + .stat-item {{ + text-align: center; padding: 20px; background: white; + border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }} - .summary-card.critical {{ border-left-color: #dc3545; }} - .summary-card.high {{ border-left-color: #fd7e14; }} - .summary-card.medium {{ border-left-color: #ffc107; }} - .summary-card.low {{ border-left-color: #28a745; }} - .summary-card h3 {{ font-size: 2rem; margin-bottom: 10px; }} - .summary-card p {{ color: #6c757d; font-weight: 500; }} - + .stat-number {{ font-size: 2.5em; font-weight: bold; margin-bottom: 5px; }} + .stat-label {{ color: #666; font-size: 1.1em; }} + .critical {{ color: #dc3545; }} + .high {{ color: #fd7e14; }} + .medium {{ color: #ffc107; }} + .low {{ color: #28a745; }} .content {{ padding: 30px; }} .section-title {{ - font-size: 1.8rem; color: #2c3e50; margin: 30px 0 20px 0; - border-bottom: 2px solid #3498db; padding-bottom: 10px; + font-size: 1.8em; margin-bottom: 20px; color: #2c3e50; + border-bottom: 3px solid #667eea; padding-bottom: 10px; }} - .finding {{ - margin: 20px 0; padding: 25px; border: 1px solid #dee2e6; - border-radius: 10px; transition: transform 0.2s ease; + border: 1px solid #dee2e6; border-radius: 8px; + margin-bottom: 20px; overflow: hidden; transition: transform 0.2s ease; }} .finding:hover {{ transform: translateY(-2px); box-shadow: 0 4px 8px rgba(0,0,0,0.1); }} - .finding.critical {{ border-left: 5px solid #dc3545; background: #fdf2f2; }} - .finding.high {{ border-left: 5px solid #fd7e14; background: #fef8f3; }} - .finding.medium {{ border-left: 5px solid #ffc107; background: #fffdf0; }} - .finding.low {{ border-left: 5px solid #28a745; background: #f0f9f0; }} - - .finding-header {{ display: flex; justify-content: between; align-items: center; margin-bottom: 15px; }} - .finding-title {{ font-size: 1.3rem; font-weight: bold; color: #2c3e50; }} + .finding-header {{ + padding: 15px 20px; display: flex; + justify-content: space-between; align-items: center; + background: #f8f9fa; border-bottom: 1px solid #dee2e6; + }} + .finding-title {{ + font-size: 1.2em; font-weight: bold; color: #2c3e50; + margin: 0; flex-grow: 1; + }} .severity {{ - display: inline-block; padding: 6px 12px; border-radius: 20px; - font-size: 0.8rem; font-weight: bold; text-transform: uppercase; + padding: 5px 15px; border-radius: 20px; + color: white; font-weight: bold; font-size: 0.9em; + text-transform: uppercase; margin-left: 15px; }} - .severity.critical {{ background: #dc3545; color: white; }} - .severity.high {{ background: #fd7e14; color: white; }} - .severity.medium {{ background: #ffc107; color: black; }} - .severity.low {{ background: #28a745; color: white; }} + .severity.critical {{ background: #dc3545; }} + .severity.high {{ background: #fd7e14; }} + .severity.medium {{ background: #ffc107; color: #333; }} + .severity.low {{ background: #28a745; }} + .severity.info {{ background: #17a2b8; }} .file-info {{ - background: #f8f9fa; padding: 10px 15px; border-radius: 6px; - font-family: 'Courier New', monospace; font-size: 0.9rem; margin: 10px 0; + padding: 12px 20px; background: #e9ecef; + font-family: 'Courier New', monospace; font-size: 0.9em; + color: #495057; border-bottom: 1px solid #dee2e6; + display: flex; align-items: center; }} - .description {{ color: #495057; margin: 15px 0; }} + .file-info .file-icon {{ + margin-right: 8px; color: #6c757d; + }} + + .description {{ + padding: 20px; color: #495057; + background: white; font-size: 1em; + border-bottom: 1px solid #f1f3f4; + }} + .recommendation {{ - background: #e3f2fd; border-left: 4px solid #2196f3; padding: 15px; - border-radius: 4px; margin-top: 15px; + padding: 20px; background: #e3f2fd; + border-left: 4px solid #2196f3; + color: #0d47a1; position: relative; + }} + .recommendation strong {{ + color: #1976d2; font-size: 1.1em; + display: block; margin-bottom: 10px; + }} + .recommendation .rec-section {{ + margin: 15px 0; + }} + .recommendation .rec-section h4 {{ + color: #1976d2; margin-bottom: 8px; font-size: 1.05em; + }} + .recommendation .rec-code {{ + background: #f5f5f5; padding: 12px; border-radius: 4px; + font-family: 'Courier New', monospace; font-size: 0.9em; + color: #333; margin: 8px 0; overflow-x: auto; + border: 1px solid #ddd; + }} + .recommendation ol, .recommendation ul {{ + margin: 10px 0 10px 20px; + }} + .recommendation li {{ + margin: 5px 0; }} - .recommendation strong {{ color: #1976d2; }} - .no-issues {{ - text-align: center; padding: 60px; color: #28a745; - background: #f0f9f0; border-radius: 10px; margin: 20px 0; + .plugin-info {{ + padding: 8px 20px; background: #f8f9fa; + font-size: 0.85em; color: #6c757d; + text-align: right; border-top: 1px solid #e9ecef; }} - .no-issues h2 {{ font-size: 2rem; margin-bottom: 10px; }} + .no-issues {{ + text-align: center; padding: 60px 20px; + background: #d4edda; color: #155724; border-radius: 8px; + }} + .no-issues h2 {{ font-size: 2em; margin-bottom: 15px; }} .footer {{ - background: #2c3e50; color: white; text-align: center; - padding: 20px; margin-top: 30px; + text-align: center; padding: 30px; + background: #2c3e50; color: white; }} - .footer a {{ color: #3498db; text-decoration: none; }} - .footer a:hover {{ text-decoration: underline; }} + .footer p {{ margin: 5px 0; }} - .stats {{ - background: #e8f4fd; padding: 20px; border-radius: 8px; - margin: 20px 0; display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); - gap: 15px; + @media (max-width: 768px) {{ + .finding-header {{ flex-direction: column; align-items: flex-start; }} + .severity {{ margin-left: 0; margin-top: 10px; }} + .stats {{ grid-template-columns: 1fr 1fr; }} }} - .stat-item {{ text-align: center; }} - .stat-number {{ font-size: 1.5rem; font-weight: bold; color: #2c3e50; }} - .stat-label {{ color: #6c757d; font-size: 0.9rem; }} @@ -324,28 +359,28 @@ def generate_html_report(scan_results: dict, config_manager: ConfigManager) -> s

๐Ÿ”’ NutriHelp Security Scanner V2.0

-

Scan time: {timestamp}

-

Target path: {target_path}

-

Scanner version: {scanner_version}

+
Scan time: {timestamp}
+
Target path: {target_path}
+
Scanner version: {scanner_version}
-
-
-

{critical_count}

-

Critical Issues

+
+
+
{critical_count}
+
Critical Issues
-
-

{high_count}

-

High Severity

+
+
{high_count}
+
High Severity
-
-

{medium_count}

-

Medium Severity

+
+
{medium_count}
+
Medium Severity
-
-

{low_count}

-

Low Severity

+
+
{low_count}
+
Low Severity
@@ -377,7 +412,7 @@ def generate_html_report(scan_results: dict, config_manager: ConfigManager) -> s """ - # Generate HTML for discovery + # Generate HTML for findings if not findings: findings_html = '

โœ… No Security Issues Found!

Your codebase has passed all security checks.

' else: @@ -385,54 +420,71 @@ def generate_html_report(scan_results: dict, config_manager: ConfigManager) -> s # Sort by severity sorted_findings = sorted(findings, key=lambda x: { - 'CRITICAL': 0, 'HIGH': 1, 'MEDIUM': 2, 'LOW': 3 + '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 with proper HTML structure recommendation = finding.get('recommendation', 'Please review this security issue and take appropriate remediation steps.') + formatted_recommendation = recommendation.replace("\n\n", "

").replace("\n", "
") if not recommendation.startswith("

") else recommendation finding_html = f""" -

+
{finding['title']}
{finding['severity']}
- ๐Ÿ“ {finding['file_path']} + ๐Ÿ“„ + {finding['file_path']} {f" (Line {finding['line_number']})" if finding.get('line_number') else ''}
{finding['description']}
- ๐Ÿ’ก Recommendation: {recommendation} + ๐Ÿ’ก Recommendation: + {formatted_recommendation}
- {f"
Plugin: {finding['plugin']}
" if finding.get('plugin') else ''} +
+ Plugin: {finding.get('plugin_name', finding.get('plugin', 'Unknown'))} +
""" findings_html += finding_html - # Format timestamp + # Format timestamp safely from datetime import datetime + + timestamp = ( + scan_results.get('timestamp') or + scan_info.get('timestamp') or + datetime.now().isoformat() + ) + try: - timestamp_obj = datetime.fromisoformat(scan_info['timestamp'].replace('Z', '+00:00')) + 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: - formatted_timestamp = scan_info['timestamp'] + except Exception: + formatted_timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S') return html_template.format( timestamp=formatted_timestamp, - target_path=scan_info['target_path'], - scanner_version=scan_info['scanner_version'], + target_path=scan_info.get('target_path', '../'), + scanner_version=scan_info.get('scanner_version', '2.0.0'), critical_count=summary['by_severity'].get('CRITICAL', 0), high_count=summary['by_severity'].get('HIGH', 0), medium_count=summary['by_severity'].get('MEDIUM', 0), low_count=summary['by_severity'].get('LOW', 0), - files_scanned=scan_info['stats']['files_scanned'], - plugins_used=scan_info['stats']['plugins_loaded'], + files_scanned=scan_info.get('stats', {}).get('files_scanned', 0), + plugins_used=scan_info.get('stats', {}).get('plugins_loaded', 0), total_findings=summary['total'], findings_html=findings_html ) From 37015cc379b8fcb6df6cfd7cf3b7038c0fb3a566 Mon Sep 17 00:00:00 2001 From: ChaohuiLi0321 Date: Sun, 7 Sep 2025 09:01:00 +1000 Subject: [PATCH 19/39] Update - Ensured that the report generated by command scan is consistent with the report generated by scanning in Swagger UI. --- Vulnerability_Tool_V2/api/scanner_api.py | 91 +++--- Vulnerability_Tool_V2/core/report_renderer.py | 305 ++++++++++++++++++ Vulnerability_Tool_V2/core/scanner_engine.py | 32 +- Vulnerability_Tool_V2/plugins/base_plugin.py | 4 +- .../plugins/jwt_security/jwt_missing.py | 24 +- Vulnerability_Tool_V2/scanner_v2.py | 280 +--------------- 6 files changed, 386 insertions(+), 350 deletions(-) create mode 100644 Vulnerability_Tool_V2/core/report_renderer.py diff --git a/Vulnerability_Tool_V2/api/scanner_api.py b/Vulnerability_Tool_V2/api/scanner_api.py index cafb2a9..b573594 100644 --- a/Vulnerability_Tool_V2/api/scanner_api.py +++ b/Vulnerability_Tool_V2/api/scanner_api.py @@ -26,6 +26,20 @@ 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 @@ -253,57 +267,45 @@ async def get_scan_report(scan_id: str, format: str = "html", download: bool = F try: if format.lower() == "html": - html_or_path = generate_html_report(scan_results) + # 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) - # normalize bytes -> str - if isinstance(html_or_path, (bytes, bytearray)): + except Exception as e: + # Final fallback to Jinja template render if shared renderer throws try: - html_or_path = html_or_path.decode("utf-8") + fallback_html = generate_html_report(scan_results) + return HTMLResponse(content=fallback_html, media_type='text/html') except Exception: - html_or_path = str(html_or_path) + 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" - - # if generator returned a path-like and file exists, serve it - candidate = Path(str(html_or_path)) - if isinstance(html_or_path, str) and not html_or_path.lstrip().startswith("<") and candidate.exists(): - return FileResponse(str(candidate), media_type="text/html", filename=f"security_report_{scan_id}.html") - - # otherwise write HTML string to file and return - report_path.write_text(str(html_or_path), encoding="utf-8") + 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") - # Not download: if HTML string -> inject a download button and return inline HTML - if isinstance(html_or_path, str) and html_or_path.lstrip().startswith("<"): - download_url = f"/scanner/scan/{scan_id}/report?format=html&download=1" - # small floating button HTML - download_button = ( - f'
' - f'Download HTML' - f'
' - ) - # try to insert button before first main container div, fallback prepend - if "
" in html_or_path: - modified = html_or_path.replace("
", download_button + "
", 1) - else: - modified = download_button + html_or_path - return HTMLResponse(content=modified, media_type="text/html") - - # Otherwise treat as path-like: check if file exists and serve inline - candidate = Path(str(html_or_path)) - if candidate.exists() and candidate.is_file(): - return FileResponse(str(candidate), media_type="text/html", filename=f"security_report_{scan_id}.html") - - # Fallback: write whatever we got into reports dir and serve inline HTML - 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_or_path), 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) @@ -378,7 +380,8 @@ async def quick_scan(scan_request: ScanRequest): "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") + "plugin_name": f.get("plugin_name") or f.get("plugin"), + "recommendation": f.get("recommendation", "") } for f in findings ] @@ -390,7 +393,8 @@ async def quick_scan(scan_request: ScanRequest): "progress": 100, "message": "Quick scan completed", "request": scan_request, - "result": result + "result": result, + "raw_result": scan_results } return result @@ -434,6 +438,9 @@ async def perform_scan(scan_id: str, scan_request: ScanRequest): ] ) + # 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" 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 index 51807be..4b782e3 100644 --- a/Vulnerability_Tool_V2/core/scanner_engine.py +++ b/Vulnerability_Tool_V2/core/scanner_engine.py @@ -264,22 +264,22 @@ def get_scan_stats(self) -> Dict[str, Any]: 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 """To fix this JWT protection issue, add the authenticateToken middleware: - -1. Import the middleware (if not already imported): - const { authenticateToken } = require('../middleware/authenticateToken'); - -2. Add middleware to the route: - router.post('/', authenticateToken, (req, res) => { ... }); - -3. For optional authentication, you can use: - const { optionalAuth } = require('../middleware/authenticateToken'); - -4. Your current JWT setup uses: - - Access tokens (15 minutes expiry) - - Refresh tokens (7 days expiry) - - Proper error handling with specific error codes""" + 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 "" \ No newline at end of file + 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 index 326eb5e..cdc3e12 100644 --- a/Vulnerability_Tool_V2/plugins/base_plugin.py +++ b/Vulnerability_Tool_V2/plugins/base_plugin.py @@ -4,7 +4,7 @@ """ from abc import ABC, abstractmethod -from typing import List, Dict, Any, Optional +from typing import List, Dict, Any, Optional, Union import logging import os from datetime import datetime @@ -15,7 +15,7 @@ class SecurityFinding: def __init__(self, title: str, severity: str, file_path: str, description: str, line_number: Optional[int] = None, - plugin: Optional[str] = None, recommendation: Optional[str] = None): + plugin: Optional[str] = None, recommendation: Optional[Union[str, Dict[str, Any]]] = None): self.title = title self.severity = severity self.file_path = file_path diff --git a/Vulnerability_Tool_V2/plugins/jwt_security/jwt_missing.py b/Vulnerability_Tool_V2/plugins/jwt_security/jwt_missing.py index 4b06a05..85f4ee1 100644 --- a/Vulnerability_Tool_V2/plugins/jwt_security/jwt_missing.py +++ b/Vulnerability_Tool_V2/plugins/jwt_security/jwt_missing.py @@ -146,20 +146,16 @@ def _has_jwt_protection(self, line: str, all_lines: List[str], line_number: int) def _get_recommendation(self, endpoint: str, method: str) -> str: """Get fix recommendation""" - return f"""To protect the {method} {endpoint} endpoint: - -1. Import authentication middleware: - const authenticateToken = require('../middleware/authenticateToken'); - -2. Add middleware to route: - router.{method.lower()}('{endpoint}', authenticateToken, (req, res) => {{ - // Your route handler - }}); - -3. Ensure JWT configuration is secure: - - Use strong secrets - - Set appropriate expiration - - Handle errors properly""" + # 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""" diff --git a/Vulnerability_Tool_V2/scanner_v2.py b/Vulnerability_Tool_V2/scanner_v2.py index f7fa1bf..45d23ca 100644 --- a/Vulnerability_Tool_V2/scanner_v2.py +++ b/Vulnerability_Tool_V2/scanner_v2.py @@ -17,6 +17,7 @@ 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): @@ -122,7 +123,8 @@ def format_output(scan_results: dict, output_format: str, config_manager: Config return json.dumps(scan_results, indent=2, ensure_ascii=False) elif output_format == 'html': - return generate_html_report(scan_results, config_manager) + # 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) @@ -213,281 +215,7 @@ def generate_summary_report(scan_results: dict) -> str: return '\n'.join(lines) -def generate_html_report(scan_results: dict, config_manager: ConfigManager) -> str: - """Generate HTML report with improved formatting and better recommendations""" - summary = scan_results['summary'] - findings = scan_results['findings'] - scan_info = scan_results['scan_info'] - - 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 with proper HTML structure - recommendation = finding.get('recommendation', 'Please review this security issue and take appropriate remediation steps.') - formatted_recommendation = recommendation.replace("\n\n", "

").replace("\n", "
") if not recommendation.startswith("

") else recommendation - - finding_html = f""" -

-
-
{finding['title']}
- {finding['severity']} -
- -
- ๐Ÿ“„ - {finding['file_path']} - {f" (Line {finding['line_number']})" if finding.get('line_number') else ''} -
- -
{finding['description']}
- -
- ๐Ÿ’ก Recommendation: - {formatted_recommendation} -
- -
- Plugin: {finding.get('plugin_name', finding.get('plugin', 'Unknown'))} -
-
- """ - findings_html += finding_html - - # Format timestamp safely - from datetime import datetime - - 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['by_severity'].get('CRITICAL', 0), - high_count=summary['by_severity'].get('HIGH', 0), - medium_count=summary['by_severity'].get('MEDIUM', 0), - low_count=summary['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['total'], - findings_html=findings_html - ) + # CLI previously had a large in-file renderer; replaced by shared renderer def write_output_file(content: str, file_path: str, output_format: str): From ca3e920d55c50b81417f9a8a9b78f612a686bfad Mon Sep 17 00:00:00 2001 From: ChaohuiLi0321 Date: Sun, 7 Sep 2025 09:04:05 +1000 Subject: [PATCH 20/39] Use the command "python scanner_v2.py --target ../ --format html --output security_report.html --verbose" to generate a debugged report --- .../nutrihelp_jwt_security_report.html | 1263 --------- Vulnerability_Tool_V2/security_report.html | 2368 +++++++++++++++++ 2 files changed, 2368 insertions(+), 1263 deletions(-) delete mode 100644 Vulnerability_Tool_V2/nutrihelp_jwt_security_report.html create mode 100644 Vulnerability_Tool_V2/security_report.html diff --git a/Vulnerability_Tool_V2/nutrihelp_jwt_security_report.html b/Vulnerability_Tool_V2/nutrihelp_jwt_security_report.html deleted file mode 100644 index dc77831..0000000 --- a/Vulnerability_Tool_V2/nutrihelp_jwt_security_report.html +++ /dev/null @@ -1,1263 +0,0 @@ - - - - - - - NutriHelp Security Scanner V2.0 Report - - - -
-
-

๐Ÿ”’ NutriHelp Security Scanner V2.0

-
-

Scan time: 2025-09-05 23:44:45

-

Target path: ../

-

Scanner version: 2.0.0

-
-
- -
-
-

2

-

Critical Issues

-
-
-

16

-

High Severity

-
-
-

10

-

Medium Severity

-
-
-

1

-

Low Severity

-
-
- -
-
-
-
840
-
Files Scanned
-
-
-
2
-
Plugins Used
-
-
-
29
-
Total Issues
-
-
- -

๐Ÿ” Detailed Findings

-
-
-
Missing JWT Protection: PUT /update-by-identifier
- CRITICAL -
- -
- ๐Ÿ“ routes/userprofile.js - (Line 14) -
- -
API endpoint PUT /update-by-identifier in userprofile.js lacks JWT authentication middleware. Based on your current architecture, this should use authenticateToken middleware.
- -
- ๐Ÿ’ก Recommendation: To fix this JWT protection issue, add the authenticateToken middleware: - -1. Import the middleware (if not already imported): - const { authenticateToken } = require('../middleware/authenticateToken'); - -2. Add middleware to the route: - router.put('/update-by-identifier', authenticateToken, (req, res) => { ... }); - - Or if using a controller: - router.put('/update-by-identifier', authenticateToken, controllerFunction); - -3. For optional authentication, you can use: - const { optionalAuth } = require('../middleware/authenticateToken'); - router.put('/update-by-identifier', optionalAuth, (req, res) => { ... }); - -4. Your current JWT setup uses: - - Access tokens (15 minutes expiry) - - Refresh tokens (7 days expiry) - - Proper error handling with specific error codes - -Example based on your auth.js pattern: -router.put('/update-by-identifier', authenticateToken, controllerFunction); -
- -
Plugin: JWTMissingProtectionPlugin
-
- -
-
-
Missing JWT Protection: PUT /update-by-identifier
- CRITICAL -
- -
- ๐Ÿ“ routes/userprofile.js - (Line 14) -
- -
API endpoint PUT /update-by-identifier in userprofile.js lacks JWT authentication middleware. Based on your current architecture, this should use authenticateToken middleware.
- -
- ๐Ÿ’ก Recommendation: To fix this JWT protection issue, add the authenticateToken middleware: - -1. Import the middleware (if not already imported): - const { authenticateToken } = require('../middleware/authenticateToken'); - -2. Add middleware to the route: - router.put('/update-by-identifier', authenticateToken, (req, res) => { ... }); - - Or if using a controller: - router.put('/update-by-identifier', authenticateToken, controllerFunction); - -3. For optional authentication, you can use: - const { optionalAuth } = require('../middleware/authenticateToken'); - router.put('/update-by-identifier', optionalAuth, (req, res) => { ... }); - -4. Your current JWT setup uses: - - Access tokens (15 minutes expiry) - - Refresh tokens (7 days expiry) - - Proper error handling with specific error codes - -Example based on your auth.js pattern: -router.put('/update-by-identifier', authenticateToken, controllerFunction); -
- -
Plugin: JWTMissingProtectionPlugin
-
- -
-
-
Missing JWT Protection: POST /
- HIGH -
- -
- ๐Ÿ“ routes/imageClassification.js - (Line 19) -
- -
API endpoint POST / in imageClassification.js lacks JWT authentication middleware. Based on your current architecture, this should use authenticateToken middleware.
- -
- ๐Ÿ’ก Recommendation: To fix this JWT protection issue, add the authenticateToken middleware: - -1. Import the middleware (if not already imported): - const { authenticateToken } = require('../middleware/authenticateToken'); - -2. Add middleware to the route: - router.post('/', authenticateToken, (req, res) => { ... }); - - Or if using a controller: - router.post('/', authenticateToken, controllerFunction); - -3. For optional authentication, you can use: - const { optionalAuth } = require('../middleware/authenticateToken'); - router.post('/', optionalAuth, (req, res) => { ... }); - -4. Your current JWT setup uses: - - Access tokens (15 minutes expiry) - - Refresh tokens (7 days expiry) - - Proper error handling with specific error codes - -Example based on your auth.js pattern: -router.post('/', authenticateToken, controllerFunction); -
- -
Plugin: JWTMissingProtectionPlugin
-
- -
-
-
Missing JWT Protection: POST /
- HIGH -
- -
- ๐Ÿ“ routes/upload.js - (Line 5) -
- -
API endpoint POST / in upload.js lacks JWT authentication middleware. Based on your current architecture, this should use authenticateToken middleware.
- -
- ๐Ÿ’ก Recommendation: To fix this JWT protection issue, add the authenticateToken middleware: - -1. Import the middleware (if not already imported): - const { authenticateToken } = require('../middleware/authenticateToken'); - -2. Add middleware to the route: - router.post('/', authenticateToken, (req, res) => { ... }); - - Or if using a controller: - router.post('/', authenticateToken, controllerFunction); - -3. For optional authentication, you can use: - const { optionalAuth } = require('../middleware/authenticateToken'); - router.post('/', optionalAuth, (req, res) => { ... }); - -4. Your current JWT setup uses: - - Access tokens (15 minutes expiry) - - Refresh tokens (7 days expiry) - - Proper error handling with specific error codes - -Example based on your auth.js pattern: -router.post('/', authenticateToken, controllerFunction); -
- -
Plugin: JWTMissingProtectionPlugin
-
- -
-
-
Missing JWT Protection: POST /
- HIGH -
- -
- ๐Ÿ“ routes/upload.js - (Line 5) -
- -
API endpoint POST / in upload.js lacks JWT authentication middleware. Based on your current architecture, this should use authenticateToken middleware.
- -
- ๐Ÿ’ก Recommendation: To fix this JWT protection issue, add the authenticateToken middleware: - -1. Import the middleware (if not already imported): - const { authenticateToken } = require('../middleware/authenticateToken'); - -2. Add middleware to the route: - router.post('/', authenticateToken, (req, res) => { ... }); - - Or if using a controller: - router.post('/', authenticateToken, controllerFunction); - -3. For optional authentication, you can use: - const { optionalAuth } = require('../middleware/authenticateToken'); - router.post('/', optionalAuth, (req, res) => { ... }); - -4. Your current JWT setup uses: - - Access tokens (15 minutes expiry) - - Refresh tokens (7 days expiry) - - Proper error handling with specific error codes - -Example based on your auth.js pattern: -router.post('/', authenticateToken, controllerFunction); -
- -
Plugin: JWTMissingProtectionPlugin
-
- -
-
-
Missing JWT Protection: POST /
- HIGH -
- -
- ๐Ÿ“ routes/waterIntake.js - (Line 5) -
- -
API endpoint POST / in waterIntake.js lacks JWT authentication middleware. Based on your current architecture, this should use authenticateToken middleware.
- -
- ๐Ÿ’ก Recommendation: To fix this JWT protection issue, add the authenticateToken middleware: - -1. Import the middleware (if not already imported): - const { authenticateToken } = require('../middleware/authenticateToken'); - -2. Add middleware to the route: - router.post('/', authenticateToken, (req, res) => { ... }); - - Or if using a controller: - router.post('/', authenticateToken, controllerFunction); - -3. For optional authentication, you can use: - const { optionalAuth } = require('../middleware/authenticateToken'); - router.post('/', optionalAuth, (req, res) => { ... }); - -4. Your current JWT setup uses: - - Access tokens (15 minutes expiry) - - Refresh tokens (7 days expiry) - - Proper error handling with specific error codes - -Example based on your auth.js pattern: -router.post('/', authenticateToken, controllerFunction); -
- -
Plugin: JWTMissingProtectionPlugin
-
- -
-
-
Missing JWT Protection: POST /createRecipe
- HIGH -
- -
- ๐Ÿ“ routes/recipe.js - (Line 8) -
- -
API endpoint POST /createRecipe in recipe.js lacks JWT authentication middleware. Based on your current architecture, this should use authenticateToken middleware.
- -
- ๐Ÿ’ก Recommendation: To fix this JWT protection issue, add the authenticateToken middleware: - -1. Import the middleware (if not already imported): - const { authenticateToken } = require('../middleware/authenticateToken'); - -2. Add middleware to the route: - router.post('/createRecipe', authenticateToken, (req, res) => { ... }); - - Or if using a controller: - router.post('/createRecipe', authenticateToken, controllerFunction); - -3. For optional authentication, you can use: - const { optionalAuth } = require('../middleware/authenticateToken'); - router.post('/createRecipe', optionalAuth, (req, res) => { ... }); - -4. Your current JWT setup uses: - - Access tokens (15 minutes expiry) - - Refresh tokens (7 days expiry) - - Proper error handling with specific error codes - -Example based on your auth.js pattern: -router.post('/createRecipe', authenticateToken, controllerFunction); -
- -
Plugin: JWTMissingProtectionPlugin
-
- -
-
-
Missing JWT Protection: POST /
- HIGH -
- -
- ๐Ÿ“ routes/recipe.js - (Line 10) -
- -
API endpoint POST / in recipe.js lacks JWT authentication middleware. Based on your current architecture, this should use authenticateToken middleware.
- -
- ๐Ÿ’ก Recommendation: To fix this JWT protection issue, add the authenticateToken middleware: - -1. Import the middleware (if not already imported): - const { authenticateToken } = require('../middleware/authenticateToken'); - -2. Add middleware to the route: - router.post('/', authenticateToken, (req, res) => { ... }); - - Or if using a controller: - router.post('/', authenticateToken, controllerFunction); - -3. For optional authentication, you can use: - const { optionalAuth } = require('../middleware/authenticateToken'); - router.post('/', optionalAuth, (req, res) => { ... }); - -4. Your current JWT setup uses: - - Access tokens (15 minutes expiry) - - Refresh tokens (7 days expiry) - - Proper error handling with specific error codes - -Example based on your auth.js pattern: -router.post('/', authenticateToken, controllerFunction); -
- -
Plugin: JWTMissingProtectionPlugin
-
- -
-
-
Missing JWT Protection: POST /
- HIGH -
- -
- ๐Ÿ“ routes/recipe.js - (Line 10) -
- -
API endpoint POST / in recipe.js lacks JWT authentication middleware. Based on your current architecture, this should use authenticateToken middleware.
- -
- ๐Ÿ’ก Recommendation: To fix this JWT protection issue, add the authenticateToken middleware: - -1. Import the middleware (if not already imported): - const { authenticateToken } = require('../middleware/authenticateToken'); - -2. Add middleware to the route: - router.post('/', authenticateToken, (req, res) => { ... }); - - Or if using a controller: - router.post('/', authenticateToken, controllerFunction); - -3. For optional authentication, you can use: - const { optionalAuth } = require('../middleware/authenticateToken'); - router.post('/', optionalAuth, (req, res) => { ... }); - -4. Your current JWT setup uses: - - Access tokens (15 minutes expiry) - - Refresh tokens (7 days expiry) - - Proper error handling with specific error codes - -Example based on your auth.js pattern: -router.post('/', authenticateToken, controllerFunction); -
- -
Plugin: JWTMissingProtectionPlugin
-
- -
-
-
Missing JWT Protection: DELETE /
- HIGH -
- -
- ๐Ÿ“ routes/recipe.js - (Line 11) -
- -
API endpoint DELETE / in recipe.js lacks JWT authentication middleware. Based on your current architecture, this should use authenticateToken middleware.
- -
- ๐Ÿ’ก Recommendation: To fix this JWT protection issue, add the authenticateToken middleware: - -1. Import the middleware (if not already imported): - const { authenticateToken } = require('../middleware/authenticateToken'); - -2. Add middleware to the route: - router.delete('/', authenticateToken, (req, res) => { ... }); - - Or if using a controller: - router.delete('/', authenticateToken, controllerFunction); - -3. For optional authentication, you can use: - const { optionalAuth } = require('../middleware/authenticateToken'); - router.delete('/', optionalAuth, (req, res) => { ... }); - -4. Your current JWT setup uses: - - Access tokens (15 minutes expiry) - - Refresh tokens (7 days expiry) - - Proper error handling with specific error codes - -Example based on your auth.js pattern: -router.delete('/', authenticateToken, controllerFunction); -
- -
Plugin: JWTMissingProtectionPlugin
-
- -
-
-
Missing JWT Protection: DELETE /
- HIGH -
- -
- ๐Ÿ“ routes/recipe.js - (Line 11) -
- -
API endpoint DELETE / in recipe.js lacks JWT authentication middleware. Based on your current architecture, this should use authenticateToken middleware.
- -
- ๐Ÿ’ก Recommendation: To fix this JWT protection issue, add the authenticateToken middleware: - -1. Import the middleware (if not already imported): - const { authenticateToken } = require('../middleware/authenticateToken'); - -2. Add middleware to the route: - router.delete('/', authenticateToken, (req, res) => { ... }); - - Or if using a controller: - router.delete('/', authenticateToken, controllerFunction); - -3. For optional authentication, you can use: - const { optionalAuth } = require('../middleware/authenticateToken'); - router.delete('/', optionalAuth, (req, res) => { ... }); - -4. Your current JWT setup uses: - - Access tokens (15 minutes expiry) - - Refresh tokens (7 days expiry) - - Proper error handling with specific error codes - -Example based on your auth.js pattern: -router.delete('/', authenticateToken, controllerFunction); -
- -
Plugin: JWTMissingProtectionPlugin
-
- -
-
-
Missing JWT Protection: POST /classify
- HIGH -
- -
- ๐Ÿ“ routes/routes.js - (Line 32) -
- -
API endpoint POST /classify in routes.js lacks JWT authentication middleware. Based on your current architecture, this should use authenticateToken middleware.
- -
- ๐Ÿ’ก Recommendation: To fix this JWT protection issue, add the authenticateToken middleware: - -1. Import the middleware (if not already imported): - const { authenticateToken } = require('../middleware/authenticateToken'); - -2. Add middleware to the route: - router.post('/classify', authenticateToken, (req, res) => { ... }); - - Or if using a controller: - router.post('/classify', authenticateToken, controllerFunction); - -3. For optional authentication, you can use: - const { optionalAuth } = require('../middleware/authenticateToken'); - router.post('/classify', optionalAuth, (req, res) => { ... }); - -4. Your current JWT setup uses: - - Access tokens (15 minutes expiry) - - Refresh tokens (7 days expiry) - - Proper error handling with specific error codes - -Example based on your auth.js pattern: -router.post('/classify', authenticateToken, controllerFunction); -
- -
Plugin: JWTMissingProtectionPlugin
-
- -
-
-
Missing JWT Protection: POST /
- HIGH -
- -
- ๐Ÿ“ routes/userfeedback.js - (Line 8) -
- -
API endpoint POST / in userfeedback.js lacks JWT authentication middleware. Based on your current architecture, this should use authenticateToken middleware.
- -
- ๐Ÿ’ก Recommendation: To fix this JWT protection issue, add the authenticateToken middleware: - -1. Import the middleware (if not already imported): - const { authenticateToken } = require('../middleware/authenticateToken'); - -2. Add middleware to the route: - router.post('/', authenticateToken, (req, res) => { ... }); - - Or if using a controller: - router.post('/', authenticateToken, controllerFunction); - -3. For optional authentication, you can use: - const { optionalAuth } = require('../middleware/authenticateToken'); - router.post('/', optionalAuth, (req, res) => { ... }); - -4. Your current JWT setup uses: - - Access tokens (15 minutes expiry) - - Refresh tokens (7 days expiry) - - Proper error handling with specific error codes - -Example based on your auth.js pattern: -router.post('/', authenticateToken, controllerFunction); -
- -
Plugin: JWTMissingProtectionPlugin
-
- -
-
-
Missing JWT Protection: POST /
- HIGH -
- -
- ๐Ÿ“ routes/healthNews.js - (Line 156) -
- -
API endpoint POST / in healthNews.js lacks JWT authentication middleware. Based on your current architecture, this should use authenticateToken middleware.
- -
- ๐Ÿ’ก Recommendation: To fix this JWT protection issue, add the authenticateToken middleware: - -1. Import the middleware (if not already imported): - const { authenticateToken } = require('../middleware/authenticateToken'); - -2. Add middleware to the route: - router.post('/', authenticateToken, (req, res) => { ... }); - - Or if using a controller: - router.post('/', authenticateToken, controllerFunction); - -3. For optional authentication, you can use: - const { optionalAuth } = require('../middleware/authenticateToken'); - router.post('/', optionalAuth, (req, res) => { ... }); - -4. Your current JWT setup uses: - - Access tokens (15 minutes expiry) - - Refresh tokens (7 days expiry) - - Proper error handling with specific error codes - -Example based on your auth.js pattern: -router.post('/', authenticateToken, controllerFunction); -
- -
Plugin: JWTMissingProtectionPlugin
-
- -
-
-
Missing JWT Protection: PUT /
- HIGH -
- -
- ๐Ÿ“ routes/healthNews.js - (Line 214) -
- -
API endpoint PUT / in healthNews.js lacks JWT authentication middleware. Based on your current architecture, this should use authenticateToken middleware.
- -
- ๐Ÿ’ก Recommendation: To fix this JWT protection issue, add the authenticateToken middleware: - -1. Import the middleware (if not already imported): - const { authenticateToken } = require('../middleware/authenticateToken'); - -2. Add middleware to the route: - router.put('/', authenticateToken, (req, res) => { ... }); - - Or if using a controller: - router.put('/', authenticateToken, controllerFunction); - -3. For optional authentication, you can use: - const { optionalAuth } = require('../middleware/authenticateToken'); - router.put('/', optionalAuth, (req, res) => { ... }); - -4. Your current JWT setup uses: - - Access tokens (15 minutes expiry) - - Refresh tokens (7 days expiry) - - Proper error handling with specific error codes - -Example based on your auth.js pattern: -router.put('/', authenticateToken, controllerFunction); -
- -
Plugin: JWTMissingProtectionPlugin
-
- -
-
-
Missing JWT Protection: DELETE /
- HIGH -
- -
- ๐Ÿ“ routes/healthNews.js - (Line 238) -
- -
API endpoint DELETE / in healthNews.js lacks JWT authentication middleware. Based on your current architecture, this should use authenticateToken middleware.
- -
- ๐Ÿ’ก Recommendation: To fix this JWT protection issue, add the authenticateToken middleware: - -1. Import the middleware (if not already imported): - const { authenticateToken } = require('../middleware/authenticateToken'); - -2. Add middleware to the route: - router.delete('/', authenticateToken, (req, res) => { ... }); - - Or if using a controller: - router.delete('/', authenticateToken, controllerFunction); - -3. For optional authentication, you can use: - const { optionalAuth } = require('../middleware/authenticateToken'); - router.delete('/', optionalAuth, (req, res) => { ... }); - -4. Your current JWT setup uses: - - Access tokens (15 minutes expiry) - - Refresh tokens (7 days expiry) - - Proper error handling with specific error codes - -Example based on your auth.js pattern: -router.delete('/', authenticateToken, controllerFunction); -
- -
Plugin: JWTMissingProtectionPlugin
-
- -
-
-
Missing JWT Protection: POST /generate-baseline
- HIGH -
- -
- ๐Ÿ“ routes/systemRoutes.js - (Line 50) -
- -
API endpoint POST /generate-baseline in systemRoutes.js lacks JWT authentication middleware. Based on your current architecture, this should use authenticateToken middleware.
- -
- ๐Ÿ’ก Recommendation: To fix this JWT protection issue, add the authenticateToken middleware: - -1. Import the middleware (if not already imported): - const { authenticateToken } = require('../middleware/authenticateToken'); - -2. Add middleware to the route: - router.post('/generate-baseline', authenticateToken, (req, res) => { ... }); - - Or if using a controller: - router.post('/generate-baseline', authenticateToken, controllerFunction); - -3. For optional authentication, you can use: - const { optionalAuth } = require('../middleware/authenticateToken'); - router.post('/generate-baseline', optionalAuth, (req, res) => { ... }); - -4. Your current JWT setup uses: - - Access tokens (15 minutes expiry) - - Refresh tokens (7 days expiry) - - Proper error handling with specific error codes - -Example based on your auth.js pattern: -router.post('/generate-baseline', authenticateToken, controllerFunction); -
- -
Plugin: JWTMissingProtectionPlugin
-
- -
-
-
Missing JWT Protection: POST /
- HIGH -
- -
- ๐Ÿ“ routes/contactus.js - (Line 14) -
- -
API endpoint POST / in contactus.js lacks JWT authentication middleware. Based on your current architecture, this should use authenticateToken middleware.
- -
- ๐Ÿ’ก Recommendation: To fix this JWT protection issue, add the authenticateToken middleware: - -1. Import the middleware (if not already imported): - const { authenticateToken } = require('../middleware/authenticateToken'); - -2. Add middleware to the route: - router.post('/', authenticateToken, (req, res) => { ... }); - - Or if using a controller: - router.post('/', authenticateToken, controllerFunction); - -3. For optional authentication, you can use: - const { optionalAuth } = require('../middleware/authenticateToken'); - router.post('/', optionalAuth, (req, res) => { ... }); - -4. Your current JWT setup uses: - - Access tokens (15 minutes expiry) - - Refresh tokens (7 days expiry) - - Proper error handling with specific error codes - -Example based on your auth.js pattern: -router.post('/', authenticateToken, controllerFunction); -
- -
Plugin: JWTMissingProtectionPlugin
-
- -
-
-
Missing JWT Protection: GET /
- MEDIUM -
- -
- ๐Ÿ“ routes/recipeNutritionlog.js - (Line 27) -
- -
API endpoint GET / in recipeNutritionlog.js lacks JWT authentication middleware. Based on your current architecture, this should use authenticateToken middleware.
- -
- ๐Ÿ’ก Recommendation: To fix this JWT protection issue, add the authenticateToken middleware: - -1. Import the middleware (if not already imported): - const { authenticateToken } = require('../middleware/authenticateToken'); - -2. Add middleware to the route: - router.get('/', authenticateToken, (req, res) => { ... }); - - Or if using a controller: - router.get('/', authenticateToken, controllerFunction); - -3. For optional authentication, you can use: - const { optionalAuth } = require('../middleware/authenticateToken'); - router.get('/', optionalAuth, (req, res) => { ... }); - -4. Your current JWT setup uses: - - Access tokens (15 minutes expiry) - - Refresh tokens (7 days expiry) - - Proper error handling with specific error codes - -Example based on your auth.js pattern: -router.get('/', authenticateToken, controllerFunction); -
- -
Plugin: JWTMissingProtectionPlugin
-
- -
-
-
Missing JWT Protection: GET /
- MEDIUM -
- -
- ๐Ÿ“ routes/healthNews.js - (Line 44) -
- -
API endpoint GET / in healthNews.js lacks JWT authentication middleware. Based on your current architecture, this should use authenticateToken middleware.
- -
- ๐Ÿ’ก Recommendation: To fix this JWT protection issue, add the authenticateToken middleware: - -1. Import the middleware (if not already imported): - const { authenticateToken } = require('../middleware/authenticateToken'); - -2. Add middleware to the route: - router.get('/', authenticateToken, (req, res) => { ... }); - - Or if using a controller: - router.get('/', authenticateToken, controllerFunction); - -3. For optional authentication, you can use: - const { optionalAuth } = require('../middleware/authenticateToken'); - router.get('/', optionalAuth, (req, res) => { ... }); - -4. Your current JWT setup uses: - - Access tokens (15 minutes expiry) - - Refresh tokens (7 days expiry) - - Proper error handling with specific error codes - -Example based on your auth.js pattern: -router.get('/', authenticateToken, controllerFunction); -
- -
Plugin: JWTMissingProtectionPlugin
-
- -
-
-
Missing JWT Protection: GET /integrity-check
- MEDIUM -
- -
- ๐Ÿ“ routes/systemRoutes.js - (Line 59) -
- -
API endpoint GET /integrity-check in systemRoutes.js lacks JWT authentication middleware. Based on your current architecture, this should use authenticateToken middleware.
- -
- ๐Ÿ’ก Recommendation: To fix this JWT protection issue, add the authenticateToken middleware: - -1. Import the middleware (if not already imported): - const { authenticateToken } = require('../middleware/authenticateToken'); - -2. Add middleware to the route: - router.get('/integrity-check', authenticateToken, (req, res) => { ... }); - - Or if using a controller: - router.get('/integrity-check', authenticateToken, controllerFunction); - -3. For optional authentication, you can use: - const { optionalAuth } = require('../middleware/authenticateToken'); - router.get('/integrity-check', optionalAuth, (req, res) => { ... }); - -4. Your current JWT setup uses: - - Access tokens (15 minutes expiry) - - Refresh tokens (7 days expiry) - - Proper error handling with specific error codes - -Example based on your auth.js pattern: -router.get('/integrity-check', authenticateToken, controllerFunction); -
- -
Plugin: JWTMissingProtectionPlugin
-
- -
-
-
Missing JWT Protection: GET /
- MEDIUM -
- -
- ๐Ÿ“ routes/filter.js - (Line 7) -
- -
API endpoint GET / in filter.js lacks JWT authentication middleware. Based on your current architecture, this should use authenticateToken middleware.
- -
- ๐Ÿ’ก Recommendation: To fix this JWT protection issue, add the authenticateToken middleware: - -1. Import the middleware (if not already imported): - const { authenticateToken } = require('../middleware/authenticateToken'); - -2. Add middleware to the route: - router.get('/', authenticateToken, (req, res) => { ... }); - - Or if using a controller: - router.get('/', authenticateToken, controllerFunction); - -3. For optional authentication, you can use: - const { optionalAuth } = require('../middleware/authenticateToken'); - router.get('/', optionalAuth, (req, res) => { ... }); - -4. Your current JWT setup uses: - - Access tokens (15 minutes expiry) - - Refresh tokens (7 days expiry) - - Proper error handling with specific error codes - -Example based on your auth.js pattern: -router.get('/', authenticateToken, controllerFunction); -
- -
Plugin: JWTMissingProtectionPlugin
-
- -
-
-
Missing JWT Protection: GET /
- MEDIUM -
- -
- ๐Ÿ“ routes/articles.js - (Line 5) -
- -
API endpoint GET / in articles.js lacks JWT authentication middleware. Based on your current architecture, this should use authenticateToken middleware.
- -
- ๐Ÿ’ก Recommendation: To fix this JWT protection issue, add the authenticateToken middleware: - -1. Import the middleware (if not already imported): - const { authenticateToken } = require('../middleware/authenticateToken'); - -2. Add middleware to the route: - router.get('/', authenticateToken, (req, res) => { ... }); - - Or if using a controller: - router.get('/', authenticateToken, controllerFunction); - -3. For optional authentication, you can use: - const { optionalAuth } = require('../middleware/authenticateToken'); - router.get('/', optionalAuth, (req, res) => { ... }); - -4. Your current JWT setup uses: - - Access tokens (15 minutes expiry) - - Refresh tokens (7 days expiry) - - Proper error handling with specific error codes - -Example based on your auth.js pattern: -router.get('/', authenticateToken, controllerFunction); -
- -
Plugin: JWTMissingProtectionPlugin
-
- -
-
-
Missing JWT Protection: GET /:user_id
- MEDIUM -
- -
- ๐Ÿ“ routes/notifications.js - (Line 21) -
- -
API endpoint GET /:user_id in notifications.js lacks JWT authentication middleware. Based on your current architecture, this should use authenticateToken middleware.
- -
- ๐Ÿ’ก Recommendation: To fix this JWT protection issue, add the authenticateToken middleware: - -1. Import the middleware (if not already imported): - const { authenticateToken } = require('../middleware/authenticateToken'); - -2. Add middleware to the route: - router.get('/:user_id', authenticateToken, (req, res) => { ... }); - - Or if using a controller: - router.get('/:user_id', authenticateToken, controllerFunction); - -3. For optional authentication, you can use: - const { optionalAuth } = require('../middleware/authenticateToken'); - router.get('/:user_id', optionalAuth, (req, res) => { ... }); - -4. Your current JWT setup uses: - - Access tokens (15 minutes expiry) - - Refresh tokens (7 days expiry) - - Proper error handling with specific error codes - -Example based on your auth.js pattern: -router.get('/:user_id', authenticateToken, controllerFunction); -
- -
Plugin: JWTMissingProtectionPlugin
-
- -
-
-
Missing JWT Protection: GET /:user_id
- MEDIUM -
- -
- ๐Ÿ“ routes/notifications.js - (Line 21) -
- -
API endpoint GET /:user_id in notifications.js lacks JWT authentication middleware. Based on your current architecture, this should use authenticateToken middleware.
- -
- ๐Ÿ’ก Recommendation: To fix this JWT protection issue, add the authenticateToken middleware: - -1. Import the middleware (if not already imported): - const { authenticateToken } = require('../middleware/authenticateToken'); - -2. Add middleware to the route: - router.get('/:user_id', authenticateToken, (req, res) => { ... }); - - Or if using a controller: - router.get('/:user_id', authenticateToken, controllerFunction); - -3. For optional authentication, you can use: - const { optionalAuth } = require('../middleware/authenticateToken'); - router.get('/:user_id', optionalAuth, (req, res) => { ... }); - -4. Your current JWT setup uses: - - Access tokens (15 minutes expiry) - - Refresh tokens (7 days expiry) - - Proper error handling with specific error codes - -Example based on your auth.js pattern: -router.get('/:user_id', authenticateToken, controllerFunction); -
- -
Plugin: JWTMissingProtectionPlugin
-
- -
-
-
Low Entropy JWT Secret
- MEDIUM -
- -
- ๐Ÿ“ .env - (Line 10) -
- -
JWT secret appears to have low entropy (predictable patterns). This could make the secret easier to guess.
- -
- ๐Ÿ’ก Recommendation: Use cryptographically secure random generation for JWT secrets. -
- -
Plugin: JWTConfigurationPlugin
-
- -
-
-
Direct JWT Usage Instead of AuthService
- MEDIUM -
- -
- ๐Ÿ“ middleware.js - -
- -
File middleware.js uses direct jwt.verify() instead of the centralized authService. This bypasses your unified authentication logic.
- -
- ๐Ÿ’ก Recommendation: Consider updating this file to use authService.verifyAccessToken() for consistent authentication behavior. -
- -
Plugin: JWTConfigurationPlugin
-
- -
-
-
Multiple JWT Implementation Files Detected
- MEDIUM -
- -
- ๐Ÿ“ Multiple files - -
- -
Found 2 different JWT middleware files: middleware.js, authenticateToken.js. This could lead to inconsistent authentication behavior.
- -
- ๐Ÿ’ก Recommendation: Consider consolidating to a single JWT middleware implementation to avoid confusion and ensure consistent behavior. -
- -
Plugin: JWTConfigurationPlugin
-
- -
-
-
Incomplete JWT Error Handling
- LOW -
- -
- ๐Ÿ“ middleware.js - -
- -
JWT verification code lacks comprehensive error handling. Should handle TokenExpiredError, JsonWebTokenError, and other JWT-related errors.
- -
- ๐Ÿ’ก Recommendation: Add comprehensive error handling for different JWT error types to provide better user experience and security. -
- -
Plugin: JWTConfigurationPlugin
-
- -
- - -
- - - \ 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..d47d3ca --- /dev/null +++ b/Vulnerability_Tool_V2/security_report.html @@ -0,0 +1,2368 @@ + + + + + + + NutriHelp Security Scanner V2.0 Report + + + +
+
+

๐Ÿ”’ NutriHelp Security Scanner V2.0

+
+
Scan time: 2025-09-07 09:02:30
+
Target path: ../
+
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 From 6375f5bdec638544341d2609e2f1e08c10db3eb5 Mon Sep 17 00:00:00 2001 From: ChaohuiLi0321 Date: Sun, 7 Sep 2025 09:08:07 +1000 Subject: [PATCH 21/39] Use Swagger UI: http://localhost:8001/scanner/docs to test and generate reports in the updated debug format (use the command "python -m uvicorn api.scanner_api:app --host 0.0.0.0 --port 8001 --reload" to start the SwaggerUI integration of NutriHelp Security Scanner V2.0) --- .../security_report_scan_20250907_090434.html | 2368 +++++++++++++++++ 1 file changed, 2368 insertions(+) create mode 100644 Vulnerability_Tool_V2/reports/security_report_scan_20250907_090434.html 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 From 702082a9f42085b47c4b5f7c868dd938dc26571f Mon Sep 17 00:00:00 2001 From: ChaohuiLi0321 Date: Sun, 7 Sep 2025 12:08:54 +1000 Subject: [PATCH 22/39] Integrate Vulnerability_Scanner_V2.0 into the Swagger UI: http://localhost/api-docs, and test the GET and POST methods in the API interface separately. --- .../tools/render_from_json.py | 35 + index.yaml | 3 - .../security_report_scan_20250907_114003.html | 2400 +++++++++++++++++ routes/scanner.js | 348 ++- server.js | 4 + 5 files changed, 2763 insertions(+), 27 deletions(-) create mode 100644 Vulnerability_Tool_V2/tools/render_from_json.py create mode 100644 reports/security_report_scan_20250907_114003.html 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/index.yaml b/index.yaml index a6d551d..9eb1a5d 100644 --- a/index.yaml +++ b/index.yaml @@ -6,9 +6,6 @@ servers: - url: "http://localhost" description: "Local API" -externalDocs: - description: "Open Vulnerability Scanner UI" - url: "http://localhost:8001/scanner/docs" tags: - name: System description: System and security monitoringย endpoints 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/routes/scanner.js b/routes/scanner.js index c0ec8d9..b4d9602 100644 --- a/routes/scanner.js +++ b/routes/scanner.js @@ -1,7 +1,7 @@ // routes/scanner.js const express = require('express'); const router = express.Router(); -const { spawn } = require('child_process'); +const { spawn, spawnSync } = require('child_process'); const path = require('path'); const fs = require('fs').promises; const { v4: uuidv4 } = require('uuid'); @@ -9,6 +9,19 @@ 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: @@ -238,7 +251,7 @@ router.post('/scan', async (req, res) => { }); } - const scanId = uuidv4(); + const scanId = generateScanId(); // Start asynchronous scan startPythonScan(scanId, target_path, plugins, output_format); @@ -290,10 +303,46 @@ router.post('/scan', async (req, res) => { * 404: * description: Scan ID does not exist */ -router.get('/scan/:scanId/status', (req, res) => { +router.get('/scan/:scanId/status', async (req, res) => { const { scanId } = req.params; - const scanInfo = activeScanners.get(scanId); + 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, @@ -334,7 +383,7 @@ router.get('/scan/:scanId/status', (req, res) => { * 404: * description: Scan ID does not exist */ -router.get('/scan/:scanId/result', (req, res) => { +router.get('/scan/:scanId/result', async (req, res) => { const { scanId } = req.params; const scanInfo = activeScanners.get(scanId); @@ -360,7 +409,23 @@ router.get('/scan/:scanId/result', (req, res) => { }); } - res.json(scanInfo.result); + // 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); }); /** @@ -396,9 +461,10 @@ router.get('/scan/:scanId/result', (req, res) => { * 404: * description: Scan ID does not exist */ -router.get('/scan/:scanId/report', (req, res) => { +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) { @@ -415,10 +481,97 @@ router.get('/scan/:scanId/report', (req, res) => { }); } - if (format === 'html' && scanInfo.htmlReport) { - res.setHeader('Content-Type', 'text/html'); - res.setHeader('Content-Disposition', `attachment; filename="security_report_${scanId}.html"`); - res.send(scanInfo.htmlReport); + 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); @@ -430,6 +583,19 @@ router.get('/scan/:scanId/report', (req, res) => { } }); +// 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: @@ -463,7 +629,7 @@ router.post('/quick-scan', async (req, res) => { }); } - const scanId = uuidv4(); + const scanId = generateScanId(); const result = await runPythonScanSync(target_path, plugins, output_format); res.json({ @@ -501,6 +667,7 @@ function startPythonScan(scanId, targetPath, plugins, outputFormat) { let outputData = ''; let errorData = ''; + // save raw output for debugging pythonProcess.stdout.on('data', (data) => { outputData += data.toString(); @@ -517,15 +684,12 @@ function startPythonScan(scanId, targetPath, plugins, outputFormat) { console.log('Full Python output:', outputData); const scanInfo = activeScanners.get(scanId); + if (scanInfo) scanInfo.rawOutput = outputData; if (!scanInfo) return; if (code === 0) { try { - const jsonStart = outputData.lastIndexOf('{'); - const jsonEnd = outputData.lastIndexOf('}') + 1; - const jsonPart = outputData.substring(jsonStart, jsonEnd); - - const result = JSON.parse(jsonPart); + const result = parseBestJSON(outputData); scanInfo.status = 'completed'; scanInfo.progress = 100; scanInfo.message = 'Scan completed successfully'; @@ -534,14 +698,53 @@ function startPythonScan(scanId, targetPath, plugins, outputFormat) { // 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) { - scanInfo.status = 'failed'; - scanInfo.message = `Failed to parse scan result: ${error.message}`; + // 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 { - scanInfo.status = 'failed'; - scanInfo.message = `Scan failed with code ${code}: ${errorData}`; + // 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}`; + } + })(); } }); } @@ -573,18 +776,115 @@ function runPythonScanSync(targetPath, plugins, outputFormat) { pythonProcess.on('close', (code) => { if (code === 0) { try { - const result = JSON.parse(outputData); + const result = parseBestJSON(outputData); resolve(result); } catch (error) { - reject(new Error(`Failed to parse scan result: ${error.message}`)); + // 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 { - reject(new Error(`Scan failed with code ${code}: ${errorData}`)); + (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}`)); + } + })(); } }); }); } +// Extract the last complete top-level JSON object or array from a string that may +// contain surrounding logs. It scans for balanced '{'..'}' and '['..']' while +// respecting string literals and escapes. Returns the last complete JSON candidate. +// Collect all complete top-level JSON candidates from text and return array +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; +} + +// Try to parse the best JSON object found in text. +// Strategy: +// 1) collect candidates and try parse from last to first +// 2) if direct parse fails, try bounded tail-trimming retries on that candidate +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; diff --git a/server.js b/server.js index 184df51..5ea62a1 100644 --- a/server.js +++ b/server.js @@ -138,6 +138,10 @@ app.use(limiter); // apply globally // Swagger Docs const swaggerDocument = yaml.load("./index.yaml"); +// Defensive: remove any externalDocs entry so Swagger UI won't render external links +if (swaggerDocument && swaggerDocument.externalDocs) { + delete swaggerDocument.externalDocs; +} app.use("/api-docs", swaggerUi.serve, swaggerUi.setup(swaggerDocument)); // JSON & URL parser From 7c28bc896d39f1d5fb6846576ab4410cda752785 Mon Sep 17 00:00:00 2001 From: ChaohuiLi0321 Date: Sun, 7 Sep 2025 12:13:51 +1000 Subject: [PATCH 23/39] Update security report --- Vulnerability_Tool_V2/security_report.html | 54 +++++++++++++++++----- 1 file changed, 43 insertions(+), 11 deletions(-) diff --git a/Vulnerability_Tool_V2/security_report.html b/Vulnerability_Tool_V2/security_report.html index d47d3ca..51c2278 100644 --- a/Vulnerability_Tool_V2/security_report.html +++ b/Vulnerability_Tool_V2/security_report.html @@ -138,7 +138,7 @@

๐Ÿ”’ NutriHelp Security Scanner V2.0

-
Scan time: 2025-09-07 09:02:30
+
Scan time: 2025-09-07 12:12:14
Target path: ../
Scanner version: 2.0.0
@@ -154,7 +154,7 @@

๐Ÿ”’ NutriHelp Security Scanner V2.0

High Severity
-
68
+
69
Medium Severity
@@ -166,7 +166,7 @@

๐Ÿ”’ NutriHelp Security Scanner V2.0

-
189
+
190
Files Scanned
@@ -174,7 +174,7 @@

๐Ÿ”’ NutriHelp Security Scanner V2.0

Plugins Used
-
69
+
70
Total Issues
@@ -1341,7 +1341,7 @@

๐Ÿ” Detailed Findings

๐Ÿ“„ routes/scanner.js - (Line 22) + (Line 35)
API endpoint GET /test lacks JWT authentication middleware
@@ -1373,7 +1373,7 @@

๐Ÿ” Detailed Findings

๐Ÿ“„ routes/scanner.js - (Line 164) + (Line 177)
API endpoint GET /plugins lacks JWT authentication middleware
@@ -1405,7 +1405,7 @@

๐Ÿ” Detailed Findings

๐Ÿ“„ routes/scanner.js - (Line 221) + (Line 234)
API endpoint POST /scan lacks JWT authentication middleware
@@ -1437,7 +1437,7 @@

๐Ÿ” Detailed Findings

๐Ÿ“„ routes/scanner.js - (Line 293) + (Line 306)
API endpoint GET /scan/:scanId/status lacks JWT authentication middleware
@@ -1469,7 +1469,7 @@

๐Ÿ” Detailed Findings

๐Ÿ“„ routes/scanner.js - (Line 337) + (Line 386)
API endpoint GET /scan/:scanId/result lacks JWT authentication middleware
@@ -1501,7 +1501,7 @@

๐Ÿ” Detailed Findings

๐Ÿ“„ routes/scanner.js - (Line 399) + (Line 464)
API endpoint GET /scan/:scanId/report lacks JWT authentication middleware
@@ -1524,6 +1524,38 @@

๐Ÿ” Detailed Findings

+
+
+
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
@@ -1533,7 +1565,7 @@

๐Ÿ” Detailed Findings

๐Ÿ“„ routes/scanner.js - (Line 455) + (Line 621)
API endpoint POST /quick-scan lacks JWT authentication middleware
From ecfe6fe04465ac45bdb104537980a027d23436b0 Mon Sep 17 00:00:00 2001 From: ChaohuiLi0321 Date: Sun, 7 Sep 2025 19:49:00 +1000 Subject: [PATCH 24/39] Add standard password or related security testing mechanisms and integrate them into the API interface scanning function in Swagger UI. --- Vulnerability_Tool_V2/core/scanner_engine.py | 2 + .../plugins/general_security/README.md | 56 + .../plugins/general_security/__init__.py | 126 + .../plugins/jwt_security/README.md | 91 + Vulnerability_Tool_V2/scanner_v2.py | 3 + .../security_report_general.html | 2761 +++++++++++++++++ .../tests/test_general_security_plugin.py | 32 + .../security_report_scan_20250907_130446.html | 2732 ++++++++++++++++ routes/scanner.js | 124 +- 9 files changed, 5896 insertions(+), 31 deletions(-) create mode 100644 Vulnerability_Tool_V2/plugins/general_security/README.md create mode 100644 Vulnerability_Tool_V2/plugins/general_security/__init__.py create mode 100644 Vulnerability_Tool_V2/plugins/jwt_security/README.md create mode 100644 Vulnerability_Tool_V2/security_report_general.html create mode 100644 Vulnerability_Tool_V2/tests/test_general_security_plugin.py create mode 100644 reports/security_report_scan_20250907_130446.html diff --git a/Vulnerability_Tool_V2/core/scanner_engine.py b/Vulnerability_Tool_V2/core/scanner_engine.py index 4b782e3..0deeb64 100644 --- a/Vulnerability_Tool_V2/core/scanner_engine.py +++ b/Vulnerability_Tool_V2/core/scanner_engine.py @@ -54,6 +54,8 @@ def load_plugins(self, plugin_configs: Optional[Dict[str, Any]] = None): 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 } 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/scanner_v2.py b/Vulnerability_Tool_V2/scanner_v2.py index 45d23ca..abfb3d2 100644 --- a/Vulnerability_Tool_V2/scanner_v2.py +++ b/Vulnerability_Tool_V2/scanner_v2.py @@ -78,6 +78,9 @@ def main(): # 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: 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/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/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/scanner.js b/routes/scanner.js index b4d9602..667f3ed 100644 --- a/routes/scanner.js +++ b/routes/scanner.js @@ -628,8 +628,16 @@ router.post('/quick-scan', async (req, res) => { error: 'target_path is required' }); } - - const scanId = generateScanId(); + // 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({ @@ -661,8 +669,43 @@ function startPythonScan(scanId, targetPath, plugins, outputFormat) { const args = ['--target', targetPath, '--format', outputFormat]; - const pythonProcess = spawn(pythonPath, [scriptPath, ...args], { - cwd: scannerPath + 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 = ''; @@ -730,21 +773,30 @@ function startPythonScan(scanId, targetPath, plugins, outputFormat) { })(); } } else { - // 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}`; - } - })(); + // 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}`; + } + })(); + } } }); } @@ -756,7 +808,8 @@ function runPythonScanSync(targetPath, plugins, outputFormat) { const pythonPath = path.join(scannerPath, 'venv/bin/python'); const scriptPath = path.join(scannerPath, 'scanner_v2.py'); - const args = ['--target', targetPath, '--format', 'json']; + // 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 @@ -793,17 +846,26 @@ function runPythonScanSync(targetPath, plugins, outputFormat) { })(); } } else { - (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}`)); - } - })(); + // 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}`)); + } + })(); + } } }); }); From ac49ba6f2f2a48b633e3067a6d05a8ff15f4a51e Mon Sep 17 00:00:00 2001 From: ChaohuiLi0321 Date: Sun, 7 Sep 2025 20:59:34 +1000 Subject: [PATCH 25/39] update comment --- routes/scanner.js | 10 ++-------- server.js | 2 +- 2 files changed, 3 insertions(+), 9 deletions(-) diff --git a/routes/scanner.js b/routes/scanner.js index 667f3ed..120a5c5 100644 --- a/routes/scanner.js +++ b/routes/scanner.js @@ -871,10 +871,7 @@ function runPythonScanSync(targetPath, plugins, outputFormat) { }); } -// Extract the last complete top-level JSON object or array from a string that may -// contain surrounding logs. It scans for balanced '{'..'}' and '['..']' while -// respecting string literals and escapes. Returns the last complete JSON candidate. -// Collect all complete top-level JSON candidates from text and return array +// Collect JSON candidates from text by tracking balanced braces/brackets function collectJSONCandidates(text) { if (!text || typeof text !== 'string') return []; @@ -915,10 +912,7 @@ function collectJSONCandidates(text) { return candidates; } -// Try to parse the best JSON object found in text. -// Strategy: -// 1) collect candidates and try parse from last to first -// 2) if direct parse fails, try bounded tail-trimming retries on that candidate +// 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'); diff --git a/server.js b/server.js index 5ea62a1..f252b71 100644 --- a/server.js +++ b/server.js @@ -138,7 +138,7 @@ app.use(limiter); // apply globally // Swagger Docs const swaggerDocument = yaml.load("./index.yaml"); -// Defensive: remove any externalDocs entry so Swagger UI won't render external links +// Remove externalDocs if present to avoid CORS issues if (swaggerDocument && swaggerDocument.externalDocs) { delete swaggerDocument.externalDocs; } From 3788ba00341a5b7791a7f28d805e5b5d8d824e15 Mon Sep 17 00:00:00 2001 From: ChaohuiLi0321 Date: Fri, 12 Sep 2025 15:35:54 +1000 Subject: [PATCH 26/39] include general_security in GET /api/scanner/plugins --- routes/scanner.js | 103 ++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 91 insertions(+), 12 deletions(-) diff --git a/routes/scanner.js b/routes/scanner.js index 120a5c5..bd09bd1 100644 --- a/routes/scanner.js +++ b/routes/scanner.js @@ -45,6 +45,21 @@ router.get('/test', (req, res) => { * required: * - target_path * properties: + * key: + * type: string + * description: internal plugin key (used by scanner) + * version: + * type: string + * description: plugin version if available + * available: + * type: boolean + * description: whether plugin directory exists in the scanner package + * enabled: + * type: boolean + * description: whether plugin is enabled in scanner config (null if unknown) + * severity_level: + * type: string + * description: default severity level assigned to findings from this plugin * target_path: * type: string * description: Target path to scan @@ -176,19 +191,83 @@ router.get('/health', async (req, res) => { */ 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" + // Dynamically construct available plugin list to reflect the scanner's plugins + const scannerRoot = path.join(__dirname, '../Vulnerability_Tool_V2'); + const pluginsDir = path.join(scannerRoot, 'plugins'); + + // Plugin mappings mirror Vulnerability_Tool_V2/core/scanner_engine.py + // Note: plugin key => folder name mapping (some plugins group under subpackage like jwt_security) + const pluginMappings = { + 'jwt_missing_protection': { name: 'JWTMissingProtectionPlugin', default_severity: 'HIGH', folder: 'jwt_security' }, + 'jwt_configuration': { name: 'JWTConfigurationPlugin', default_severity: 'MEDIUM', folder: 'jwt_security' }, + 'general_security': { name: 'general_security', default_severity: 'MEDIUM', folder: 'general_security' } + }; + + // Try to read scanner config to determine enabled state when possible + let enabledPluginsConfig = {}; + try { + const configPath = path.join(scannerRoot, 'config', 'scanner_config.yaml'); + const exists = await fs.access(configPath).then(() => true).catch(() => false); + if (exists) { + const yaml = require('yamljs'); + const cfg = yaml.load(configPath) || {}; + enabledPluginsConfig = cfg.plugins || {}; } - ]; - + } catch (e) { + // ignore config read errors; we'll fall back to defaults + } + + const plugins = []; + for (const [key, meta] of Object.entries(pluginMappings)) { + const pluginFolder = path.join(pluginsDir, meta.folder || key); + const available = await fs.access(pluginFolder).then(() => true).catch(() => false); + + // defaults + let description = ''; + let version = null; + + if (available) { + // Try to read __init__.py to get metadata heuristically + try { + const initPath = path.join(pluginFolder, '__init__.py'); + const initExists = await fs.access(initPath).then(() => true).catch(() => false); + if (initExists) { + const content = await fs.readFile(initPath, 'utf8'); + // attempt to extract description and version strings from get_plugin_info + const descMatch = content.match(/description\s*[:=]\s*['\"]([\s\S]*?)['\"]/i); + const verMatch = content.match(/version\s*[:=]\s*['\"]([\w\.\-]+)['\"]/i); + if (descMatch) description = descMatch[1].trim(); + if (verMatch) version = verMatch[1].trim(); + } + } catch (e) { + // best-effort only + } + } + + // fallback description if not found + if (!description) { + if (meta.name === 'general_security') description = 'Detect generic security issues such as hardcoded secrets, DB URLs and permissive CORS.'; + else if (meta.name === 'JWTMissingProtectionPlugin') description = 'Detect missing JWT protection in API endpoints'; + else if (meta.name === 'JWTConfigurationPlugin') description = 'Validate JWT configuration security'; + } + + const cfg = enabledPluginsConfig[key]; + // Follow scanner_v2.py semantics: general_security should be enabled by default if not present in config + let enabled = null; + if (cfg && typeof cfg.enabled === 'boolean') enabled = cfg.enabled; + else if (key === 'general_security') enabled = true; + + plugins.push({ + key, + name: meta.name, + description, + version, + severity_level: meta.default_severity, + available, + enabled + }); + } + res.json({ plugins }); } catch (error) { res.status(500).json({ From 3e9f6476a423edf9b7b44e0522e8083b7d67185a Mon Sep 17 00:00:00 2001 From: ChaohuiLi0321 Date: Fri, 12 Sep 2025 20:12:09 +1000 Subject: [PATCH 27/39] chore: update .gitignore to ignore venv and pytest cache --- .gitignore | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/.gitignore b/.gitignore index a930828..0a9d83f 100644 --- a/.gitignore +++ b/.gitignore @@ -137,6 +137,15 @@ venv/ __pycache__/ *.pyc +# Local virtualenv created during testing +.venv/ + +# pytest cache +.pytest_cache/ + +# pipenv +Pipfile.lock + # macOS system files .DS_Store From 4b7fc1e63d455011a5ff3f29088fd4c2aedc8a7a Mon Sep 17 00:00:00 2001 From: ChaohuiLi0321 Date: Sat, 13 Sep 2025 02:02:06 +1000 Subject: [PATCH 28/39] Add general security rules and enhance testing framework - Introduced a comprehensive set of security rules in `rules_v1.yaml` to detect vulnerabilities such as SQL injection, XSS, hardcoded credentials, and insecure file handling across JavaScript, Python, and text files. - Implemented tests for the new rules in `test_general_security_legacy_rules.py`, ensuring detection of hardcoded API keys and permissive CORS configurations. - Enhanced the testing framework with new test cases for excluding paths in `test_exclude_paths.py` and verifying JSON output fields in `test_output_json_fields.py`. - Added a script `rename_reports_security_to_vulnerability.py` for batch renaming legacy security report files to a new naming convention. - Improved the debug rules toggle functionality and HTML report generation in `test_debug_rules_and_html.py`. --- .../config/scanner_config.yaml | 47 + Vulnerability_Tool_V2/core/report_renderer.py | 10 +- Vulnerability_Tool_V2/core/scanner_engine.py | 267 +- Vulnerability_Tool_V2/plugins/base_plugin.py | 71 +- .../plugins/general_security/__init__.py | 72 +- .../plugins/general_security/rules_v1.yaml | 500 +++ .../plugins/jwt_security/jwt_missing.py | 11 +- Vulnerability_Tool_V2/scanner_v2.py | 23 +- Vulnerability_Tool_V2/security_report.html | 2400 -------------- .../security_report_general.html | 2761 ----------------- .../tests/test_debug_rules_and_html.py | 48 + .../tests/test_exclude_paths.py | 97 + .../test_general_security_legacy_rules.py | 29 + .../tests/test_internal_file_exclude.py | 44 + .../tests/test_output_json_fields.py | 43 + index.yaml | 72 +- package-lock.json | 26 + package.json | 2 + .../security_report_scan_20250907_114003.html | 2400 -------------- .../security_report_scan_20250907_130446.html | 2732 ---------------- routes/scanner.js | 215 +- ...ename_reports_security_to_vulnerability.py | 131 + 22 files changed, 1556 insertions(+), 10445 deletions(-) create mode 100644 Vulnerability_Tool_V2/plugins/general_security/rules_v1.yaml delete mode 100644 Vulnerability_Tool_V2/security_report.html delete mode 100644 Vulnerability_Tool_V2/security_report_general.html create mode 100644 Vulnerability_Tool_V2/tests/test_debug_rules_and_html.py create mode 100644 Vulnerability_Tool_V2/tests/test_exclude_paths.py create mode 100644 Vulnerability_Tool_V2/tests/test_general_security_legacy_rules.py create mode 100644 Vulnerability_Tool_V2/tests/test_internal_file_exclude.py create mode 100644 Vulnerability_Tool_V2/tests/test_output_json_fields.py delete mode 100644 reports/security_report_scan_20250907_114003.html delete mode 100644 reports/security_report_scan_20250907_130446.html create mode 100644 scripts/rename_reports_security_to_vulnerability.py diff --git a/Vulnerability_Tool_V2/config/scanner_config.yaml b/Vulnerability_Tool_V2/config/scanner_config.yaml index 8239ee7..596d47e 100644 --- a/Vulnerability_Tool_V2/config/scanner_config.yaml +++ b/Vulnerability_Tool_V2/config/scanner_config.yaml @@ -17,6 +17,16 @@ plugins: - /health - /api-docs enabled: true + general_security: + config: + legacy_rules: + enabled: true + # default path relative to plugin dir; can be overridden with absolute path + path: plugins/general_security/rules_v1.yaml + # plugin-specific defaults + allowlist_keys: ['TEST_SECRET', 'PLACEHOLDER', 'EXAMPLE_SECRET'] + exclude_paths: ['tests/', '__tests__/', 'fixtures/', 'node_modules/', '.venv/', 'venv/'] + enabled: true rls_missing_protection_disabled: config: rls_indicators: @@ -82,8 +92,45 @@ scanner: - .yml - .env name: NutriHelp Security Scanner V2.0 + # Engine-level global exclude paths (substring matches). These will be + # injected into each plugin's exclude_paths so plugins and engine skip them. + global_exclude_paths: + - tests/ + - __tests__/ + - fixtures/ + - Vulnerability_Tool_V2/ + - reports/ + - scripts/ + - tools/ + - venv/ + - .venv/ + - node_modules/ + + # New: internal scanner files filtering + exclude_internal_scanner_files: true + internal_paths: + - routes/scanner.js + - reports/ + - Vulnerability_Tool_V2/ + - Vulnerability_Tool/ + - scripts/ scan_settings: max_file_size_mb: 50 parallel_scanning: false timeout_seconds: 300 version: 2.0.0 + # Recognize common global middleware names that indicate protection when used + trusted_global_middlewares: + - authenticateToken + - useAuth + - authorizeRoles + - optionalAuth + # Public paths that should not trigger JWT-missing alerts (prefix or exact match) + public_paths: + - /login + - /signup + - /health + - /status + - /mfa + - /classify + - /integrity-check diff --git a/Vulnerability_Tool_V2/core/report_renderer.py b/Vulnerability_Tool_V2/core/report_renderer.py index 3831d30..027ed06 100644 --- a/Vulnerability_Tool_V2/core/report_renderer.py +++ b/Vulnerability_Tool_V2/core/report_renderer.py @@ -22,7 +22,7 @@ def render_html_report(scan_results: Dict[str, Any], config_manager=None) -> str - NutriHelp Security Scanner V2.0 Report + NutriHelp Vulnerability 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 deleted file mode 100644 index 4960ed1..0000000 --- a/Vulnerability_Tool_V2/security_report_general.html +++ /dev/null @@ -1,2761 +0,0 @@ - - - - - - - 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/tests/test_debug_rules_and_html.py b/Vulnerability_Tool_V2/tests/test_debug_rules_and_html.py new file mode 100644 index 0000000..1826704 --- /dev/null +++ b/Vulnerability_Tool_V2/tests/test_debug_rules_and_html.py @@ -0,0 +1,48 @@ +import sys +import os +import json + +sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) + +from core.scanner_engine import SecurityScannerEngine +from core.config_manager import ConfigManager +from core.report_renderer import render_html_report + + +def test_debug_rules_toggle_and_html_output(tmp_path): + # setup temp dir with files that match debug-mode rules (email/url/ip) + tdir = tmp_path / "sample2" + tdir.mkdir() + f = tdir / "data.txt" + f.write_text("contact: info@example.com\nlink: https://example.com\nip: 192.168.1.1\n") + + cfg = ConfigManager(None) + scanner_cfg = cfg.get_scanner_config() + + # Load only the general_security plugin to keep test deterministic + pcfg = { + 'general_security': { + 'enabled': True, + 'legacy_rules': {'enabled': True, 'include_debug_rules': False} + } + } + engine = SecurityScannerEngine(scanner_cfg) + engine.load_plugins(pcfg) + + results_no_debug = engine.scan_target(str(tdir)) + # There should be no findings with rule_mode == 'debug' + assert not any(f.get('rule_mode') == 'debug' for f in results_no_debug.get('findings', [])) + + # Now enable debug rules and reload plugins + pcfg['general_security']['legacy_rules']['include_debug_rules'] = True + engine = SecurityScannerEngine(scanner_cfg) + engine.load_plugins(pcfg) + results_with_debug = engine.scan_target(str(tdir)) + + # Now at least one finding should come from a debug-mode rule + assert any(f.get('rule_mode') == 'debug' for f in results_with_debug.get('findings', [])) + + # Generate HTML and assert rule metadata label appears in HTML for the findings + scan_results = results_with_debug + html = render_html_report(scan_results) + assert 'Rule:' in html or 'rule_id' in html or 'Rule ID' in html diff --git a/Vulnerability_Tool_V2/tests/test_exclude_paths.py b/Vulnerability_Tool_V2/tests/test_exclude_paths.py new file mode 100644 index 0000000..5a70c7b --- /dev/null +++ b/Vulnerability_Tool_V2/tests/test_exclude_paths.py @@ -0,0 +1,97 @@ +import os +import sys +import tempfile +import shutil +# Ensure repo root is on sys.path for imports during pytest +sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))) +from Vulnerability_Tool_V2.core.scanner_engine import VulnerabilityScannerEngine + + +def setup_sample_repo(tmpdir): + # Create sample structure + base = tmpdir + os.makedirs(os.path.join(base, 'src'), exist_ok=True) + os.makedirs(os.path.join(base, 'tests'), exist_ok=True) + os.makedirs(os.path.join(base, 'Vulnerability_Tool_V2'), exist_ok=True) + + with open(os.path.join(base, 'src', 'app.js'), 'w') as f: + f.write("console.log('hello')\n") + + with open(os.path.join(base, 'tests', 'test_dummy.js'), 'w') as f: + f.write("describe('dummy', () => {});\n") + + # file that should be excluded + with open(os.path.join(base, 'Vulnerability_Tool_V2', 'plugins', 'dummy.py'), 'w') as f: + os.makedirs(os.path.join(base, 'Vulnerability_Tool_V2', 'plugins'), exist_ok=True) + f.write('# plugin file') + + return base + + +def test_engine_excludes(tmp_path): + repo = tmp_path / "sample_repo" + repo.mkdir() + + # construct folders + (repo / 'src').mkdir() + (repo / 'tests').mkdir() + (repo / 'Vulnerability_Tool_V2').mkdir() + (repo / 'Vulnerability_Tool_V2' / 'plugins').mkdir(parents=True) + + # create files + (repo / 'src' / 'app.js').write_text("console.log('ok')\n") + (repo / 'tests' / 'test_dummy.js').write_text("describe('x', ()=>{})\n") + (repo / 'Vulnerability_Tool_V2' / 'plugins' / 'plugin.py').write_text("# plugin file\n") + + # configure engine with global excludes + cfg = { + 'global_exclude_paths': ['tests/', 'Vulnerability_Tool_V2/'] + } + engine = VulnerabilityScannerEngine(cfg) + + # load only the general_security plugin (it exists in repo); but tests should not rely on plugin detection + # We will manually register a minimal plugin that returns a finding for each file that contains 'console' + class DummyPlugin: + def __init__(self, config=None): + self.config = config or {} + self.findings = [] + self.name = 'dummy' + + def get_plugin_info(self): + return {'name': 'dummy', 'version': '0.0.1'} + + def get_severity_level(self): + return 'LOW' + + def scan(self, target_path): + res = [] + for root, dirs, files in os.walk(target_path): + dirs[:] = [d for d in dirs if not any(p and p in os.path.join(root, d) for p in self.config.get('exclude_paths', []))] + for fname in files: + fpath = os.path.join(root, fname) + # use plugin-level file exclusion + if any(p and p in fpath for p in self.config.get('exclude_paths', [])): + continue + try: + with open(fpath, 'r') as fh: + content = fh.read() + if 'console' in content: + res.append({ 'title': 'found console', 'file_path': fpath }) + except Exception: + continue + return res + + # register our dummy plugin + dp = DummyPlugin() + engine.plugin_manager.register_plugin(dp) + + result = engine.scan_target(str(repo)) + + # findings should not include files under tests/ or Vulnerability_Tool_V2/ + for f in result['findings']: + fp = f.get('file_path', '') + assert 'tests/' not in fp + assert 'Vulnerability_Tool_V2/' not in fp + + # ensure at least one finding from src/app.js exists + assert any('app.js' in f.get('file_path', '') for f in result['findings']) diff --git a/Vulnerability_Tool_V2/tests/test_general_security_legacy_rules.py b/Vulnerability_Tool_V2/tests/test_general_security_legacy_rules.py new file mode 100644 index 0000000..2c0d9a0 --- /dev/null +++ b/Vulnerability_Tool_V2/tests/test_general_security_legacy_rules.py @@ -0,0 +1,29 @@ +import os +import sys +# ensure project package path is available for imports when running tests from repo root +sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) +from plugins.general_security import GeneralSecurityPlugin + + +def test_legacy_api_key_rule_triggers(tmp_path): + # create a sample JS file with hardcoded api_key + sample = tmp_path / "sample_api_key.js" + sample.write_text("const api_key = 'ABCDEFGH12345678';\nconsole.log('ok');\n") + + plugin = GeneralSecurityPlugin(config={}) + findings = plugin.scan(str(tmp_path)) + + # There should be at least one finding whose title includes API_Key or Hardcoded + titles = [f.title for f in plugin.findings] + assert any('API_Key' in t or 'Hardcoded' in t or 'API Key' in t for t in titles), f"No api key finding found: {titles}" + + +def test_permissive_cors_triggers(tmp_path): + sample = tmp_path / "cors.conf" + sample.write_text("Access-Control-Allow-Origin: *\n") + + plugin = GeneralSecurityPlugin(config={}) + findings = plugin.scan(str(tmp_path)) + + titles = [f.title for f in plugin.findings] + assert any('Permissive CORS' in t or 'CORS' in t for t in titles), f"No CORS finding found: {titles}" diff --git a/Vulnerability_Tool_V2/tests/test_internal_file_exclude.py b/Vulnerability_Tool_V2/tests/test_internal_file_exclude.py new file mode 100644 index 0000000..0b8ac2d --- /dev/null +++ b/Vulnerability_Tool_V2/tests/test_internal_file_exclude.py @@ -0,0 +1,44 @@ +import os +import pytest + +from Vulnerability_Tool_V2.core.scanner_engine import VulnerabilityScannerEngine + + +def _scan_with_config(config): + engine = VulnerabilityScannerEngine(config=config) + engine.load_plugins({}) + return engine.scan_target(os.getcwd()) + + +def test_default_internal_files_excluded(): + # default config should exclude internal scanner files + cfg = { + 'scanner': { + 'exclude_internal_scanner_files': True, + 'internal_paths': ['routes/scanner.js', 'reports/'] + } + } + + res = _scan_with_config(cfg) + file_paths = [f.get('file_path') or '' for f in res['findings']] + + # Ensure scanner route is not present in findings + assert not any('routes/scanner.js' in p or 'scanner.js' == os.path.basename(p) for p in file_paths) + + +def test_disable_internal_exclusion_includes_files(): + # When toggle is off, internal paths should be allowed + cfg = { + 'scanner': { + 'exclude_internal_scanner_files': False, + 'internal_paths': ['routes/scanner.js', 'reports/'] + } + } + + res = _scan_with_config(cfg) + file_paths = [f.get('file_path') or '' for f in res['findings']] + + # It's acceptable if no finding references the scanner file because plugins may not flag it, + # but we at least assert that the engine did not remove entries that explicitly reference it. + # To be conservative, check that sanitization did not forcibly remove any path equal to 'routes/scanner.js' + assert all(not (p and p.endswith('routes/scanner.js') and cfg['scanner']['exclude_internal_scanner_files']) for p in file_paths) diff --git a/Vulnerability_Tool_V2/tests/test_output_json_fields.py b/Vulnerability_Tool_V2/tests/test_output_json_fields.py new file mode 100644 index 0000000..8c05a74 --- /dev/null +++ b/Vulnerability_Tool_V2/tests/test_output_json_fields.py @@ -0,0 +1,43 @@ +import sys +import os +import json + +# ensure repo root is on path +sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) + +from core.scanner_engine import SecurityScannerEngine +from core.config_manager import ConfigManager + + +def test_json_output_includes_rule_metadata(tmp_path): + # Use a small temp directory with a sample file that triggers legacy rules + target = tmp_path / "sample" + target.mkdir() + sample_file = target / "test.js" + sample_file.write_text(""" + // sample to trigger api key hardcoded + const api_key = 'ABC123DEF456GHI789'; + """) + + # Load default config manager + cfg = ConfigManager(None) + scanner_cfg = cfg.get_scanner_config() + engine = SecurityScannerEngine(scanner_cfg) + # ensure general_security plugin enabled + plugin_cfgs = cfg.get_enabled_plugins() + if 'general_security' not in plugin_cfgs: + plugin_cfgs['general_security'] = {'enabled': True} + engine.load_plugins(plugin_cfgs) + + results = engine.scan_target(str(target)) + # Serialize to JSON (same as CLI does) + j = json.loads(json.dumps(results, ensure_ascii=False)) + + assert 'findings' in j + # Require that at least one finding contains the rule metadata keys (if any findings exist) + if j['findings']: + f = j['findings'][0] + assert 'rule_id' in f + assert 'rule_name' in f + assert 'confidence' in f + assert 'rule_mode' in f diff --git a/index.yaml b/index.yaml index 9eb1a5d..7763739 100644 --- a/index.yaml +++ b/index.yaml @@ -1402,7 +1402,6 @@ paths: description: Number of records to return schema: type: integer - description: Integer ID of the recipe for cost calculation default: 20 - name: page in: query @@ -1421,7 +1420,6 @@ paths: default: true responses: '200': - description: Calculate cost successfully description: Successfully retrieved requested data content: application/json: @@ -1875,61 +1873,6 @@ paths: description: Unauthorized - Authentication credentials missing or invalid. '500': description: Internal Server Error - Something went wrong on the server. - type: object - properties: - user_id: - type: string - format: uuid - description: The unique ID of the user - glasses_consumed: - type: integer - description: Number of glasses consumed - required: - - user_id - - glasses_consumed - example: - user_id: "15" - glasses_consumed: 5 - responses: - '200': - description: Water intake updated successfully - content: - application/json: - schema: - type: object - properties: - message: - type: string - example: "Water intake updated successfully" - data: - type: object - properties: - user_id: - type: string - example: "15" - date: - type: string - format: date - example: "2025-05-10" - glasses_consumed: - type: integer - example: 5 - updated_at: - type: string - format: date-time - example: "2025-05-10T12:00:00Z" - '400': - description: Bad request - missing or invalid fields - content: - application/json: - schema: - $ref: '#/components/schemas/ErrorResponse' - '500': - description: Internal server error - content: - application/json: - schema: - $ref: '#/components/schemas/ErrorResponse' /auth/register: post: @@ -3045,3 +2988,18 @@ components: plugin_name: type: string example: "JWTMissingProtectionPlugin" + rule_id: + type: string + example: "jwt_missing_protection" + rule_name: + type: string + example: "Missing JWT Protection" + rule_mode: + type: string + description: "Rule execution mode (e.g., normal, debug)" + example: "normal" + confidence: + type: string + description: "Classifier confidence for this finding" + enum: [LOW, MEDIUM, HIGH] + example: "HIGH" diff --git a/package-lock.json b/package-lock.json index 88cc625..3e74aed 100644 --- a/package-lock.json +++ b/package-lock.json @@ -36,6 +36,8 @@ "yamljs": "^0.3.0" }, "devDependencies": { + "acorn": "^8.15.0", + "acorn-walk": "^8.3.4", "axios": "^1.11.0", "concurrently": "^8.2.2", "form-data": "^4.0.2", @@ -295,6 +297,30 @@ "node": ">= 0.6" } }, + "node_modules/acorn": { + "version": "8.15.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz", + "integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==", + "dev": true, + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/acorn-walk": { + "version": "8.3.4", + "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.3.4.tgz", + "integrity": "sha512-ueEepnujpqee2o5aIYnvHU6C0A42MNdsIDeqy5BydrkuC5R1ZuUFnm27EeFJGoEHJQgn3uleRvmTXaJgfXbt4g==", + "dev": true, + "dependencies": { + "acorn": "^8.11.0" + }, + "engines": { + "node": ">=0.4.0" + } + }, "node_modules/ansi-colors": { "version": "4.1.3", "resolved": "https://registry.npmjs.org/ansi-colors/-/ansi-colors-4.1.3.tgz", diff --git a/package.json b/package.json index d780570..9d851f3 100644 --- a/package.json +++ b/package.json @@ -48,6 +48,8 @@ "yamljs": "^0.3.0" }, "devDependencies": { + "acorn": "^8.15.0", + "acorn-walk": "^8.3.4", "axios": "^1.11.0", "concurrently": "^8.2.2", "form-data": "^4.0.2", diff --git a/reports/security_report_scan_20250907_114003.html b/reports/security_report_scan_20250907_114003.html deleted file mode 100644 index 29e671d..0000000 --- a/reports/security_report_scan_20250907_114003.html +++ /dev/null @@ -1,2400 +0,0 @@ - - - - - - - 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 deleted file mode 100644 index 8f1c78c..0000000 --- a/reports/security_report_scan_20250907_130446.html +++ /dev/null @@ -1,2732 +0,0 @@ - - - - - - - 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/scanner.js b/routes/scanner.js index bd09bd1..f89512c 100644 --- a/routes/scanner.js +++ b/routes/scanner.js @@ -10,7 +10,13 @@ const { v4: uuidv4 } = require('uuid'); const activeScanners = new Map(); // Generate scan id in style: scan_YYYYMMDD_HHMMSS_ -function generateScanId() { +// Generate scan id in style: YYYYMMDD_HHMMSS_ +// tag defaults to 'scan' but can be set to 'quick-scan' or others. Keeps filename-safe characters. +// Generate canonical timestamp ID: YYYYMMDD_HHMMSS +// The optional tag is no longer embedded into the canonical ID; callers +// should record the tag separately and filenames are built with the helper +// below to append an optional tag suffix (e.g. _quick-scan). +function generateScanId(tag = 'scan') { const now = new Date(); const pad = (n) => String(n).padStart(2, '0'); const YYYY = now.getFullYear(); @@ -19,7 +25,26 @@ function generateScanId() { const hh = pad(now.getHours()); const mm = pad(now.getMinutes()); const ss = pad(now.getSeconds()); - return `scan_${YYYY}${MM}${DD}_${hh}${mm}${ss}`; + return `${YYYY}${MM}${DD}_${hh}${mm}${ss}`; +} + +// Compose a filename-safe identifier from the canonical timestamp id and an optional tag. +function formatScanIdWithTag(scanId, tag) { + const cleanTag = tag ? String(tag).replace(/[^a-zA-Z0-9_-]/g, '-') : ''; + return `${scanId}${cleanTag ? '_' + cleanTag : ''}`; +} + +// Find a file in 'dir' that starts with prefix and ends with ext. Returns null if none found. +async function findFileWithPrefix(dir, prefix, ext) { + try { + const entries = await fs.readdir(dir); + for (const e of entries) { + if (e.startsWith(prefix) && e.endsWith(ext)) return path.join(dir, e); + } + } catch (e) { + return null; + } + return null; } /** @@ -331,9 +356,11 @@ router.post('/scan', async (req, res) => { } const scanId = generateScanId(); + // For normal async scans, use default tag 'scan' + const scanTag = 'scan'; - // Start asynchronous scan - startPythonScan(scanId, target_path, plugins, output_format); + // Start asynchronous scan and pass tag so filenames can include it as a suffix + startPythonScan(scanId, scanTag, target_path, plugins, output_format); res.json({ scan_id: scanId, @@ -388,34 +415,38 @@ router.get('/scan/:scanId/status', async (req, res) => { 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 } }; + const reportsDir = path.join(process.cwd(), 'reports'); + const jsonPrefix = `Vulnerability_Scan_Result_${scanId}`; + const projectReportJson = await findFileWithPrefix(reportsDir, jsonPrefix, '.json'); + + if (projectReportJson) { + const data = await fs.readFile(projectReportJson, 'utf8'); + scanInfo = { status: 'completed', result: JSON.parse(data) }; + } else { + // Try HTML in scanner's reports dir + const scannerReportsDir = path.join(process.cwd(), 'Vulnerability_Tool_V2', 'reports'); + const htmlPrefix = `Vulnerability_Scan_Report_${scanId}`; + const scannerReportHtml = await findFileWithPrefix(scannerReportsDir, htmlPrefix, '.html'); + + if (scannerReportHtml) { + 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) { @@ -565,7 +596,7 @@ router.get('/scan/:scanId/report', async (req, res) => { try { const reportsDir = path.join(__dirname, '../reports'); await fs.mkdir(reportsDir, { recursive: true }); - const htmlPath = path.join(reportsDir, `security_report_${scanId}.html`); + const htmlPath = path.join(reportsDir, `Vulnerability_Scan_Report_${scanId}.html`); // First try to use Python renderer if present const pythonRenderer = path.join(__dirname, '../Vulnerability_Tool_V2/tools/render_from_json.py'); @@ -631,20 +662,19 @@ router.get('/scan/:scanId/report', async (req, res) => { // 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 + const projectReportsDir = path.join(__dirname, '../reports'); + const scannerReportsDir = path.join(__dirname, '../Vulnerability_Tool_V2/reports'); + + // Try to find the actual HTML file which may include an optional tag suffix + let finalPath = await findFileWithPrefix(projectReportsDir, `Vulnerability_Scan_Report_${scanId}`, '.html'); + if (!finalPath) finalPath = await findFileWithPrefix(scannerReportsDir, `Vulnerability_Scan_Report_${scanId}`, '.html'); + if (!finalPath) finalPath = htmlPath; // fallback to whatever we wrote earlier + + // record chosen path and stream it 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.setHeader('Content-Disposition', `attachment; filename="${path.basename(finalPath)}"`); res.send(htmlContent); return; } catch (err) { @@ -652,7 +682,11 @@ router.get('/scan/:scanId/report', async (req, res) => { return; } } else if (format === 'json') { - res.setHeader('Content-Disposition', `attachment; filename="security_report_${scanId}.json"`); + // attempt to find persisted json with optional tag + const reportsDir = path.join(__dirname, '../reports'); + const jsonPath = await findFileWithPrefix(reportsDir, `Vulnerability_Scan_Result_${scanId}`, '.json'); + if (jsonPath) res.setHeader('Content-Disposition', `attachment; filename="${path.basename(jsonPath)}"`); + else res.setHeader('Content-Disposition', `attachment; filename=\"Vulnerability_Scan_Result_${scanId}.json\"`); res.json(scanInfo.result); } else { res.status(400).json({ @@ -716,15 +750,82 @@ router.post('/quick-scan', async (req, res) => { }); } - 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 - }); + const scanId = generateScanId(); + const scanTag = 'quick-scan'; + const scanIdWithTag = formatScanIdWithTag(scanId, scanTag); + const result = await runPythonScanSync(target_path, plugins, output_format); + + // persist into activeScanners so subsequent report/status endpoints can find it + const scanInfo = { + status: 'completed', + progress: 100, + message: 'Quick scan completed', + result: result, + tag: scanTag, + scan_time: new Date().toISOString() + }; + + // write report files into project's reports dir for later retrieval + try { + const reportsDir = path.join(__dirname, '../reports'); + await fs.mkdir(reportsDir, { recursive: true }); + const jsonPath = path.join(reportsDir, `Vulnerability_Scan_Result_${scanIdWithTag}.json`); + await fs.writeFile(jsonPath, JSON.stringify(result, null, 2)); + + // also generate HTML report if requested or default format + if (output_format === 'html' || output_format === 'json') { + // Prefer the project's Python renderer for consistent/identical HTML output + const pythonRenderer = path.join(__dirname, '../Vulnerability_Tool_V2/tools/render_from_json.py'); + const htmlPath = path.join(reportsDir, `Vulnerability_Scan_Report_${scanIdWithTag}.html`); + const tmpJson = path.join(reportsDir, `tmp_${scanIdWithTag}.json`); + await fs.writeFile(tmpJson, JSON.stringify(result, null, 2)); + let wroteHtml = false; + if (await fs.access(pythonRenderer).then(() => true).catch(() => false)) { + // try to run python helper (best-effort without blocking server startup) + const { spawnSync } = require('child_process'); + const scannerPath = path.join(__dirname, '../Vulnerability_Tool_V2'); + const pythonCandidates = [ + path.join(scannerPath, 'venv', 'bin', 'python'), + 'python3', + 'python' + ]; + for (const py of pythonCandidates) { + try { + const spawnRes = spawnSync(py, [pythonRenderer, tmpJson, htmlPath], { cwd: path.join(__dirname, '..'), encoding: 'utf8' }); + if (!spawnRes.error && spawnRes.status === 0) { + wroteHtml = true; + break; + } + } catch (e) { + // ignore and try next + } + } + } + + // remove tmp json + try { await fs.unlink(tmpJson); } catch (e) {} + + if (!wroteHtml) { + // fallback to JS renderer + const html = generateHTMLReport(result); + await fs.writeFile(htmlPath, html); + } + scanInfo.reportPath = htmlPath; + } + } catch (e) { + // non-fatal: keep scanInfo in memory but log message + scanInfo.message += `; Failed to persist reports: ${e.message}`; + } + + activeScanners.set(scanId, scanInfo); + + // Ensure result's own scan_id (if any) doesn't override our generated scanId + const responsePayload = Object.assign({}, result || {}); + responsePayload.scan_id = scanId; + responsePayload.target_path = target_path; + responsePayload.scan_time = scanInfo.scan_time; + + res.json(responsePayload); } catch (error) { res.status(500).json({ @@ -735,11 +836,12 @@ router.post('/quick-scan', async (req, res) => { }); // Start asynchronous Python scan -function startPythonScan(scanId, targetPath, plugins, outputFormat) { +function startPythonScan(scanId, scanTag, targetPath, plugins, outputFormat) { activeScanners.set(scanId, { status: 'running', progress: 0, - message: 'Scan initiated' + message: 'Scan initiated', + tag: scanTag }); const scannerPath = path.join(__dirname, '../Vulnerability_Tool_V2'); @@ -825,7 +927,8 @@ function startPythonScan(scanId, targetPath, plugins, outputFormat) { try { const reportsDir = path.join(__dirname, '../reports'); await fs.mkdir(reportsDir, { recursive: true }); - const htmlPath = path.join(reportsDir, `security_report_${scanId}.html`); + const idWithTag = formatScanIdWithTag(scanId, scanTag); + const htmlPath = path.join(reportsDir, `Vulnerability_Scan_Report_${idWithTag}.html`); await fs.writeFile(htmlPath, scanInfo.htmlReport); scanInfo.reportPath = htmlPath; } catch (e) { @@ -1028,7 +1131,7 @@ function generateHTMLReport(scanResult) { - NutriHelp Security Scan Report + NutriHelp Vulnerability Scan 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/package-lock.json b/package-lock.json index 6cc0206..b62bb4c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -7,6 +7,7 @@ "": { "name": "nutrihelp-api", "version": "1.0.0", + "hasInstallScript": true, "license": "ISC", "dependencies": { "@sendgrid/mail": "^8.1.3", diff --git a/package.json b/package.json index 32370d0..bf6d357 100644 --- a/package.json +++ b/package.json @@ -11,7 +11,11 @@ "security-scan": "python3 scanner_v2.py --format html --output security_report.html", "security-check": "python3 scanner_v2.py --format summary", "test:unit": "mocha ./test/**/*.test.js", - "validate-env": "node scripts/validateEnv.js" + "validate-env": "node scripts/validateEnv.js", + "prepare-scanner": "node scripts/prepareScanner.js", + "ensure-scanner": "node scripts/ensureScannerReady.js", + "setup": "node scripts/bootstrap.js --mode=full", + "postinstall": "node scripts/bootstrap.js --mode=postinstall" }, "jest": { "testMatch": [ diff --git a/routes/scanner.js b/routes/scanner.js index c64938b..ba30e2d 100644 --- a/routes/scanner.js +++ b/routes/scanner.js @@ -33,11 +33,19 @@ function generateScanId(tag = 'scan') { async function resolvePythonExecutable(scannerRoot) { const { spawnSync } = require('child_process'); const path = require('path'); + const envOverride = process.env.PYTHON_EXECUTABLE && process.env.PYTHON_EXECUTABLE.trim(); const candidates = [ + envOverride, // Highest priority: explicit override + // Windows venv locations + path.join(scannerRoot, 'venv', 'Scripts', 'python.exe'), + path.join(scannerRoot, 'venv', 'Scripts', 'python'), + // POSIX venv location path.join(scannerRoot, 'venv', 'bin', 'python'), + // System fallbacks 'python3', - 'python' - ]; + 'python', + 'py' // Windows launcher + ].filter(Boolean); for (const c of candidates) { try { const res = spawnSync(c, ['--version'], { encoding: 'utf8' }); @@ -864,11 +872,16 @@ function startPythonScan(scanId, scanTag, targetPath, plugins, outputFormat) { // Resolve a usable python executable: prefer venv, then system python3, then python function resolvePythonExecutableSync(scannerRoot) { const { spawnSync } = require('child_process'); + const envOverride = process.env.PYTHON_EXECUTABLE && process.env.PYTHON_EXECUTABLE.trim(); const candidates = [ + envOverride, + path.join(scannerRoot, 'venv', 'Scripts', 'python.exe'), + path.join(scannerRoot, 'venv', 'Scripts', 'python'), path.join(scannerRoot, 'venv', 'bin', 'python'), 'python3', - 'python' - ]; + 'python', + 'py' + ].filter(Boolean); for (const c of candidates) { try { const res = spawnSync(c, ['--version'], { encoding: 'utf8' }); @@ -898,8 +911,15 @@ function startPythonScan(scanId, scanTag, targetPath, plugins, outputFormat) { let pythonProcess; try { + // Enforce UTF-8 so emoji / unicode characters don't break on Windows consoles (keep emoji output intact) + const childEnv = Object.assign({}, process.env, { + PYTHONUTF8: '1', + PYTHONIOENCODING: 'utf-8', + SCANNER_PROGRESS: '1' // signal Python side to emit incremental progress lines + }); pythonProcess = spawn(pythonExec, [scriptPath, ...args], { - cwd: scannerPath + cwd: scannerPath, + env: childEnv }); } catch (spawnErr) { const scanInfo = activeScanners.get(scanId); @@ -937,13 +957,30 @@ function startPythonScan(scanId, scanTag, targetPath, plugins, outputFormat) { let outputData = ''; let errorData = ''; + let lineBuffer = ''; // save raw output for debugging pythonProcess.stdout.on('data', (data) => { - outputData += data.toString(); - // Update progress + const chunk = data.toString(); + outputData += chunk; const scanInfo = activeScanners.get(scanId); - console.log('Python output chunk:', data.toString()); // Debug output + lineBuffer += chunk; + // Process complete lines for progress markers + let lines = lineBuffer.split(/\r?\n/); + lineBuffer = lines.pop(); // keep last partial line + for (const line of lines) { + // Progress sentinel format: PROGRESS|| + const m = line.match(/^PROGRESS\|(\d{1,3})(?:\|(.*))?$/); + if (m && scanInfo && scanInfo.status === 'running') { + const pct = Math.max(0, Math.min(100, parseInt(m[1], 10))); + scanInfo.progress = pct; + if (m[2]) { + const msg = m[2].trim(); + // ๅชๅœจไปๅค„ไบŽ running ้˜ถๆฎตๆ—ถๆ›ดๆ–ฐ message๏ผŒๅฎŒๆˆๅŽ็š„ๆˆๅŠŸๆ–‡ๆกˆไฟๆŒๅŽŸๆ ท + if (msg) scanInfo.message = msg; + } + } + } }); pythonProcess.stderr.on('data', (data) => { @@ -1006,7 +1043,11 @@ function startPythonScan(scanId, scanTag, targetPath, plugins, outputFormat) { const maybeResult = parseBestJSON(outputData); scanInfo.status = 'completed'; scanInfo.progress = 100; - scanInfo.message = `Scan completed with non-zero exit code ${code} but output parsed successfully`; + // Keep user-facing message consistent with successful scans + const detailMsg = `Non-zero exit code ${code} but output parsed successfully`; + scanInfo.message = 'Scan completed successfully'; + // Preserve diagnostic detail separately (not exposed unless you add to response) + scanInfo.diagnostic = detailMsg; scanInfo.result = maybeResult; } catch (parseErr) { // Save raw output for non-zero exit as well @@ -1043,8 +1084,13 @@ function runPythonScanSync(targetPath, plugins, outputFormat) { return reject(new Error('No usable Python executable found. Please create Vulnerability_Tool_V2/venv or ensure python3 is available and scanner dependencies are installed.')); } + const childEnv = Object.assign({}, process.env, { + PYTHONUTF8: '1', + PYTHONIOENCODING: 'utf-8' + }); const pythonProcess = spawn(pythonExec, [scriptPath, ...args], { - cwd: scannerPath + cwd: scannerPath, + env: childEnv }); let outputData = ''; @@ -1059,46 +1105,35 @@ function runPythonScanSync(targetPath, plugins, outputFormat) { }); 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); + const attemptParse = () => { + try { return parseBestJSON(outputData); } catch (e) { return null; } + }; + const resultObj = attemptParse(); + if (resultObj) { + // ไปปไฝ•ๆƒ…ๅ†ตไธ‹๏ผˆๅŒ…ๆ‹ฌ้ž้›ถ้€€ๅ‡บ๏ผ‰ๅช่ฆๆˆๅŠŸ่งฃๆžๅฐฑ่ฟ”ๅ›ž็ป“ๆžœ + resolve(resultObj); 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}`)); - } - })(); } - } + // ่‹ฅ็ฌฌไธ€ๆฌก่งฃๆžๅคฑ่ดฅ๏ผŒๅ†ๅฐ่ฏ•ๅ‰ชๆމ stderr ้™„ๅŠ ็š„ๅฐพ้ƒจ๏ผˆๅธธ่ง็ผ–็ ้”™่ฏฏ่กŒ๏ผ‰ + let trimmed = outputData.replace(/Unexpected error:[\s\S]*$/i, '').trim(); + if (!resultObj && trimmed !== outputData) { + try { + const salvage = parseBestJSON(trimmed); + return resolve(salvage); + } catch (_) {} + } + // ไปๅคฑ่ดฅ๏ผŒๅ†™ raw ่พ“ๅ‡บ + (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}`)); + } + })(); }); })(); }); diff --git a/scripts/bootstrap.js b/scripts/bootstrap.js new file mode 100644 index 0000000..939d477 --- /dev/null +++ b/scripts/bootstrap.js @@ -0,0 +1,74 @@ +#!/usr/bin/env node +/** + * bootstrap.js + * One-shot developer setup script: Node deps, scanner venv deps, env template, validation. + * Modes: + * full (default) - Used by "npm run setup" (hard fail on validation errors) + * postinstall - Used automatically after npm install (soft fail: warns only) + */ +const { spawnSync } = require('child_process'); +const fs = require('fs'); +const path = require('path'); + +const modeArg = process.argv.find(a => a.startsWith('--mode=')); +const mode = modeArg ? modeArg.split('=')[1] : 'full'; +const soft = mode === 'postinstall'; + +function log(msg){ console.log(`[bootstrap] ${msg}`); } +function warn(msg){ console.warn(`[bootstrap] WARN: ${msg}`); } +function run(cmd,args,opts){ + const r = spawnSync(cmd,args,Object.assign({stdio:'inherit'},opts)); + if (r.status !== 0) { + console.error(`Command failed: ${cmd} ${args.join(' ')}`); + if (!soft) process.exit(r.status || 1); + else warn(`Continuing despite failure (mode=${mode})`); + } +} + +// 1. Install Node dependencies if node_modules missing +if (!fs.existsSync(path.join(__dirname,'..','node_modules'))) { + log('Installing Node dependencies (npm ci fallback to npm install)...'); + let res = spawnSync('npm',['ci'],{stdio:'inherit'}); + if (res.status !== 0) { + log('npm ci failed, trying npm install'); + res = spawnSync('npm',['install'],{stdio:'inherit'}); + if (res.status !== 0) { + if (!soft) process.exit(res.status); + else warn('Node dependency installation failed during postinstall mode. Project may be unusable.'); + } + } +} else { + log('node_modules present, skipping npm install'); +} + +// 2. Ensure .env (create from example if available) +const envPath = path.join(__dirname,'..','.env'); +const examplePath = path.join(__dirname,'..','.env.example'); +if (!fs.existsSync(envPath)) { + if (fs.existsSync(examplePath)) { + fs.copyFileSync(examplePath, envPath); + log('Created .env from .env.example'); + } else { + fs.writeFileSync(envPath, '# Auto-generated minimal env (edit with real internal secrets)\nJWT_SECRET=change_me_replace_before_prod\nSUPABASE_URL=your_supabase_url\nSUPABASE_ANON_KEY=your_public_anon_key\nPORT=3000\n'); + log('Generated minimal .env (placeholders).'); + } +} else { + log('.env already exists, not touching'); +} + +// 3. Prepare scanner (venv + deps) +log('Preparing vulnerability scanner environment...'); +run(process.execPath, [path.join(__dirname,'prepareScanner.js')]); + +// 4. Validate environment +log('Validating environment variables...'); +const val = spawnSync('npm',['run','validate-env'],{stdio:'inherit'}); +if (val.status !== 0) { + if (soft) { + warn('Environment validation reported issues (non-fatal in postinstall mode).'); + } else { + process.exit(val.status); + } +} + +console.log(`\nโœ… Bootstrap complete (mode=${mode}). You can now run: npm start`); diff --git a/scripts/ensureScannerReady.js b/scripts/ensureScannerReady.js new file mode 100644 index 0000000..d64be4f --- /dev/null +++ b/scripts/ensureScannerReady.js @@ -0,0 +1,43 @@ +#!/usr/bin/env node +/** + * ensureScannerReady.js + * Lightweight check to confirm scanner venv & core dependencies exist; if not, call prepareScanner. + */ +const fs = require('fs'); +const path = require('path'); +const { spawnSync } = require('child_process'); + +const scannerRoot = path.join(__dirname, '..', 'Vulnerability_Tool_V2'); +const venvDir = path.join(scannerRoot, 'venv'); +const markerPip = process.platform === 'win32' ? path.join(venvDir,'Scripts','pip.exe') : path.join(venvDir,'bin','pip'); + +function log(m){ console.log(`[ensure-scanner] ${m}`); } +function run(cmd, args, opts={}){ return spawnSync(cmd,args,Object.assign({encoding:'utf8'},opts)); } + +if (!fs.existsSync(scannerRoot)) { + log('Scanner root not found, nothing to ensure.'); + process.exit(0); +} + +let needPrepare = false; +if (!fs.existsSync(venvDir)) needPrepare = true; +if (!fs.existsSync(markerPip)) needPrepare = true; + +// quick module import probe (yaml, jinja2) using venv python if present +if (!needPrepare) { + const pyExe = process.platform === 'win32' ? path.join(venvDir,'Scripts','python.exe') : path.join(venvDir,'bin','python'); + if (fs.existsSync(pyExe)) { + const probe = run(pyExe, ['-c','import yaml,jinja2']); + if (probe.status !== 0) needPrepare = true; + } else { + needPrepare = true; + } +} + +if (needPrepare) { + log('Scanner environment incomplete; running prepare-scanner'); + const prep = run(process.execPath, [path.join(__dirname,'prepareScanner.js')], { stdio:'inherit' }); + process.exit(prep.status || 0); +} else { + log('Scanner environment is ready.'); +} diff --git a/scripts/prepareScanner.js b/scripts/prepareScanner.js new file mode 100644 index 0000000..b901403 --- /dev/null +++ b/scripts/prepareScanner.js @@ -0,0 +1,90 @@ +#!/usr/bin/env node +/** + * prepareScanner.js + * Recreates Python virtual environment for Vulnerability_Tool_V2 (idempotent) and installs dependencies. + * Safe to run multiple times. Skips work if already up to date. Gracefully degrades if Python is missing. + */ +const { spawnSync } = require('child_process'); +const fs = require('fs'); +const path = require('path'); + +const scannerRoot = path.join(__dirname, '..', 'Vulnerability_Tool_V2'); +const reqFile = path.join(scannerRoot, 'requirements.txt'); +const venvDir = path.join(scannerRoot, 'venv'); + +function log(msg){ console.log(`[prepare-scanner] ${msg}`); } +function warn(msg){ console.warn(`[prepare-scanner] WARN: ${msg}`); } +function err(msg){ console.error(`[prepare-scanner] ERROR: ${msg}`); } + +if (!fs.existsSync(scannerRoot)) { + warn(`Scanner directory not found at ${scannerRoot}, skipping.`); + process.exit(0); +} + +// Determine python executable candidates (prefer explicit override and local project .venv before global) +const localProjectVenv = process.platform === 'win32' + ? path.join(__dirname,'..','.venv','Scripts','python.exe') + : path.join(__dirname,'..','.venv','bin','python'); +const envOverride = process.env.PYTHON_EXECUTABLE && process.env.PYTHON_EXECUTABLE.trim(); +const pythonCandidates = [envOverride, localProjectVenv, 'python3', 'python', 'py'].filter(Boolean); +let pythonExe = null; +for (const c of pythonCandidates) { + try { + const res = spawnSync(c, ['--version'], { encoding: 'utf8' }); + if (!res.error && res.status === 0) { pythonExe = c; break; } + } catch (_) {} +} +if (!pythonExe) { + warn('No usable python interpreter (exit status 0) found. Skipping scanner setup.'); + warn('API will run; scanner endpoints will be unavailable until Python is installed.'); + process.exit(0); +} + +// Create venv if missing +if (!fs.existsSync(venvDir)) { + log(`Creating virtual environment: ${pythonExe} -m venv venv`); + const create = spawnSync(pythonExe, ['-m','venv','venv'], { cwd: scannerRoot, stdio:'inherit' }); + if (create.status !== 0) { + err('Failed to create scanner venv. You may create it manually then rerun this script.'); + process.exit(0); // degrade gracefully + } +} else { + log('Scanner venv already exists, skipping creation'); +} + +// Locate pip +const pipPath = process.platform === 'win32' + ? path.join(venvDir,'Scripts','pip.exe') + : path.join(venvDir,'bin','pip'); +if (!fs.existsSync(pipPath)) { + err(`pip not found at ${pipPath}`); + process.exit(1); +} + +if (!fs.existsSync(reqFile)) { + warn('requirements.txt not found, skipping dependency install'); + process.exit(0); +} + +// Dependency change detection marker +const marker = path.join(venvDir, '.deps_hash'); +let needInstall = true; +try { + const reqStat = fs.statSync(reqFile).mtimeMs; + const markerData = fs.existsSync(marker) ? fs.readFileSync(marker,'utf8') : ''; + if (markerData.trim() === String(reqStat)) needInstall = false; else fs.writeFileSync(marker, String(reqStat)); +} catch { /* ignore */ } + +if (!needInstall) { + log('Dependencies already up to date, skipping pip install'); + process.exit(0); +} + +log('Installing Python scanner dependencies...'); +const install = spawnSync(pipPath, ['install','-r','requirements.txt'], { cwd: scannerRoot, stdio:'inherit' }); +if (install.status !== 0) { + err('pip install failed'); + process.exit(1); +} +log('Scanner dependencies installed successfully.'); + From 690a0651b9a4adf08f1d59fe4fc8018968b50c49 Mon Sep 17 00:00:00 2001 From: Chaohui Li <156674635+ChaohuiLi0321@users.noreply.github.com> Date: Fri, 26 Sep 2025 21:17:15 +1000 Subject: [PATCH 38/39] refactor: remove Python setup and V2 scanner integration from security assessment workflow --- .github/workflows/security-assessment.yml | 22 +--------------------- 1 file changed, 1 insertion(+), 21 deletions(-) diff --git a/.github/workflows/security-assessment.yml b/.github/workflows/security-assessment.yml index 1764f91..9cea4a9 100644 --- a/.github/workflows/security-assessment.yml +++ b/.github/workflows/security-assessment.yml @@ -37,15 +37,6 @@ jobs: - name: Install dependencies run: npm ci - - name: Setup Python 3 (for Vulnerability Scanner V2) - uses: actions/setup-python@v4 - with: - python-version: '3.11' - - - name: Prepare Scanner Environment (V2) - run: | - node scripts/prepareScanner.js || echo "Scanner prepare script exited non-zero (continuing)" - if [ -d Vulnerability_Tool_V2/venv ]; then echo "Scanner venv ready"; else echo "Scanner venv missing, will fallback to system python"; fi - name: Start server in background run: | @@ -94,19 +85,8 @@ jobs: run: | echo "Starting security assessment..." - # Run the assessment + # Run the assessment (original behavior without full V2 scan integration) node security/runAssessment.js - - echo "Running full V2 vulnerability scan (JSON & HTML)..." - PYEXEC="python3" - if [ -f Vulnerability_Tool_V2/venv/bin/python ]; then PYEXEC="Vulnerability_Tool_V2/venv/bin/python"; fi - mkdir -p security/reports || true - if [ -f Vulnerability_Tool_V2/scanner_v2.py ]; then - $PYEXEC Vulnerability_Tool_V2/scanner_v2.py --target . --format json --output security/reports/security-report-v2.json || echo "JSON scan failed" - $PYEXEC Vulnerability_Tool_V2/scanner_v2.py --target . --format html --output security/reports/security-report-v2.html || echo "HTML scan failed" - else - echo "scanner_v2.py not found" > security/reports/security-report-v2.json - fi # Find the latest generated JSON report LATEST_REPORT=$(ls -t security/reports/security-report-*.json 2>/dev/null | head -1) From 74501939200edc131e952b11119312f01d800791 Mon Sep 17 00:00:00 2001 From: Chaohui Li <156674635+ChaohuiLi0321@users.noreply.github.com> Date: Fri, 26 Sep 2025 22:41:42 +1000 Subject: [PATCH 39/39] refactor: remove unused API files and dependencies from the project --- Vulnerability_Tool_V2/api/__init__.py | 6 - Vulnerability_Tool_V2/api/scanner_api.py | 527 ----------------------- Vulnerability_Tool_V2/requirements.txt | 6 - 3 files changed, 539 deletions(-) delete mode 100644 Vulnerability_Tool_V2/api/__init__.py delete mode 100644 Vulnerability_Tool_V2/api/scanner_api.py diff --git a/Vulnerability_Tool_V2/api/__init__.py b/Vulnerability_Tool_V2/api/__init__.py deleted file mode 100644 index c3d5503..0000000 --- a/Vulnerability_Tool_V2/api/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -""" -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 deleted file mode 100644 index b573594..0000000 --- a/Vulnerability_Tool_V2/api/scanner_api.py +++ /dev/null @@ -1,527 +0,0 @@ -#!/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/requirements.txt b/Vulnerability_Tool_V2/requirements.txt index ed62c91..0c7da7d 100644 --- a/Vulnerability_Tool_V2/requirements.txt +++ b/Vulnerability_Tool_V2/requirements.txt @@ -13,9 +13,3 @@ flake8>=5.0.0 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