/**
 * OWASP Threat Database — Built-in OWASP Top 10 (2021) + CWE Patterns
 *
 * This is the Sentinel's knowledge base of known vulnerability patterns.
 * Updated daily via the threat sync service and seeded with OWASP Top 10.
 */

import { SecurityPattern, OwaspCategory } from './types';

/** OWASP Top 10 — 2021 Edition with detection patterns */
export const OWASP_TOP_10_2021: OwaspCategory[] = [
  {
    id: 'A01:2021',
    name: 'Broken Access Control',
    description: 'Restrictions on what authenticated users are allowed to do are often not properly enforced.',
    year: 2021,
    patterns: [
      {
        name: 'Missing Auth Check',
        cweId: 'CWE-284',
        keywords: ['req.body', 'req.query', 'params.id', 'DELETE', 'PUT', 'PATCH'],
        severity: 'critical',
        description: 'API route modifies/deletes data without verifying user authorization',
        remediation: 'Add session validation and ownership checks before data modification. Use getServerSession() or middleware auth guards.',
      },
      {
        name: 'IDOR — Insecure Direct Object Reference',
        cweId: 'CWE-639',
        keywords: ['params.id', 'findUnique', 'findFirst', 'where: { id'],
        severity: 'high',
        description: 'Direct database lookup by user-supplied ID without ownership verification',
        remediation: 'Always filter by both resource ID and authenticated userId. Never trust client-supplied IDs alone.',
      },
      {
        name: 'Missing CORS Configuration',
        cweId: 'CWE-346',
        keywords: ['Access-Control-Allow-Origin', '*'],
        severity: 'medium',
        description: 'Wildcard CORS allows any origin to make requests',
        remediation: 'Restrict Access-Control-Allow-Origin to specific trusted domains.',
      },
    ],
  },
  {
    id: 'A02:2021',
    name: 'Cryptographic Failures',
    description: 'Failures related to cryptography which often lead to sensitive data exposure.',
    year: 2021,
    patterns: [
      {
        name: 'Hardcoded Secret',
        cweId: 'CWE-798',
        regex: '(?:password|secret|api_key|apikey|token|auth)\\s*[:=]\\s*["\'][^"\']+("|\')',
        keywords: ['password =', 'secret =', 'apiKey =', 'token ='],
        severity: 'critical',
        description: 'Sensitive credential hardcoded in source code',
        remediation: 'Move all secrets to environment variables. Use process.env for runtime access.',
      },
      {
        name: 'Weak Hashing',
        cweId: 'CWE-328',
        keywords: ['md5', 'sha1', 'createHash("md5")', 'createHash("sha1")'],
        severity: 'high',
        description: 'Use of weak hash algorithm (MD5/SHA1) for security-sensitive operations',
        remediation: 'Use bcrypt for passwords, SHA-256+ for integrity checks.',
      },
      {
        name: 'Unencrypted Sensitive Data',
        cweId: 'CWE-311',
        keywords: ['localStorage.setItem', 'sessionStorage.setItem'],
        severity: 'medium',
        description: 'Sensitive data stored in browser storage without encryption',
        remediation: 'Use httpOnly cookies for auth tokens. Encrypt any data stored client-side.',
      },
    ],
  },
  {
    id: 'A03:2021',
    name: 'Injection',
    description: 'User-supplied data is not validated, filtered, or sanitized by the application.',
    year: 2021,
    patterns: [
      {
        name: 'SQL Injection',
        cweId: 'CWE-89',
        regex: '\\$\\{.*\\}.*(?:SELECT|INSERT|UPDATE|DELETE|FROM|WHERE)',
        keywords: ['$queryRaw', '$executeRaw', 'raw(', 'query('],
        severity: 'critical',
        description: 'Raw SQL with interpolated user input enables SQL injection',
        remediation: 'Use Prisma parameterized queries or $queryRaw with Prisma.sql tagged template.',
      },
      {
        name: 'XSS — Cross-Site Scripting',
        cweId: 'CWE-79',
        keywords: ['dangerouslySetInnerHTML', 'innerHTML', 'document.write'],
        severity: 'high',
        description: 'User input rendered as raw HTML without sanitization',
        remediation: 'Sanitize HTML with DOMPurify or use React\'s built-in escaping. Avoid dangerouslySetInnerHTML.',
      },
      {
        name: 'Command Injection',
        cweId: 'CWE-78',
        keywords: ['exec(', 'execSync(', 'spawn(', 'child_process'],
        severity: 'critical',
        description: 'System command execution with potentially unsanitized input',
        remediation: 'Never pass user input to exec/spawn. Use parameterized commands or allowlists.',
      },
    ],
  },
  {
    id: 'A04:2021',
    name: 'Insecure Design',
    description: 'Risks related to design and architectural flaws.',
    year: 2021,
    patterns: [
      {
        name: 'Missing Rate Limiting',
        cweId: 'CWE-770',
        keywords: ['POST', 'api/', 'route.ts'],
        severity: 'medium',
        description: 'API endpoint without rate limiting is vulnerable to abuse',
        remediation: 'Implement rate limiting middleware for sensitive endpoints (auth, payments, data creation).',
      },
      {
        name: 'Missing Input Validation',
        cweId: 'CWE-20',
        keywords: ['req.body', 'request.json()', 'JSON.parse'],
        severity: 'medium',
        description: 'Request body parsed without schema validation',
        remediation: 'Validate all input with Zod, Yup, or similar schema validation library before processing.',
      },
    ],
  },
  {
    id: 'A05:2021',
    name: 'Security Misconfiguration',
    description: 'Missing appropriate security hardening across any part of the application stack.',
    year: 2021,
    patterns: [
      {
        name: 'Debug Mode in Production',
        cweId: 'CWE-489',
        keywords: ['console.log(', 'console.debug(', 'DEBUG=true', 'NODE_ENV !== "production"'],
        severity: 'low',
        description: 'Debug statements or debug mode flags that may leak information in production',
        remediation: 'Remove console.log statements or use a structured logging library with level control.',
      },
      {
        name: 'Missing Security Headers',
        cweId: 'CWE-693',
        keywords: ['next.config', 'headers()', 'Content-Security-Policy'],
        severity: 'medium',
        description: 'Missing security headers (CSP, X-Frame-Options, etc.)',
        remediation: 'Configure security headers in next.config.js or middleware.',
      },
    ],
  },
  {
    id: 'A06:2021',
    name: 'Vulnerable and Outdated Components',
    description: 'Using components with known vulnerabilities.',
    year: 2021,
    patterns: [
      {
        name: 'Known Vulnerable Dependency',
        cweId: 'CWE-1104',
        keywords: ['package.json', 'yarn.lock', 'node_modules'],
        severity: 'high',
        description: 'Application uses dependencies with known security vulnerabilities',
        remediation: 'Run yarn audit regularly. Update vulnerable packages. Use Snyk or similar SCA tools.',
      },
    ],
  },
  {
    id: 'A07:2021',
    name: 'Identification and Authentication Failures',
    description: 'Confirmation of the user\'s identity, authentication, and session management is critical.',
    year: 2021,
    patterns: [
      {
        name: 'Weak Password Policy',
        cweId: 'CWE-521',
        keywords: ['password.length', 'minLength: 4', 'minLength: 6'],
        severity: 'medium',
        description: 'Password policy allows weak passwords (less than 8 characters)',
        remediation: 'Enforce minimum 8 characters with complexity requirements (uppercase, lowercase, number, special).',
      },
      {
        name: 'Missing Session Timeout',
        cweId: 'CWE-613',
        keywords: ['maxAge', 'session', 'jwt', 'expires'],
        severity: 'medium',
        description: 'Session or JWT tokens without expiration can be exploited indefinitely',
        remediation: 'Set appropriate session timeouts. Use short-lived JWTs with refresh token rotation.',
      },
    ],
  },
  {
    id: 'A08:2021',
    name: 'Software and Data Integrity Failures',
    description: 'Relating to code and infrastructure that does not protect against integrity violations.',
    year: 2021,
    patterns: [
      {
        name: 'Unsafe Deserialization',
        cweId: 'CWE-502',
        keywords: ['JSON.parse', 'eval(', 'Function(', 'new Function'],
        severity: 'high',
        description: 'Parsing untrusted data without validation can lead to code execution',
        remediation: 'Validate JSON schema after parsing. Never use eval() on user input.',
      },
    ],
  },
  {
    id: 'A09:2021',
    name: 'Security Logging and Monitoring Failures',
    description: 'Without logging and monitoring, breaches cannot be detected.',
    year: 2021,
    patterns: [
      {
        name: 'Silent Error Handling',
        cweId: 'CWE-390',
        regex: 'catch\\s*\\([^)]*\\)\\s*\\{\\s*\\}',
        keywords: ['catch (', 'catch(e)', '// ignore', '// swallow'],
        severity: 'medium',
        description: 'Empty catch blocks swallow errors, hiding security incidents',
        remediation: 'Log all errors with structured logging. Alert on security-relevant errors.',
      },
    ],
  },
  {
    id: 'A10:2021',
    name: 'Server-Side Request Forgery (SSRF)',
    description: 'SSRF flaws occur when a web application fetches a remote resource without validating the user-supplied URL.',
    year: 2021,
    patterns: [
      {
        name: 'Unvalidated URL Fetch',
        cweId: 'CWE-918',
        keywords: ['fetch(', 'axios.get(', 'axios.post(', 'http.get('],
        severity: 'high',
        description: 'Server-side fetch with user-controlled URL enables SSRF attacks',
        remediation: 'Validate and allowlist URLs before server-side fetching. Block internal IPs and metadata endpoints.',
      },
    ],
  },
];

/**
 * OWASP Threat Database Manager
 * Maintains and queries the threat knowledge base
 */
export class OwaspThreatDb {
  private categories: OwaspCategory[] = OWASP_TOP_10_2021;

  getAllCategories(): OwaspCategory[] {
    return this.categories;
  }

  getCategory(id: string): OwaspCategory | undefined {
    return this.categories.find(c => c.id === id);
  }

  getAllPatterns(): SecurityPattern[] {
    return this.categories.flatMap(c => c.patterns);
  }

  getPatternsBySeverity(severity: string): SecurityPattern[] {
    return this.getAllPatterns().filter(p => p.severity === severity);
  }

  getCriticalPatterns(): SecurityPattern[] {
    return this.getPatternsBySeverity('critical');
  }

  getThreatCount(): number {
    return this.getAllPatterns().length;
  }

  getStats() {
    const patterns = this.getAllPatterns();
    return {
      totalCategories: this.categories.length,
      totalPatterns: patterns.length,
      critical: patterns.filter(p => p.severity === 'critical').length,
      high: patterns.filter(p => p.severity === 'high').length,
      medium: patterns.filter(p => p.severity === 'medium').length,
      low: patterns.filter(p => p.severity === 'low').length,
      version: 'OWASP Top 10 — 2021',
      lastUpdated: new Date().toISOString(),
    };
  }
}

export const owaspThreatDb = new OwaspThreatDb();
