"use strict";
/**
 * Rule Metadata Registry
 *
 * Provides comprehensive metadata for all vulnerability categories including:
 * - whyItMatters: Business impact explanation
 * - fixSteps: Step-by-step remediation guidance
 * - evidence: What triggers this finding
 * - references: OWASP/CWE documentation links
 *
 * This metadata enables actionable output for every finding,
 * regardless of whether AI validation is used.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.RULE_REGISTRY = void 0;
exports.getRuleMetadata = getRuleMetadata;
exports.getAllCategories = getAllCategories;
exports.hasMetadata = hasMetadata;
/**
 * Comprehensive metadata registry for all vulnerability categories
 */
exports.RULE_REGISTRY = {
    // ==========================================================================
    // Secrets & Credentials
    // ==========================================================================
    hardcoded_secret: {
        name: 'Hardcoded Secret',
        whyItMatters: 'Hardcoded secrets in source code can be extracted from version control history or compiled binaries, leading to unauthorized access to APIs, databases, or infrastructure.',
        fixSteps: [
            'Remove the secret from source code immediately',
            'Rotate the compromised credential (generate a new one)',
            'Store the new secret in environment variables or a secrets manager',
            'Update your code to read from process.env or your secrets manager',
            'Verify the old secret is invalidated and not in git history',
        ],
        evidence: 'Detected a pattern matching known API key or credential formats',
        references: [
            'https://owasp.org/www-community/vulnerabilities/Use_of_hard-coded_password',
            'https://cwe.mitre.org/data/definitions/798.html',
        ],
    },
    high_entropy_string: {
        name: 'High Entropy String',
        whyItMatters: 'High-entropy strings often indicate secrets, API keys, or tokens that may be unintentionally exposed, potentially granting attackers access to protected resources.',
        fixSteps: [
            'Verify whether this string is actually a secret or credential',
            'If it is a secret, move it to environment variables',
            'If it is a hash, constant, or non-sensitive data, consider adding an inline suppression comment',
            'Use a secrets manager for production deployments',
        ],
        evidence: 'String has high Shannon entropy (randomness) characteristic of secrets',
        references: [
            'https://owasp.org/www-community/vulnerabilities/Use_of_hard-coded_password',
            'https://cwe.mitre.org/data/definitions/798.html',
        ],
    },
    sensitive_variable: {
        name: 'Sensitive Variable Name',
        whyItMatters: 'Variables with names suggesting sensitive data (password, secret, key) may indicate hardcoded credentials or improper handling of sensitive information.',
        fixSteps: [
            'Review whether this variable contains actual sensitive data',
            'If so, ensure the value comes from environment variables or a secrets manager',
            'Never log or expose this variable in error messages or responses',
            'Consider using more generic variable names if the data is not actually sensitive',
        ],
        evidence: 'Variable name matches sensitive patterns (password, secret, apiKey, etc.)',
        references: [
            'https://owasp.org/www-project-web-security-testing-guide/latest/4-Web_Application_Security_Testing/04-Authentication_Testing/04-Testing_for_Weak_Password_Policy',
        ],
    },
    // ==========================================================================
    // Injection Vulnerabilities
    // ==========================================================================
    sql_injection: {
        name: 'SQL Injection',
        whyItMatters: 'SQL injection allows attackers to read, modify, or delete database records, bypass authentication, and potentially execute commands on the database server.',
        fixSteps: [
            'Replace string concatenation with parameterized queries or prepared statements',
            'Use your ORM\'s query builder instead of raw SQL',
            'Validate and sanitize all user inputs before use',
            'Apply the principle of least privilege to database accounts',
        ],
        evidence: 'User input is concatenated into SQL query strings',
        references: [
            'https://owasp.org/www-community/attacks/SQL_Injection',
            'https://cwe.mitre.org/data/definitions/89.html',
        ],
    },
    xss: {
        name: 'Cross-Site Scripting (XSS)',
        whyItMatters: 'XSS allows attackers to inject malicious scripts into web pages, stealing user sessions, credentials, or sensitive data displayed to victims.',
        fixSteps: [
            'Escape all user input before rendering in HTML',
            'Use framework-provided sanitization (React JSX auto-escapes)',
            'Avoid innerHTML, document.write, or dangerouslySetInnerHTML with user data',
            'Implement Content Security Policy (CSP) headers',
        ],
        evidence: 'User input flows to DOM sinks without proper escaping',
        references: [
            'https://owasp.org/www-community/attacks/xss/',
            'https://cwe.mitre.org/data/definitions/79.html',
        ],
    },
    command_injection: {
        name: 'Command Injection',
        whyItMatters: 'Command injection allows attackers to execute arbitrary system commands, potentially taking full control of the server, accessing sensitive files, or pivoting to other systems.',
        fixSteps: [
            'Avoid passing user input to shell commands entirely',
            'If shell commands are necessary, use parameterized execution (execFile, not exec)',
            'Validate and sanitize inputs against a strict allowlist',
            'Use language-native libraries instead of shell commands where possible',
        ],
        evidence: 'User input is passed to shell execution functions',
        references: [
            'https://owasp.org/www-community/attacks/Command_Injection',
            'https://cwe.mitre.org/data/definitions/78.html',
        ],
    },
    // ==========================================================================
    // Authentication & Authorization
    // ==========================================================================
    missing_auth: {
        name: 'Missing Authentication',
        whyItMatters: 'Endpoints without authentication can be accessed by anyone, potentially exposing sensitive data or allowing unauthorized actions.',
        fixSteps: [
            'Add authentication middleware to protect this route',
            'Verify user identity using session tokens, JWTs, or API keys',
            'Implement authorization checks to ensure users can only access their own data',
            'For public endpoints, document them explicitly and ensure they expose no sensitive data',
        ],
        evidence: 'Route handler lacks visible authentication checks',
        references: [
            'https://owasp.org/API-Security/editions/2023/en/0xa2-broken-authentication/',
            'https://cwe.mitre.org/data/definitions/306.html',
        ],
    },
    security_bypass: {
        name: 'Security Bypass Logic',
        whyItMatters: 'Security bypass patterns (like checking for admin in predictable ways) may allow attackers to circumvent access controls and gain unauthorized privileges.',
        fixSteps: [
            'Review the authentication and authorization logic',
            'Ensure bypass conditions are intentional and documented',
            'Use proper role-based access control (RBAC) instead of flag-based checks',
            'Log all uses of bypass mechanisms for audit purposes',
        ],
        evidence: 'Code contains patterns that could bypass security checks',
        references: [
            'https://owasp.org/www-project-web-security-testing-guide/latest/4-Web_Application_Security_Testing/04-Authentication_Testing/',
            'https://cwe.mitre.org/data/definitions/284.html',
        ],
    },
    // ==========================================================================
    // Data Exposure
    // ==========================================================================
    data_exposure: {
        name: 'Data Exposure',
        whyItMatters: 'Exposing sensitive data in logs, error messages, or API responses can leak credentials, personal information, or system details to attackers.',
        fixSteps: [
            'Review what data is being logged or returned in responses',
            'Remove sensitive fields before logging or sending to clients',
            'Use structured logging with field filtering for sensitive data',
            'Return generic error messages to users, log details server-side only',
        ],
        evidence: 'Sensitive data may be exposed in logs or responses',
        references: [
            'https://owasp.org/www-project-web-security-testing-guide/latest/4-Web_Application_Security_Testing/09-Testing_for_Weak_Cryptography/04-Testing_for_Weak_Encryption',
            'https://cwe.mitre.org/data/definitions/200.html',
        ],
    },
    sensitive_url: {
        name: 'Sensitive URL',
        whyItMatters: 'Hardcoded URLs may expose internal services, development endpoints, or contain sensitive information that could be exploited by attackers.',
        fixSteps: [
            'Move URLs to environment variables or configuration files',
            'Use different configurations for development and production',
            'Ensure internal service URLs are not exposed in client-side code',
            'Review whether the URL exposes sensitive paths or parameters',
        ],
        evidence: 'URL detected that may expose sensitive endpoints or internal services',
        references: [
            'https://owasp.org/www-project-web-security-testing-guide/latest/4-Web_Application_Security_Testing/02-Configuration_and_Deployment_Management_Testing/',
        ],
    },
    // ==========================================================================
    // Configuration & Infrastructure
    // ==========================================================================
    insecure_config: {
        name: 'Insecure Configuration',
        whyItMatters: 'Insecure configuration settings can disable security features, expose debug information, or weaken encryption, making the application vulnerable to attacks.',
        fixSteps: [
            'Review the configuration value and understand its security implications',
            'Enable security features that are disabled (HTTPS, CORS restrictions, etc.)',
            'Use secure defaults and environment-specific configuration',
            'Audit all configuration changes for security impact',
        ],
        evidence: 'Configuration setting detected that weakens security posture',
        references: [
            'https://owasp.org/www-project-web-security-testing-guide/latest/4-Web_Application_Security_Testing/02-Configuration_and_Deployment_Management_Testing/',
            'https://cwe.mitre.org/data/definitions/16.html',
        ],
    },
    cors_misconfiguration: {
        name: 'CORS Misconfiguration',
        whyItMatters: 'Overly permissive CORS settings (like origin: "*") can allow malicious websites to make authenticated requests to your API, potentially stealing user data.',
        fixSteps: [
            'Replace wildcard origin ("*") with a specific list of allowed origins',
            'Validate the Origin header against your allowlist',
            'Disable credentials (cookies, auth headers) for cross-origin requests unless necessary',
            'Review which endpoints truly need CORS access',
        ],
        evidence: 'CORS configuration allows requests from any origin',
        references: [
            'https://owasp.org/www-community/attacks/CORS_OriginHeaderScrutiny',
            'https://cwe.mitre.org/data/definitions/942.html',
        ],
    },
    root_container: {
        name: 'Container Running as Root',
        whyItMatters: 'Containers running as root give attackers full privileges if compromised, allowing them to escape the container or access the host system.',
        fixSteps: [
            'Add a USER directive to your Dockerfile to run as non-root',
            'Create a dedicated user for your application',
            'Ensure file permissions allow the non-root user to operate',
            'Use rootless container runtimes where possible',
        ],
        evidence: 'Dockerfile or container config runs processes as root user',
        references: [
            'https://docs.docker.com/develop/develop-images/dockerfile_best-practices/#user',
            'https://cwe.mitre.org/data/definitions/250.html',
        ],
    },
    // ==========================================================================
    // Dangerous Functions & Patterns
    // ==========================================================================
    dangerous_function: {
        name: 'Dangerous Function',
        whyItMatters: 'Functions like eval(), innerHTML, or exec() can execute arbitrary code if passed untrusted input, leading to code injection or XSS attacks.',
        fixSteps: [
            'Identify whether the input to this function is user-controlled',
            'Replace with safer alternatives (JSON.parse instead of eval, textContent instead of innerHTML)',
            'If the dangerous function is necessary, validate and sanitize all inputs',
            'Consider using a sandboxed execution environment for code evaluation',
        ],
        evidence: 'Use of function known to be dangerous when handling untrusted input',
        references: [
            'https://owasp.org/www-community/attacks/Code_Injection',
            'https://cwe.mitre.org/data/definitions/95.html',
        ],
    },
    weak_crypto: {
        name: 'Weak Cryptography',
        whyItMatters: 'Weak cryptographic algorithms (MD5, SHA1, DES) or insecure random number generation can be broken by attackers, compromising data confidentiality and integrity.',
        fixSteps: [
            'Replace weak hash functions (MD5, SHA1) with SHA-256 or stronger',
            'Use crypto.randomBytes() or crypto.getRandomValues() for security-sensitive randomness',
            'Replace DES/3DES with AES-256-GCM for encryption',
            'Use established libraries for cryptographic operations',
        ],
        evidence: 'Use of cryptographic functions known to be weak or deprecated',
        references: [
            'https://owasp.org/www-project-web-security-testing-guide/latest/4-Web_Application_Security_Testing/09-Testing_for_Weak_Cryptography/',
            'https://cwe.mitre.org/data/definitions/327.html',
        ],
    },
    dangerous_file: {
        name: 'Dangerous File Operation',
        whyItMatters: 'Unsafe file operations can lead to path traversal attacks, allowing attackers to read or write arbitrary files on the server.',
        fixSteps: [
            'Validate and sanitize all file paths before use',
            'Use path.join() with a base directory to prevent traversal',
            'Implement an allowlist of permitted directories',
            'Set appropriate file permissions and chroot where possible',
        ],
        evidence: 'File operation may be vulnerable to path traversal',
        references: [
            'https://owasp.org/www-community/attacks/Path_Traversal',
            'https://cwe.mitre.org/data/definitions/22.html',
        ],
    },
    // ==========================================================================
    // Supply Chain & Dependencies
    // ==========================================================================
    suspicious_package: {
        name: 'Suspicious Package',
        whyItMatters: 'Unknown or typosquatted packages may be malicious, potentially executing harmful code, stealing credentials, or compromising your build pipeline.',
        fixSteps: [
            'Verify the package name is correct and matches the intended library',
            'Check the package on npm/PyPI for legitimacy (downloads, maintainers, repo)',
            'If suspicious, remove the dependency and find an alternative',
            'Use lockfiles and integrity checking to prevent supply chain attacks',
        ],
        evidence: 'Package may be typosquatted, AI-hallucinated, or otherwise suspicious',
        references: [
            'https://owasp.org/www-project-dependency-check/',
            'https://cwe.mitre.org/data/definitions/829.html',
        ],
    },
    // ==========================================================================
    // AI-Specific Categories
    // ==========================================================================
    ai_pattern: {
        name: 'AI-Generated Code Pattern',
        whyItMatters: 'AI-generated code may contain subtle security issues, use deprecated patterns, or include placeholder code that should be reviewed before production use.',
        fixSteps: [
            'Review this code section for security best practices',
            'Verify any hardcoded values are intentional',
            'Check for proper error handling and input validation',
            'Ensure the code follows your team\'s security standards',
        ],
        evidence: 'Code pattern suggests AI-generated content that may need review',
        references: [
            'https://owasp.org/www-project-top-ten/',
        ],
    },
    ai_prompt_injection: {
        name: 'AI Prompt Injection',
        whyItMatters: 'User input included in AI prompts without proper sanitization can manipulate the AI\'s behavior, potentially extracting sensitive data or performing unauthorized actions.',
        fixSteps: [
            'Separate user input from system instructions using clear delimiters',
            'Use role-based prompting (system vs user messages) in your LLM API calls',
            'Validate and sanitize user inputs before including in prompts',
            'Implement output filtering to catch potential jailbreak attempts',
        ],
        evidence: 'User input flows directly into AI prompt without sanitization',
        references: [
            'https://owasp.org/www-project-top-10-for-large-language-model-applications/',
            'https://genai.owasp.org/llmrisk/llm01-prompt-injection/',
        ],
    },
    ai_unsafe_execution: {
        name: 'AI Unsafe Execution',
        whyItMatters: 'Executing AI-generated code or SQL without validation can lead to code injection, data manipulation, or system compromise.',
        fixSteps: [
            'Never execute AI output directly without validation',
            'Use sandboxed environments (vm2, isolated-vm) for code execution',
            'Apply parameterized queries for any AI-generated SQL',
            'Implement strict output schema validation before use',
        ],
        evidence: 'AI-generated content flows to dangerous execution sinks',
        references: [
            'https://owasp.org/www-project-top-10-for-large-language-model-applications/',
            'https://genai.owasp.org/llmrisk/llm02-insecure-output-handling/',
        ],
    },
    ai_overpermissive_tool: {
        name: 'AI Overpermissive Tool',
        whyItMatters: 'AI agent tools with excessive permissions can be exploited through prompt injection to access sensitive data, execute commands, or bypass security controls.',
        fixSteps: [
            'Apply principle of least privilege to all AI agent tools',
            'Implement user-scoped access controls in tool implementations',
            'Add allowlists for permitted operations (files, URLs, commands)',
            'Require explicit user confirmation for sensitive operations',
        ],
        evidence: 'AI agent tool has broad permissions without proper restrictions',
        references: [
            'https://owasp.org/www-project-top-10-for-large-language-model-applications/',
            'https://genai.owasp.org/llmrisk/llm08-excessive-agency/',
        ],
    },
    ai_rag_exfiltration: {
        name: 'AI RAG Data Exfiltration',
        whyItMatters: 'RAG systems without proper access controls can leak data across tenant boundaries or expose sensitive information in retrieved context.',
        fixSteps: [
            'Add user/tenant filtering to all vector store queries',
            'Validate that retrieved documents belong to the requesting user',
            'Filter or redact sensitive fields before returning RAG results',
            'Implement RLS (Row Level Security) at the database level',
        ],
        evidence: 'RAG query lacks user/tenant scoping or exposes raw context',
        references: [
            'https://owasp.org/www-project-top-10-for-large-language-model-applications/',
            'https://genai.owasp.org/llmrisk/llm06-sensitive-information-disclosure/',
        ],
    },
    ai_endpoint_unprotected: {
        name: 'AI Endpoint Unprotected',
        whyItMatters: 'Unprotected AI endpoints can incur significant API costs from abuse and may allow attackers to extract system prompts or manipulate AI behavior.',
        fixSteps: [
            'Add authentication middleware to protect AI endpoints',
            'Implement rate limiting to prevent abuse',
            'Consider usage quotas per user to control costs',
            'Log and monitor AI endpoint usage for anomalies',
        ],
        evidence: 'AI/LLM endpoint lacks authentication or rate limiting',
        references: [
            'https://owasp.org/API-Security/editions/2023/en/0xa2-broken-authentication/',
            'https://genai.owasp.org/',
        ],
    },
    ai_schema_mismatch: {
        name: 'AI Schema Validation Missing',
        whyItMatters: 'AI-generated structured output without schema validation may contain malformed data, unexpected types, or malicious payloads that cause application errors or security issues.',
        fixSteps: [
            'Define a strict schema for expected AI output (using zod, joi, or ajv)',
            'Validate all AI responses against the schema before use',
            'Use OpenAI Structured Outputs or similar features where available',
            'Implement fallback handling for validation failures',
        ],
        evidence: 'AI output is parsed or used without schema validation',
        references: [
            'https://owasp.org/www-project-top-10-for-large-language-model-applications/',
            'https://genai.owasp.org/llmrisk/llm02-insecure-output-handling/',
        ],
    },
    // ==========================================================================
    // AI Detection Roadmap Phase 1
    // ==========================================================================
    ai_package_hallucination: {
        name: 'AI Package Hallucination',
        whyItMatters: 'AI-generated code frequently references packages that don\'t exist (USENIX research shows ~20% hallucination rate). Attackers can register these fake package names and inject malicious code into your supply chain.',
        fixSteps: [
            'Verify the package exists: run "npm view <package>" or check npmjs.com',
            'Search for the correct package name that provides the functionality you need',
            'Remove the hallucinated dependency from package.json',
            'Consider using AI coding assistants with package validation enabled',
        ],
        evidence: 'Package name matches known hallucination patterns or verified fake packages',
        references: [
            'https://arxiv.org/abs/2406.10279',
            'https://owasp.org/www-project-dependency-check/',
            'https://cwe.mitre.org/data/definitions/829.html',
        ],
    },
    ai_rag_corpus_poisoning: {
        name: 'RAG Corpus Poisoning Risk',
        whyItMatters: 'User-uploaded content directly embedded into RAG corpus without sanitization can inject malicious instructions, causing the AI to leak data, execute harmful actions, or provide manipulated responses.',
        fixSteps: [
            'Sanitize and validate all user uploads before embedding',
            'Strip or escape instruction-like content from documents',
            'Implement content classification to detect prompt injection attempts',
            'Use separate corpus namespaces for different trust levels',
        ],
        evidence: 'User upload flows directly to embedding/indexing without sanitization',
        references: [
            'https://owasp.org/www-project-top-10-for-large-language-model-applications/',
            'https://genai.owasp.org/llmrisk/llm03-training-data-poisoning/',
        ],
    },
    ai_rag_pii_leakage: {
        name: 'RAG PII Leakage',
        whyItMatters: 'PII (Personally Identifiable Information) in RAG-indexed documents may be exposed in retrieval responses, violating privacy regulations and user trust.',
        fixSteps: [
            'Scan documents for PII before embedding (names, emails, SSNs, etc.)',
            'Redact or mask PII in documents before indexing',
            'Filter PII fields from retrieval responses',
            'Implement access controls to restrict who can query which documents',
        ],
        evidence: 'PII fields detected in embedded documents or retrieval responses',
        references: [
            'https://genai.owasp.org/llmrisk/llm06-sensitive-information-disclosure/',
            'https://owasp.org/www-community/vulnerabilities/Information_exposure_through_an_error_message',
        ],
    },
    ai_mcp_tool_poisoning: {
        name: 'MCP Tool Poisoning',
        whyItMatters: 'MCP (Model Context Protocol) tools that return unvalidated external content can be exploited through indirect prompt injection, causing the AI to execute malicious instructions embedded in the content.',
        fixSteps: [
            'Validate and sanitize all external content before returning in tool responses',
            'Strip instruction-like patterns from retrieved content',
            'Implement content classification to detect injection attempts',
            'Use structured output formats instead of free-form text where possible',
        ],
        evidence: 'MCP tool returns external content without validation or sanitization',
        references: [
            'https://modelcontextprotocol.io/docs/concepts/tools',
            'https://genai.owasp.org/llmrisk/llm01-prompt-injection/',
            'https://invariantlabs.ai/blog/mcp-security-notification-tool-poisoning-attacks',
        ],
    },
    ai_mcp_credential_issue: {
        name: 'MCP Credential Exposure',
        whyItMatters: 'MCP tools exposing credentials in parameters or responses can leak sensitive authentication tokens, API keys, or user credentials to the AI model or logs.',
        fixSteps: [
            'Never pass credentials as tool parameters - use server-side auth',
            'Filter credentials from tool responses before returning to the model',
            'Use OAuth or session-based auth instead of passing tokens',
            'Audit MCP tool responses for credential patterns',
        ],
        evidence: 'MCP tool parameter or response contains credential patterns',
        references: [
            'https://modelcontextprotocol.io/docs/concepts/tools',
            'https://cwe.mitre.org/data/definitions/522.html',
        ],
    },
    ai_mcp_confused_deputy: {
        name: 'MCP Confused Deputy',
        whyItMatters: 'MCP tools performing operations without proper user context can be exploited to access other users\' data or perform unauthorized actions (confused deputy attack).',
        fixSteps: [
            'Always pass and validate user context in tool implementations',
            'Implement proper authorization checks within tool handlers',
            'Use session-scoped credentials, not shared service accounts',
            'Log user context with all tool operations for audit trails',
        ],
        evidence: 'MCP tool performs data operations without user/tenant scoping',
        references: [
            'https://modelcontextprotocol.io/docs/concepts/tools',
            'https://cwe.mitre.org/data/definitions/441.html',
            'https://genai.owasp.org/llmrisk/llm08-excessive-agency/',
        ],
    },
    // ==========================================================================
    // Phase 1 Enhancement Backlog
    // ==========================================================================
    ai_mcp_description_injection: {
        name: 'MCP Tool Description Injection',
        whyItMatters: 'Tool descriptions containing user input or prompt injection keywords can manipulate AI behavior, causing it to ignore instructions, bypass security controls, or execute unintended actions.',
        fixSteps: [
            'Use static, hardcoded descriptions for all MCP tools',
            'Never interpolate user input into tool descriptions',
            'Avoid manipulation keywords (ignore, bypass, override) in descriptions',
            'Review and audit all tool metadata for injection vectors',
        ],
        evidence: 'MCP tool description contains dynamic content or injection keywords',
        references: [
            'https://modelcontextprotocol.io/docs/concepts/tools',
            'https://genai.owasp.org/llmrisk/llm01-prompt-injection/',
            'https://arxiv.org/abs/2302.12173',
        ],
    },
    ai_mcp_server_shadowing: {
        name: 'MCP Server Shadowing Risk',
        whyItMatters: 'MCP server configuration from untrusted sources can allow attackers to inject malicious servers that shadow legitimate tools, intercepting data or executing malicious actions.',
        fixSteps: [
            'Define MCP servers in code, not from environment variables or user input',
            'Validate server URLs against an explicit allowlist',
            'Implement tool name conflict detection',
            'Use signed server manifests where supported',
        ],
        evidence: 'MCP server configuration loaded from user input or environment',
        references: [
            'https://modelcontextprotocol.io/docs/concepts/transports',
            'https://cwe.mitre.org/data/definitions/441.html',
        ],
    },
    ai_mcp_config_secrets: {
        name: 'MCP Config Contains Secrets',
        whyItMatters: 'Secrets hardcoded in MCP configuration files can be exposed through version control, logs, or file access, leading to unauthorized API access or credential theft.',
        fixSteps: [
            'Move all secrets to environment variables',
            'Use a secrets manager for production deployments',
            'Reference secrets as ${ENV_VAR} in config files',
            'Ensure MCP config files are not committed to version control',
        ],
        evidence: 'API key, token, or secret found in MCP configuration file',
        references: [
            'https://cwe.mitre.org/data/definitions/798.html',
            'https://owasp.org/www-community/vulnerabilities/Use_of_hard-coded_password',
        ],
    },
    ai_mcp_config_permissions: {
        name: 'MCP Overpermissive Config',
        whyItMatters: 'Overly permissive MCP settings (disabled approval, wildcard permissions, infinite timeouts) reduce security controls and increase the blast radius of potential attacks.',
        fixSteps: [
            'Enable tool approval for sensitive operations',
            'Explicitly list allowed tools instead of using wildcards',
            'Set reasonable timeouts for tool execution',
            'Enable TLS/HTTPS for all remote MCP servers',
        ],
        evidence: 'MCP configuration disables security features or uses overpermissive settings',
        references: [
            'https://modelcontextprotocol.io/docs/concepts/tools',
            'https://cwe.mitre.org/data/definitions/732.html',
        ],
    },
    ai_rag_query_injection: {
        name: 'RAG Query Injection',
        whyItMatters: 'User input flowing directly to RAG queries without validation can manipulate retrieval results, potentially surfacing unauthorized data or injecting adversarial instructions.',
        fixSteps: [
            'Validate and sanitize user queries before retrieval',
            'Implement query length limits and content validation',
            'Use parameterized queries where supported',
            'Add rate limiting to prevent query abuse',
        ],
        evidence: 'User input flows to vector store query without validation',
        references: [
            'https://genai.owasp.org/llmrisk/llm01-prompt-injection/',
            'https://owasp.org/www-project-top-10-for-large-language-model-applications/',
        ],
    },
    ai_rag_embedding_poisoning: {
        name: 'RAG Embedding Poisoning',
        whyItMatters: 'User-controlled content embedded without validation can poison the vector corpus with adversarial documents designed to manipulate retrieval results or inject malicious instructions.',
        fixSteps: [
            'Validate and sanitize user content before embedding',
            'Implement content classification to detect malicious documents',
            'Set similarity thresholds to filter low-relevance results',
            'Check for duplicate or near-duplicate documents before embedding',
        ],
        evidence: 'User content embedded without validation or similarity threshold missing',
        references: [
            'https://genai.owasp.org/llmrisk/llm03-training-data-poisoning/',
            'https://arxiv.org/abs/2310.19156',
        ],
    },
    ai_rag_chunk_injection: {
        name: 'RAG Chunk Boundary Exploitation',
        whyItMatters: 'Improper chunk handling can allow attackers to inject content that spans chunk boundaries, potentially manipulating context or injecting instructions that bypass per-chunk validation.',
        fixSteps: [
            'Validate each chunk individually before embedding',
            'Use clear separators when joining retrieved chunks',
            'Generate chunk metadata server-side, not from user input',
            'Configure appropriate chunk sizes and overlap',
        ],
        evidence: 'User content chunked without validation or chunks joined without separators',
        references: [
            'https://genai.owasp.org/llmrisk/llm01-prompt-injection/',
            'https://owasp.org/www-project-top-10-for-large-language-model-applications/',
        ],
    },
    ai_package_typosquat: {
        name: 'Package Typosquatting',
        whyItMatters: 'Typosquatting attacks use package names similar to popular packages to trick developers into installing malicious code. These packages can steal credentials, inject backdoors, or exfiltrate data.',
        fixSteps: [
            'Verify the package name is correct (check spelling against the popular package)',
            'Run "npm view <package>" to confirm the package exists and is legitimate',
            'Review the package\'s repository, maintainers, and recent activity',
            'Consider using lockfiles and integrity hashes to prevent substitution',
        ],
        evidence: 'Package name is very similar to a popular package (possible typosquat)',
        references: [
            'https://snyk.io/blog/typosquatting-attacks/',
            'https://cwe.mitre.org/data/definitions/829.html',
            'https://owasp.org/www-project-dependency-check/',
        ],
    },
    ai_package_malicious: {
        name: 'Malicious Package',
        whyItMatters: 'This package has been flagged as malicious by security advisories. It may contain malware, data exfiltration code, or other harmful functionality that could compromise your systems.',
        fixSteps: [
            'Remove this package immediately from your dependencies',
            'Audit your codebase for any data the package may have accessed',
            'Check for unexpected network connections or file access',
            'Rotate any credentials that may have been exposed',
            'Report the incident to your security team',
        ],
        evidence: 'Package flagged as malicious in OSV.dev or security advisories',
        references: [
            'https://osv.dev/',
            'https://socket.dev/blog/npm-malware',
            'https://cwe.mitre.org/data/definitions/506.html',
        ],
    },
    // ==========================================================================
    // AI Detection Roadmap Phase 2
    // ==========================================================================
    ai_unsafe_model_load: {
        name: 'Unsafe Model Loading',
        whyItMatters: 'Loading ML models with pickle, joblib, or torch.load enables arbitrary code execution. Attackers can embed malicious code in model files that runs when the model is loaded, compromising your entire system.',
        fixSteps: [
            'Use weights_only=True for torch.load() to load only tensors',
            'Use safe_mode=True for TensorFlow/Keras model loading',
            'Prefer SafeTensors format over pickle-based formats',
            'Download models only from trusted sources (official repos)',
            'Verify model checksums/hashes before loading',
        ],
        evidence: 'Detected pickle.load, joblib.load, or torch.load without safe mode',
        references: [
            'https://genai.owasp.org/llmrisk/llm05-supply-chain-vulnerabilities/',
            'https://cwe.mitre.org/data/definitions/502.html',
            'https://huggingface.co/docs/safetensors/index',
        ],
    },
    ai_unverified_model: {
        name: 'Unverified Model Source',
        whyItMatters: 'Loading ML models without integrity verification allows attackers to serve poisoned models via man-in-the-middle attacks or compromised registries. Malicious models can produce harmful outputs or contain backdoors.',
        fixSteps: [
            'Download models from official sources (Hugging Face Hub, official repos)',
            'Verify model checksums/hashes against published values',
            'Use model signing and verification where available',
            'Pin specific model revisions instead of latest',
            'Avoid trust_remote_code=True unless absolutely necessary',
        ],
        evidence: 'Model loaded from untrusted source or without integrity verification',
        references: [
            'https://genai.owasp.org/llmrisk/llm05-supply-chain-vulnerabilities/',
            'https://cwe.mitre.org/data/definitions/494.html',
            'https://cwe.mitre.org/data/definitions/829.html',
        ],
    },
    ai_unsafe_finetuning: {
        name: 'Unsafe Fine-tuning Data',
        whyItMatters: 'Training or fine-tuning models on unvalidated user data enables data poisoning attacks. Attackers can inject malicious examples that cause the model to learn harmful behaviors, bypass safety measures, or leak sensitive information.',
        fixSteps: [
            'Validate and sanitize all training data before use',
            'Implement content moderation for user-contributed training data',
            'Use data versioning and auditing for training datasets',
            'Monitor model behavior for signs of poisoning',
            'Separate user data from trusted training sources',
        ],
        evidence: 'Training/fine-tuning on user uploads or unvalidated data sources',
        references: [
            'https://genai.owasp.org/llmrisk/llm03-training-data-poisoning/',
            'https://cwe.mitre.org/data/definitions/20.html',
            'https://atlas.mitre.org/techniques/AML.T0020',
        ],
    },
    ai_excessive_agency: {
        name: 'Excessive Agent Autonomy',
        whyItMatters: 'AI agents with unbounded execution (no iteration limits, timeouts, or human oversight) can run indefinitely, consume excessive resources, or take harmful actions without human review. This is especially dangerous when combined with code execution or external tool access.',
        fixSteps: [
            'Set explicit maxIterations limits (e.g., maxIterations: 10)',
            'Configure reasonable timeouts for agent execution',
            'Enable human-in-the-loop for destructive operations',
            'Implement cost/budget limits for API usage',
            'Use Docker containers for code execution (never bare metal)',
        ],
        evidence: 'Agent configuration with unbounded loops, no timeout, or disabled human oversight',
        references: [
            'https://genai.owasp.org/llmrisk/llm08-excessive-agency/',
            'https://cwe.mitre.org/data/definitions/250.html',
            'https://docs.crewai.com/concepts/security',
        ],
    },
    // ==========================================================================
    // OWASP Workstream 1: Classic Vulnerability Detectors
    // ==========================================================================
    missing_security_headers: {
        name: 'Missing Security Headers',
        whyItMatters: 'Missing HTTP security headers (CSP, HSTS, X-Frame-Options) leave the application vulnerable to clickjacking, MIME sniffing, XSS, and man-in-the-middle attacks.',
        fixSteps: [
            'Add helmet middleware for Express apps: app.use(helmet())',
            'Configure Content-Security-Policy to restrict resource loading',
            'Enable HSTS (Strict-Transport-Security) for HTTPS enforcement',
            'Set X-Frame-Options to prevent clickjacking',
            'Add X-Content-Type-Options: nosniff to prevent MIME sniffing',
        ],
        evidence: 'Server configuration missing critical HTTP security headers',
        references: [
            'https://owasp.org/www-project-secure-headers/',
            'https://cwe.mitre.org/data/definitions/693.html',
        ],
    },
    ssrf: {
        name: 'Server-Side Request Forgery (SSRF)',
        whyItMatters: 'SSRF allows attackers to make the server send requests to unintended locations, potentially accessing internal services, cloud metadata endpoints, or performing port scanning from within the network.',
        fixSteps: [
            'Validate and sanitize all user-supplied URLs before making server-side requests',
            'Implement an allowlist of permitted domains or IP ranges',
            'Block requests to private IP ranges (127.0.0.1, 10.x, 192.168.x, 169.254.x)',
            'Use a URL parser to validate the scheme, host, and port',
            'Consider using a proxy service for user-supplied URLs',
        ],
        evidence: 'User-controlled input flows to server-side HTTP request without validation',
        references: [
            'https://owasp.org/www-community/attacks/Server_Side_Request_Forgery',
            'https://cwe.mitre.org/data/definitions/918.html',
        ],
    },
    log_injection: {
        name: 'Log Injection',
        whyItMatters: 'Unsanitized user input in log statements can forge log entries, inject CRLF sequences to create fake log lines, or exploit log processing tools via injection attacks.',
        fixSteps: [
            'Sanitize user input before including in log messages (strip newlines, control characters)',
            'Use structured logging (JSON format) instead of string interpolation',
            'Parameterize log fields instead of concatenating user input',
            'Implement log output encoding appropriate to the log format',
        ],
        evidence: 'User-controlled request data flows directly into log statements',
        references: [
            'https://owasp.org/www-community/attacks/Log_Injection',
            'https://cwe.mitre.org/data/definitions/117.html',
        ],
    },
    xxe: {
        name: 'XML External Entity (XXE) Injection',
        whyItMatters: 'XXE vulnerabilities allow attackers to read server files, perform SSRF, execute denial-of-service attacks (billion laughs), and potentially achieve remote code execution through XML parsing.',
        fixSteps: [
            'Disable external entity processing in your XML parser',
            'Use defusedxml (Python) instead of standard xml library',
            'Set factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true) in Java',
            'Use JSON instead of XML where possible',
            'Upgrade XML parsing libraries to versions with secure defaults',
        ],
        evidence: 'XML parser used without disabling external entity processing',
        references: [
            'https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing',
            'https://cwe.mitre.org/data/definitions/611.html',
        ],
    },
    // ==========================================================================
    // Agent Skill File Security
    // ==========================================================================
    ai_skill_injection: {
        name: 'Agent Skill Injection',
        whyItMatters: 'AI agent skill/configuration files define agent behavior. Prompt injection, data exfiltration commands, or hidden execution patterns in these files can compromise the agent, exfiltrate sensitive data, or execute arbitrary code on the host system.',
        fixSteps: [
            'Review the skill file for any instructions that override safety guidelines',
            'Remove any shell commands that pipe remote content to execution (curl | sh)',
            'Remove any references to sensitive files or environment variables',
            'Check for hidden Unicode characters using a hex editor or unicode inspector',
            'Ensure tool descriptions do not contain injection language',
        ],
        evidence: 'Detected prompt injection, data exfiltration, or hidden execution pattern in agent skill file',
        references: [
            'https://owasp.org/www-project-top-10-for-large-language-model-applications/',
            'https://cwe.mitre.org/data/definitions/77.html',
        ],
    },
};
/**
 * Get metadata for a vulnerability category
 * Returns undefined if category is not in registry (shouldn't happen for valid categories)
 */
function getRuleMetadata(category) {
    return exports.RULE_REGISTRY[category];
}
/**
 * Get all available rule categories
 */
function getAllCategories() {
    return Object.keys(exports.RULE_REGISTRY);
}
/**
 * Check if a category has metadata
 */
function hasMetadata(category) {
    return category in exports.RULE_REGISTRY;
}
//# sourceMappingURL=metadata.js.map