/**
 * Compliance Mapper
 *
 * Maps adversary findings to compliance framework controls including
 * OWASP LLM Top 10, MITRE ATLAS, MITRE ATT&CK, CWE, SOC 2, ISO 27001,
 * PCI-DSS, and GDPR.
 *
 * @module agents/adversary/reporting/compliance-mapper
 */
import { FOCUS_AREA_MITRE_MAPPING, FOCUS_AREA_CWE_MAPPING, } from "../config.js";
// ============================================================================
// OWASP LLM Top 10 Mapping
// ============================================================================
const OWASP_LLM_CONTROLS = {
    LLM01: {
        id: "LLM01",
        name: "Prompt Injection",
        description: "Manipulating LLMs via crafted inputs to cause unintended actions",
        severity: "critical",
    },
    LLM02: {
        id: "LLM02",
        name: "Insecure Output Handling",
        description: "Failing to validate, sanitize, and handle LLM outputs",
        severity: "high",
    },
    LLM03: {
        id: "LLM03",
        name: "Training Data Poisoning",
        description: "Tampering with training data to introduce vulnerabilities",
        severity: "high",
    },
    LLM04: {
        id: "LLM04",
        name: "Model Denial of Service",
        description: "Overloading LLMs to cause resource exhaustion or service disruption",
        severity: "medium",
    },
    LLM05: {
        id: "LLM05",
        name: "Supply Chain Vulnerabilities",
        description: "Vulnerabilities in LLM supply chain including models and plugins",
        severity: "high",
    },
    LLM06: {
        id: "LLM06",
        name: "Sensitive Information Disclosure",
        description: "LLM revealing confidential data through responses",
        severity: "high",
    },
    LLM07: {
        id: "LLM07",
        name: "Insecure Plugin Design",
        description: "LLM plugins with inadequate access controls or validation",
        severity: "high",
    },
    LLM08: {
        id: "LLM08",
        name: "Excessive Agency",
        description: "LLM granted excessive capability to perform unintended actions",
        severity: "high",
    },
    LLM09: {
        id: "LLM09",
        name: "Overreliance",
        description: "Excessive dependence on LLMs without oversight",
        severity: "medium",
    },
    LLM10: {
        id: "LLM10",
        name: "Model Theft",
        description: "Unauthorized access to or copying of proprietary LLMs",
        severity: "high",
    },
};
// ============================================================================
// CWE Mapping
// ============================================================================
const CWE_DETAILS = {
    "CWE-79": { id: "CWE-79", name: "Cross-site Scripting (XSS)", description: "Improper neutralization of input during web page generation" },
    "CWE-89": { id: "CWE-89", name: "SQL Injection", description: "Improper neutralization of special elements used in SQL command" },
    "CWE-78": { id: "CWE-78", name: "OS Command Injection", description: "Improper neutralization of special elements used in OS command" },
    "CWE-94": { id: "CWE-94", name: "Code Injection", description: "Improper control of generation of code" },
    "CWE-287": { id: "CWE-287", name: "Improper Authentication", description: "Failure to properly verify identity claims" },
    "CWE-352": { id: "CWE-352", name: "Cross-Site Request Forgery (CSRF)", description: "Server accepts requests without verification" },
    "CWE-384": { id: "CWE-384", name: "Session Fixation", description: "Authenticating without invalidating existing session" },
    "CWE-798": { id: "CWE-798", name: "Hardcoded Credentials", description: "Use of hardcoded credentials in code" },
    "CWE-327": { id: "CWE-327", name: "Broken Crypto Algorithm", description: "Use of broken or risky cryptographic algorithm" },
    "CWE-611": { id: "CWE-611", name: "XXE", description: "Improper restriction of XML external entity reference" },
    "CWE-639": { id: "CWE-639", name: "IDOR", description: "Authorization bypass through user-controlled key" },
    "CWE-1336": { id: "CWE-1336", name: "SSTI", description: "Improper neutralization of special elements in template engine" },
};
// ============================================================================
// SOC 2 Mapping
// ============================================================================
const SOC2_CONTROLS = {
    CC6_1: { criteria: "CC6.1", control: "Logical Access", description: "Logical access security over protected information assets" },
    CC6_6: { criteria: "CC6.6", control: "Threat Protection", description: "Protection against unauthorized access" },
    CC6_7: { criteria: "CC6.7", control: "Access Revocation", description: "Restriction and revocation of access" },
    CC7_2: { criteria: "CC7.2", control: "System Monitoring", description: "Monitoring system components for anomalies" },
    CC7_4: { criteria: "CC7.4", control: "Incident Response", description: "Security incident identification and response" },
};
// ============================================================================
// ISO 27001 Mapping
// ============================================================================
const ISO27001_CONTROLS = {
    "A.9.4.1": { control: "A.9.4.1", annex: "A.9", description: "Information access restriction" },
    "A.9.4.2": { control: "A.9.4.2", annex: "A.9", description: "Secure log-on procedures" },
    "A.9.4.4": { control: "A.9.4.4", annex: "A.9", description: "Use of privileged utility programs" },
    "A.12.2.1": { control: "A.12.2.1", annex: "A.12", description: "Controls against malware" },
    "A.14.2.5": { control: "A.14.2.5", annex: "A.14", description: "Secure development principles" },
};
// ============================================================================
// Category to Framework Mapping
// ============================================================================
const CATEGORY_TO_OWASP_LLM = {
    "prompt-injection": "LLM01",
    "insecure-output": "LLM02",
    "training-data-poisoning": "LLM03",
    "model-denial-of-service": "LLM04",
    "supply-chain-vuln": "LLM05",
    "sensitive-disclosure": "LLM06",
    "insecure-plugin": "LLM07",
    "excessive-agency": "LLM08",
    "overreliance": "LLM09",
    "model-theft": "LLM10",
};
const CATEGORY_TO_SOC2 = {
    "authentication": "CC6_1",
    "auth-bypass": "CC6_1",
    "broken-access-control": "CC6_1",
    "sql-injection": "CC6_6",
    "command-injection": "CC6_6",
    "xss": "CC6_6",
    "hardcoded-secret": "CC6_7",
    "session-management": "CC6_7",
};
const CATEGORY_TO_ISO27001 = {
    "authentication": "A.9.4.1",
    "auth-bypass": "A.9.4.2",
    "sql-injection": "A.14.2.5",
    "command-injection": "A.12.2.1",
    "xss": "A.14.2.5",
    "code-injection": "A.12.2.1",
};
// ============================================================================
// Main Mapping Function
// ============================================================================
/**
 * Map a finding to compliance frameworks
 */
export function mapFindingToCompliance(finding, focusArea) {
    const area = focusArea || finding.focusArea || "web-app";
    const category = finding.category || "";
    const result = {
        finding,
        frameworks: {},
        overallRisk: finding.severity,
    };
    // Map to OWASP LLM if applicable
    const owaspLlmId = CATEGORY_TO_OWASP_LLM[category];
    if (owaspLlmId && OWASP_LLM_CONTROLS[owaspLlmId]) {
        result.frameworks.owaspLlm = OWASP_LLM_CONTROLS[owaspLlmId];
    }
    // Map to MITRE ATT&CK
    const mitreIds = finding.mitreAttackTechniques || FOCUS_AREA_MITRE_MAPPING[area] || [];
    if (mitreIds.length > 0) {
        result.frameworks.mitreAttack = {
            technique: mitreIds[0],
            tactic: getTacticForTechnique(mitreIds[0]),
            description: `MITRE ATT&CK technique ${mitreIds[0]}`,
        };
    }
    // Map to MITRE ATLAS for LLM focus area
    if (area === "llm" || category.includes("prompt") || category.includes("llm")) {
        result.frameworks.mitreAtlas = {
            technique: "AML.T0048",
            tactic: "ML Attack Staging",
            description: "LLM Prompt Injection",
        };
    }
    // Map to CWE
    const cweIds = finding.cweIds || FOCUS_AREA_CWE_MAPPING[area] || [];
    if (cweIds.length > 0) {
        const cweId = cweIds[0];
        result.frameworks.cwe = CWE_DETAILS[cweId] || {
            id: cweId,
            name: cweId,
            description: `Common Weakness Enumeration ${cweId}`,
        };
    }
    // Map to SOC 2
    const soc2Control = CATEGORY_TO_SOC2[category];
    if (soc2Control && SOC2_CONTROLS[soc2Control]) {
        result.frameworks.soc2 = SOC2_CONTROLS[soc2Control];
    }
    // Map to ISO 27001
    const iso27001Control = CATEGORY_TO_ISO27001[category];
    if (iso27001Control && ISO27001_CONTROLS[iso27001Control]) {
        result.frameworks.iso27001 = ISO27001_CONTROLS[iso27001Control];
    }
    // Map to PCI-DSS for relevant categories
    if (["sql-injection", "xss", "authentication", "hardcoded-secret"].includes(category)) {
        result.frameworks.pciDss = {
            requirement: "6.5",
            description: "Address common coding vulnerabilities in software development",
        };
    }
    // Map to GDPR for data-related vulnerabilities
    if (["sensitive-disclosure", "pii-exposure", "data-flow"].includes(category) ||
        area === "data-flow") {
        result.frameworks.gdpr = {
            article: "Article 32",
            description: "Security of processing - technical measures",
        };
    }
    return result;
}
/**
 * Map multiple findings to compliance frameworks
 */
export function mapFindingsToCompliance(findings) {
    return findings.map((f) => mapFindingToCompliance(f, f.focusArea));
}
/**
 * Generate compliance summary from mappings
 */
export function generateComplianceSummary(mappings) {
    const summary = {
        totalFindings: mappings.length,
        byFramework: {
            owaspLlm: [],
            mitreAtlas: [],
            mitreAttack: [],
            cwe: [],
            soc2: [],
            iso27001: [],
            pciDss: [],
            gdpr: [],
        },
        bySeverity: {
            critical: 0,
            high: 0,
            medium: 0,
            low: 0,
        },
        affectedControls: [],
    };
    for (const mapping of mappings) {
        // Count by severity (skip "info" as it's not tracked)
        const risk = mapping.overallRisk;
        if (risk === "critical" || risk === "high" || risk === "medium" || risk === "low") {
            summary.bySeverity[risk]++;
        }
        // Collect framework mappings
        if (mapping.frameworks.owaspLlm) {
            addUniqueMapping(summary.byFramework.owaspLlm, mapping.frameworks.owaspLlm.id);
        }
        if (mapping.frameworks.mitreAtlas) {
            addUniqueMapping(summary.byFramework.mitreAtlas, mapping.frameworks.mitreAtlas.technique);
        }
        if (mapping.frameworks.mitreAttack) {
            addUniqueMapping(summary.byFramework.mitreAttack, mapping.frameworks.mitreAttack.technique);
        }
        if (mapping.frameworks.cwe) {
            addUniqueMapping(summary.byFramework.cwe, mapping.frameworks.cwe.id);
        }
        if (mapping.frameworks.soc2) {
            addUniqueMapping(summary.byFramework.soc2, mapping.frameworks.soc2.criteria);
        }
        if (mapping.frameworks.iso27001) {
            addUniqueMapping(summary.byFramework.iso27001, mapping.frameworks.iso27001.control);
        }
        if (mapping.frameworks.pciDss) {
            addUniqueMapping(summary.byFramework.pciDss, mapping.frameworks.pciDss.requirement);
        }
        if (mapping.frameworks.gdpr) {
            addUniqueMapping(summary.byFramework.gdpr, mapping.frameworks.gdpr.article);
        }
    }
    // Collect all affected controls
    summary.affectedControls = [
        ...summary.byFramework.owaspLlm,
        ...summary.byFramework.soc2,
        ...summary.byFramework.iso27001,
        ...summary.byFramework.pciDss,
    ];
    return summary;
}
// ============================================================================
// Helper Functions
// ============================================================================
function getTacticForTechnique(techniqueId) {
    const tacticMap = {
        T1059: "Execution",
        T1078: "Defense Evasion",
        T1110: "Credential Access",
        T1190: "Initial Access",
        T1203: "Execution",
        T1539: "Credential Access",
        T1552: "Credential Access",
        T1556: "Credential Access",
        "AML.T0043": "ML Attack Staging",
        "AML.T0048": "ML Attack Staging",
        "AML.T0051": "ML Attack Staging",
    };
    return tacticMap[techniqueId] || "Unknown";
}
function addUniqueMapping(array, value) {
    if (!array.includes(value)) {
        array.push(value);
    }
}
// ============================================================================
// Formatting Functions
// ============================================================================
/**
 * Format compliance mapping as markdown
 */
export function formatComplianceMappingAsMarkdown(mapping) {
    const lines = [
        `## Compliance Mapping: ${mapping.finding.id}`,
        "",
        `**Overall Risk:** ${mapping.overallRisk.toUpperCase()}`,
        "",
        "### Framework Mappings",
    ];
    if (mapping.frameworks.owaspLlm) {
        lines.push(`- **OWASP LLM:** ${mapping.frameworks.owaspLlm.id} - ${mapping.frameworks.owaspLlm.name}`);
    }
    if (mapping.frameworks.mitreAtlas) {
        lines.push(`- **MITRE ATLAS:** ${mapping.frameworks.mitreAtlas.technique} (${mapping.frameworks.mitreAtlas.tactic})`);
    }
    if (mapping.frameworks.mitreAttack) {
        lines.push(`- **MITRE ATT&CK:** ${mapping.frameworks.mitreAttack.technique} (${mapping.frameworks.mitreAttack.tactic})`);
    }
    if (mapping.frameworks.cwe) {
        lines.push(`- **CWE:** ${mapping.frameworks.cwe.id} - ${mapping.frameworks.cwe.name}`);
    }
    if (mapping.frameworks.soc2) {
        lines.push(`- **SOC 2:** ${mapping.frameworks.soc2.criteria} - ${mapping.frameworks.soc2.control}`);
    }
    if (mapping.frameworks.iso27001) {
        lines.push(`- **ISO 27001:** ${mapping.frameworks.iso27001.control} (${mapping.frameworks.iso27001.annex})`);
    }
    if (mapping.frameworks.pciDss) {
        lines.push(`- **PCI-DSS:** Requirement ${mapping.frameworks.pciDss.requirement}`);
    }
    if (mapping.frameworks.gdpr) {
        lines.push(`- **GDPR:** ${mapping.frameworks.gdpr.article}`);
    }
    return lines.join("\n");
}
/**
 * Format compliance summary as markdown
 */
export function formatComplianceSummaryAsMarkdown(summary) {
    const lines = [
        "# Compliance Summary",
        "",
        `**Total Findings:** ${summary.totalFindings}`,
        "",
        "## By Severity",
        `- Critical: ${summary.bySeverity.critical}`,
        `- High: ${summary.bySeverity.high}`,
        `- Medium: ${summary.bySeverity.medium}`,
        `- Low: ${summary.bySeverity.low}`,
        "",
        "## Framework Coverage",
    ];
    if (summary.byFramework.owaspLlm.length > 0) {
        lines.push(`- **OWASP LLM Top 10:** ${summary.byFramework.owaspLlm.join(", ")}`);
    }
    if (summary.byFramework.mitreAtlas.length > 0) {
        lines.push(`- **MITRE ATLAS:** ${summary.byFramework.mitreAtlas.join(", ")}`);
    }
    if (summary.byFramework.mitreAttack.length > 0) {
        lines.push(`- **MITRE ATT&CK:** ${summary.byFramework.mitreAttack.join(", ")}`);
    }
    if (summary.byFramework.cwe.length > 0) {
        lines.push(`- **CWE:** ${summary.byFramework.cwe.join(", ")}`);
    }
    if (summary.byFramework.soc2.length > 0) {
        lines.push(`- **SOC 2:** ${summary.byFramework.soc2.join(", ")}`);
    }
    if (summary.byFramework.iso27001.length > 0) {
        lines.push(`- **ISO 27001:** ${summary.byFramework.iso27001.join(", ")}`);
    }
    return lines.join("\n");
}
//# sourceMappingURL=compliance-mapper.js.map