/**
 * Threat Modeling Knowledge Module
 *
 * STRIDE methodology, attack trees, threat matrix templates,
 * and risk prioritization frameworks.
 *
 * @module agents/experts/knowledge/security/threat-modeling
 * @see NIST 800-53: RA-3, RA-5
 * (Source: Epic #643 / Issue #645 - Phase 1a)
 */

import type { KnowledgeModule } from '../types.js';

export const THREAT_MODELING_MODULE: KnowledgeModule = {
  id: 'security-threat-modeling',
  domain: 'security',
  title: 'Threat Modeling with STRIDE',
  nistControls: ['RA-3', 'RA-5'],
  tags: ['threat-modeling', 'stride', 'attack-trees', 'risk-assessment'],
  sections: [
    {
      title: 'STRIDE Categories',
      content: [
        'S — SPOOFING (violates Authentication):',
        '  Threat: Attacker impersonates a user or system',
        '  Examples: Credential theft, session hijacking, token forgery',
        '  Mitigations: MFA, mutual TLS, signed tokens, certificate pinning',
        'T — TAMPERING (violates Integrity):',
        '  Threat: Attacker modifies data in transit or at rest',
        '  Examples: Man-in-middle, SQL injection, file modification',
        '  Mitigations: TLS, HMAC signatures, input validation, checksums',
        'R — REPUDIATION (violates Non-repudiation):',
        '  Threat: Attacker denies performing an action',
        '  Examples: Deleting logs, unsigned transactions',
        '  Mitigations: Audit logging, digital signatures, append-only logs',
        'I — INFORMATION DISCLOSURE (violates Confidentiality):',
        '  Threat: Data exposed to unauthorized parties',
        '  Examples: Verbose errors, directory listing, unencrypted PII',
        '  Mitigations: Encryption at rest/transit, access control, data masking',
        'D — DENIAL OF SERVICE (violates Availability):',
        '  Threat: System rendered unavailable',
        '  Examples: Resource exhaustion, amplification attacks, deadlocks',
        '  Mitigations: Rate limiting, auto-scaling, circuit breakers, CDN',
        'E — ELEVATION OF PRIVILEGE (violates Authorization):',
        '  Threat: Attacker gains higher privileges',
        '  Examples: Privilege escalation, IDOR, insecure deserialization',
        '  Mitigations: Least privilege, input validation, sandboxing',
      ].join('\n'),
      priority: 10,
    },
    {
      title: 'Threat Modeling Process',
      content: [
        'STEP 1 — Define Scope:',
        '  - Identify system boundaries and trust boundaries',
        '  - List assets (data, services, infrastructure)',
        '  - Identify entry points (APIs, UIs, message queues)',
        'STEP 2 — Create Data Flow Diagram (DFD):',
        '  - External entities (users, third-party services)',
        '  - Processes (services, functions)',
        '  - Data stores (databases, caches, file systems)',
        '  - Data flows (arrows showing data movement)',
        '  - Trust boundaries (dashed lines separating trust zones)',
        'STEP 3 — Identify Threats:',
        '  - Apply STRIDE to each element in the DFD',
        '  - Focus on trust boundary crossings',
        '  - Document threat scenarios with attacker goals',
        'STEP 4 — Assess and Prioritize:',
        '  - Use risk matrix (likelihood x impact)',
        '  - Categorize: Critical / High / Medium / Low',
        'STEP 5 — Define Mitigations:',
        '  - Map each threat to specific controls',
        '  - Track in issue tracker with severity labels',
      ].join('\n'),
      priority: 9,
    },
    {
      title: 'Attack Surface Mapping',
      content: [
        'IDENTIFY ATTACK SURFACE:',
        '  - Network: open ports, exposed services, DNS records',
        '  - Application: API endpoints, file upload, auth flows',
        '  - Human: phishing targets, social engineering vectors',
        '  - Supply chain: dependencies, build pipeline, CI/CD',
        'REDUCE ATTACK SURFACE:',
        '  - Disable unused services and ports',
        '  - Remove debug endpoints in production',
        '  - Minimize public API surface area',
        '  - Use network segmentation (VPC, subnets)',
        '  - Pin and audit third-party dependencies',
        'MONITOR:',
        '  - Track new endpoints added per release',
        '  - Alert on unexpected port openings',
        '  - Review dependency additions in PRs',
      ].join('\n'),
      priority: 8,
    },
    {
      title: 'Risk Prioritization Matrix',
      content: [
        'LIKELIHOOD SCALE:',
        '  5-Certain: Exploit publicly known, trivial to execute',
        '  4-Likely: Exploit known, requires moderate skill',
        '  3-Possible: Exploit theoretical, requires significant skill',
        '  2-Unlikely: Requires insider access + specialized knowledge',
        '  1-Rare: Requires multiple unlikely conditions',
        'IMPACT SCALE:',
        '  5-Critical: Full system compromise, mass data breach',
        '  4-High: Significant data exposure, service outage',
        '  3-Medium: Limited data exposure, degraded service',
        '  2-Low: Minor information leak, no direct harm',
        '  1-Negligible: Cosmetic, no security impact',
        'RISK SCORE: Likelihood x Impact (1-25)',
        '  Critical (20-25): Immediate remediation, block release',
        '  High (12-19): Remediate within current sprint',
        '  Medium (6-11): Schedule for next sprint',
        '  Low (1-5): Track in backlog, accept risk if justified',
      ].join('\n'),
      priority: 8,
    },
    {
      title: 'Attack Tree Template',
      content: [
        'ROOT GOAL: [Attacker objective, e.g., "Exfiltrate user PII"]',
        'BRANCHES (OR = any path, AND = all required):',
        '  OR 1: Exploit API vulnerability',
        '    AND 1.1: Discover undocumented endpoint (recon)',
        '    AND 1.2: Bypass authentication (BOLA, broken auth)',
        '    AND 1.3: Extract data (pagination abuse, export)',
        '  OR 2: Compromise credentials',
        '    AND 2.1: Phishing attack on admin user',
        '    AND 2.2: Use credentials to access admin panel',
        '    AND 2.3: Export user data via admin tools',
        '  OR 3: Supply chain attack',
        '    AND 3.1: Compromise dependency with data exfil payload',
        '    AND 3.2: Wait for dependency update in target system',
        'ANNOTATE each node with: likelihood, impact, existing controls, gaps',
        'USE: Identify cheapest attack path for attacker = highest priority to defend',
      ].join('\n'),
      priority: 7,
    },
  ],
} as const;
