"use strict";
/**
 * PCI DSS v4.0.1 Compliance Pack
 *
 * Payment Card Industry Data Security Standard v4.0.1 (current
 * mandatory version) for AI systems that store, process, or transmit
 * cardholder data.
 *
 * Key dates:
 *   - 31 March 2024: PCI DSS v3.2.1 retired
 *   - 31 March 2025: All v4.0 "future-dated" best-practice requirements
 *     became mandatory
 *   - June 2024: v4.0.1 published with corrections to v4.0
 *   - PCI DSS v4.0.1 is the ONLY current valid version in 2026
 *
 * Current state (2026):
 *   - 12 core requirements + 250+ sub-requirements now all mandatory.
 *   - Targeted risk analysis required for customised approach.
 *   - Annual penetration testing + quarterly ASV scanning.
 *   - Enhanced MFA: required for ALL access into cardholder data
 *     environment (CDE), not just admin.
 *   - AI/ML scope: any system materially involved in processing
 *     cardholder data is in scope; model outputs touching CDE require
 *     corresponding controls.
 *   - Service provider responsibilities clarified (Req 12.8, 12.9).
 *
 * P1C-04 (2026-04-24): Added payment-specific category classifiers:
 *   PAN (Luhn-valid, BIN-prefixed), CVV, CARD_EXPIRY, TRACK_DATA,
 *   CARDHOLDER_NAME. subjectKeyedCategories: PAN, CVV, TRACK_DATA.
 *   TransactionContext pass-through for PCI Req-10 audit fields.
 *
 * @connexum/ai-governance
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.PCIDSS_PACK = exports.PCIDSS_CATEGORY_CLASSIFIERS = void 0;
exports.derivePciEventType = derivePciEventType;
// ---------------------------------------------------------------------------
// Luhn algorithm (Req 3.4: detect PANs, not just any digit sequence)
// ---------------------------------------------------------------------------
/**
 * Validate a numeric string (digits only) using the Luhn algorithm.
 * PCI DSS Req 3.4 requires Luhn-valid sequences to be treated as PANs.
 */
function luhnValid(digits) {
    let sum = 0;
    let double = false;
    for (let i = digits.length - 1; i >= 0; i--) {
        let d = parseInt(digits[i], 10);
        if (double) {
            d *= 2;
            if (d > 9)
                d -= 9;
        }
        sum += d;
        double = !double;
    }
    return sum % 10 === 0;
}
/**
 * PAN (Primary Account Number) classifier.
 *
 * Detects 13-19 digit sequences that:
 *   1. Match a recognised card-brand BIN prefix (Visa 4, Mastercard 51-55,
 *      Amex 34/37, Discover 6011/65).
 *   2. Pass the Luhn algorithm (Req 3.4).
 *
 * Spaces and hyphens between digit groups are normalised before testing
 * so "4111 1111 1111 1111" and "4111-1111-1111-1111" both match.
 */
const PAN_OUTER = /\b(?:4\d{3}[\s\-]?\d{4}[\s\-]?\d{4}[\s\-]?\d{1,4}|5[1-5]\d{2}[\s\-]?\d{4}[\s\-]?\d{4}[\s\-]?\d{4}|3[47]\d{2}[\s\-]?\d{6}[\s\-]?\d{5}|(?:6011|65\d{2})[\s\-]?\d{4}[\s\-]?\d{4}[\s\-]?\d{4})\b/g;
function panClassifier(input) {
    PAN_OUTER.lastIndex = 0;
    let match;
    while ((match = PAN_OUTER.exec(input)) !== null) {
        const digits = match[0].replace(/[\s\-]/g, '');
        if (digits.length >= 13 && digits.length <= 19 && luhnValid(digits)) {
            return true;
        }
    }
    return false;
}
/**
 * CVV (Card Verification Value) classifier.
 *
 * Detects a 3 or 4 digit value in proximity to CVV/CVC/CV2/security code
 * context words. Proximity = within 30 characters of the label.
 * This avoids false positives on standalone 3-digit numbers.
 *
 * Covers: cvv, cvc, cvc2, cv2, cvv2, security code, verification value,
 * card code, card security code.
 */
const CVV_PATTERN = /(?:cvv2?|cvc2?|cv2|security\s*code|verification\s*value|card\s*(?:security\s*)?code)[:\s\-]*\d{3,4}\b/i;
/**
 * CARD_EXPIRY classifier.
 *
 * Detects MM/YY or MM/YYYY (or MM-YY / MM-YYYY) in payment context.
 * Payment context = within the same sentence/line as payment-related words
 * (card, expir, payment, visa, mastercard, amex, discover).
 */
const CARD_EXPIRY_PATTERN = /\b(?:0[1-9]|1[0-2])[\/-](?:\d{2}|\d{4})\b/;
const PAYMENT_CONTEXT_WORDS = /\b(?:card|expir|payment|visa|mastercard|amex|discover|credit|debit|cardholder)\b/i;
function cardExpiryClassifier(input) {
    if (!CARD_EXPIRY_PATTERN.test(input))
        return false;
    return PAYMENT_CONTEXT_WORDS.test(input);
}
/**
 * TRACK_DATA classifier.
 *
 * Detects magnetic stripe track 1 or track 2 sentinel patterns.
 *   Track 1: starts with % B or % followed by digits, contains ^ separators
 *   Track 2: starts with ; followed by digits, contains = separator, ends with ?
 *
 * Pattern follows ISO/IEC 7813 (financial transaction card format).
 */
const TRACK_DATA_PATTERN = /(?:%[Bb][A-Z0-9\s]{1,19}\^[A-Z\s\/]{2,26}\^\d{4}\d{3}[\d\s]{1,15}[\?*]?|;\d{13,19}=\d{4}\d{3}[\d\s]{1,15}\?)/;
/**
 * CARDHOLDER_NAME classifier.
 *
 * Detects a name field explicitly labelled in a payment-form context.
 * Lone personal names are not CHD; the label "cardholder" / "name on card"
 * is required. Action is LOG (informational; name alone is not Sensitive
 * Authentication Data but is part of the merchant record set).
 */
const CARDHOLDER_NAME_PATTERN = /(?:cardholder\s+name|name\s+on\s+(?:card|account)|card(?:holder)?\s*[:\-]\s*[A-Z][a-z]+\s+[A-Z][a-z]+)/i;
// ---------------------------------------------------------------------------
// Exported category classifiers (W1 pack-driven classifier contract)
// ---------------------------------------------------------------------------
exports.PCIDSS_CATEGORY_CLASSIFIERS = {
    PAN: {
        references: [
            'PCI DSS v4.0.1 Req 3.4 -- Render PAN unreadable anywhere it is stored',
            'PCI DSS v4.0.1 Req 3.3 -- SAD must not be stored after authorization',
        ],
        classifier: (input) => panClassifier(input),
    },
    CVV: {
        references: [
            'PCI DSS v4.0.1 Req 3.2.1 -- SAD (CVV/CVC) must never be retained after authorization',
        ],
        pattern: CVV_PATTERN,
    },
    CARD_EXPIRY: {
        references: [
            'PCI DSS v4.0.1 Req 3.3 -- Sensitive authentication data not stored after authorization',
        ],
        classifier: (input) => cardExpiryClassifier(input),
    },
    TRACK_DATA: {
        references: [
            'PCI DSS v4.0.1 Req 3.2.1 -- Full track data (magnetic stripe) must never be retained',
        ],
        pattern: TRACK_DATA_PATTERN,
    },
    CARDHOLDER_NAME: {
        references: [
            'PCI DSS v4.0.1 Req 3.3 -- Cardholder name is part of the account data set',
        ],
        pattern: CARDHOLDER_NAME_PATTERN,
    },
    SAD: {
        references: [
            'PCI DSS v4.0.1 Req 3.2.1 -- Sensitive Authentication Data (SAD) must not be stored after authorization',
        ],
        // Broad SAD pattern: PIN blocks, cryptograms, service codes in context
        pattern: /\b(?:pin\s*block|cryptogram|service\s*code|magnetic\s*stripe|chip\s*data|emv\s*data)[:\s]*[A-Za-z0-9+\/=]{4,}/i,
    },
    CREDENTIALS: {
        references: [
            'PCI DSS v4.0.1 Req 8.2 -- System components with strong authentication credentials',
        ],
        pattern: /\b(?:password|api[_\-]?key|secret[_\-]?key|access[_\-]?token|private[_\-]?key)\s*[=:]\s*["']?[A-Za-z0-9_\-\/+]{16,}["']?/i,
    },
};
/**
 * Derive the PCI Req-10 event type from transaction type and governance action.
 *
 * When action is BLOCK the event is DENIED regardless of transaction type
 * (Req 10.2.1.7 -- "all invalid logical access attempts").
 */
function derivePciEventType(transactionType, action) {
    if (action === 'BLOCK')
        return 'DENIED';
    switch (transactionType) {
        case 'authorization': return 'AUTH';
        case 'capture': return 'CAPTURE';
        case 'refund': return 'REFUND';
        case 'void': return 'VOID';
        case 'query': return 'QUERY';
    }
}
exports.PCIDSS_PACK = {
    categoryClassifiers: exports.PCIDSS_CATEGORY_CLASSIFIERS,
    /**
     * P3.5: PAN, CVV, and TRACK_DATA are inherently subject-keyed --
     * processing them necessarily involves a specific cardholder.
     * The five-dimensional identity framework will require dataSubjectId
     * on matches once ENFORCE_FIVE_DIM_IDENTITY=true is enabled.
     *
     * CARD_EXPIRY and CARDHOLDER_NAME are NOT subject-keyed at this time:
     *   - CARD_EXPIRY alone does not identify an individual.
     *   - CARDHOLDER_NAME action is LOG only.
     */
    subjectKeyedCategories: ['PAN', 'CVV', 'TRACK_DATA'],
    id: 'pci-dss',
    name: 'PCI DSS v4.0.1',
    version: '1.0.0',
    contentHash: 'd2cec4ec0c098e879fe80c8ed5598d0b18506908de21235307d6ecd628ead4d0',
    description: 'PCI DSS v4.0.1 (mandatory since 31 March 2025; v4.0.1 corrections June 2024) compliance for AI systems handling cardholder data. Covers all 12 core requirements across the cardholder data environment (CDE).',
    authority: 'PCI Security Standards Council (PCI SSC)',
    industries: ['payments', 'fintech', 'ecommerce', 'banking', 'retail', 'hospitality', 'service-provider'],
    requiredModules: [
        {
            name: 'data-classifier',
            required: true,
            reason: 'PAN / CVV / SAD detection with Luhn validation',
            reference: 'Req 3.4 -- Render PAN unreadable; Req 3.2 -- Sensitive authentication data',
        },
        {
            name: 'encryption-layer',
            required: true,
            reason: 'AES-256 encryption of cardholder data at rest + strong cryptography in transit',
            reference: 'Req 3.5 -- Protect stored account data; Req 4.1 -- Transit security',
        },
        {
            name: 'audit-integrity',
            required: true,
            reason: 'Tamper-evident audit trail with 12-month retention',
            reference: 'Req 10.2, 10.7 -- Audit log implementation and retention',
        },
        {
            name: 'governance-runtime',
            required: true,
            reason: 'Access control; deny-by-default; least privilege; MFA for CDE access',
            reference: 'Req 7.1-7.3 -- Restrict access; Req 8.4 -- MFA for CDE',
        },
        {
            name: 'agent-auth',
            required: true,
            reason: 'Unique agent identification; MFA enforcement',
            reference: 'Req 8.1-8.6 -- Identification + Authentication',
        },
        {
            name: 'event-bus',
            required: true,
            reason: 'Security monitoring; daily log review; incident detection',
            reference: 'Req 10.4, 10.6 -- Log review; Req 12.10 -- Incident detection',
        },
        {
            name: 'circuit-breaker',
            required: true,
            reason: 'Incident response isolation; contain suspected compromise',
            reference: 'Req 12.10 -- Incident response plan',
        },
        {
            name: 'supply-chain',
            required: true,
            reason: 'Service provider / TPSP management with AOC verification',
            reference: 'Req 12.8, 12.9 -- Service provider management + AOC',
        },
        {
            name: 'anomaly-detector',
            required: true,
            reason: 'Security event detection; file integrity monitoring',
            reference: 'Req 10.6.2 -- Security event review; Req 11.5 -- File integrity monitoring',
        },
        {
            name: 'attestation-manager',
            required: true,
            reason: 'Targeted risk analysis (v4.0.1 customised approach) + annual ASV scan + annual pentest attestations',
            reference: 'Req 12.3, 11.3, 11.4 -- Risk analysis + pentest + vuln scan',
        },
        {
            name: 'approval-queue',
            required: true,
            reason: 'Human-in-the-loop approval for agent actions that touch the CDE (cardholder data environment), privileged operations, and out-of-band account changes. Without HITL, an automated agent with CDE access violates least-privilege and the "authorized personnel" requirement.',
            reference: 'Req 7.2 -- Access assigned by job function / need-to-know; Req 8.5 -- Shared/generic accounts authorized per action; Req 12.5 -- Assignment of information security responsibilities',
        },
    ],
    moduleConfig: {
        'data-classifier': {
            enabledCategories: ['PAN', 'CVV', 'SAD', 'PII', 'CREDENTIALS'],
            defaultAction: 'BLOCK',
            panLuhnValidationRequired: true,
        },
        'encryption-layer': {
            algorithm: 'aes-256-gcm',
            strongCryptographyInTransitRequired: true,
        },
        'audit-integrity': {
            minimumRetentionDays: 365, // Req 10.7
            logReviewDaily: true, // Req 10.4
        },
        'governance-runtime': {
            denyByDefaultRequired: true,
            leastPrivilegeRequired: true,
        },
        // AIAG-034: MFA mandatory for all CDE access per PCI DSS v4.0.1 Req 8.4.2
        // (expanded scope: was "administrative access only", now "all access into CDE").
        'agent-auth': {
            mfaRequired: true,
            mfaForCdeAccessRequired: true,
            uniqueIdentificationRequired: true,
            mfaRequiredReason: 'PCI DSS v4.0.1 Req 8.4.2 -- MFA required for ALL access into CDE (expanded scope from v3.2.1)',
            allowedFactors: ['totp', 'webauthn', 'hardware-key'],
            smsFactorAllowed: false, // NIST 800-63B deprecates SMS-only
        },
        'attestation-manager': {
            targetedRiskAnalysisRequired: true,
            annualAsvScanRequired: true,
            annualPenetrationTestRequired: true,
            serviceProviderAocRequired: true,
        },
        'supply-chain': {
            tpspManagementRequired: true,
            aocVerificationRequired: true,
        },
    },
    providerPolicy: {
        blockedProviders: ['deepseek', 'baidu', 'alibaba'],
        requiredCapabilities: ['SOC2-TYPE2'],
        blockReasons: {
            deepseek: 'PRC data sovereignty conflicts with PCI DSS Req 3, 7. Cannot guarantee cardholder data does not transit PRC jurisdiction.',
            baidu: 'PRC jurisdiction. Cannot guarantee data sovereignty for cardholder data.',
            alibaba: 'PRC jurisdiction. Cannot guarantee data sovereignty for cardholder data.',
        },
    },
    dataPolicy: {
        // P1C-04: expanded with PAN/CVV/TRACK_DATA/CARD_EXPIRY/CARDHOLDER_NAME classifiers.
        scanCategories: ['PAN', 'CVV', 'TRACK_DATA', 'CARD_EXPIRY', 'CARDHOLDER_NAME', 'SAD', 'CREDENTIALS'],
        categoryActions: {
            // Input-side: BLOCK -> DENY verdict before tool executes.
            // Output-side stripping is handled by the pii_shield block below.
            PAN: 'BLOCK', // Req 3.4 -- render unreadable; never permitted in transit
            CVV: 'BLOCK', // Req 3.2.1 -- SAD; must not be retained after auth
            TRACK_DATA: 'BLOCK', // Req 3.2.1 -- full track data; absolute prohibition
            CARD_EXPIRY: 'WARN', // Req 3.3 -- expiry alone is lower-risk; flag for review
            CARDHOLDER_NAME: 'LOG', // Req 3.3 -- name is part of account data, record it
            SAD: 'BLOCK', // Req 3.2.1 -- any other SAD (PIN blocks, cryptograms)
            CREDENTIALS: 'BLOCK', // Req 8.2 -- strong authentication credentials
        },
        encryptionRequired: true,
        encryptionStandard: 'AES-256-GCM',
        minimumClassification: 'RESTRICTED',
        /**
         * PR-2: PII Shield -- PCI DSS v4.0.1.
         *
         * STRICT mode: PAN, CARD_EXPIRY, and CARDHOLDER_NAME are stripped and
         * pseudonymised. CVV / SAD are hard-blocked (no retention even as pseudonym
         * per PCI DSS Req 3.2.1 prohibition on post-auth SAD storage).
         *
         * References:
         *   PCI DSS v4.0.1 Req 3.3 -- Account data protection
         *   PCI DSS v4.0.1 Req 3.4 -- PAN unreadable in storage
         *   PCI DSS v4.0.1 Req 4.2 -- PAN unreadable in transit
         */
        pii_shield: {
            pii_shield_mode: 'STRICT',
            strip_classes: ['pci-cardholder'],
            uuid_scope: 'per_session',
            date_handling: 'relative_offset',
            age_aggregation_threshold: 89,
            ner_pre_scan: true,
            pre_send_phi_scan: true,
            auto_remediate_on_register: true,
            provider_memory_disabled_required: true,
        },
    },
    retentionPolicy: {
        auditLogRetentionDays: 365, // Req 10.7: at least 12 months
        sessionRetentionDays: 90,
        incidentRetentionDays: 365,
        reference: 'PCI DSS v4.0.1 Req 10.7 -- Retain audit trail for at least 12 months (3 months immediately available)',
        // P4-RET-02: PCI DSS Req 3.2.1 mandates DELETION of sensitive authentication
        // data (SAD) after authorization. forceDelete=true enforces PolicyMatrix to
        // select 'delete' for PCI-governed records, preventing cardholder data from
        // persisting in any archive beyond the retention window.
        forceDelete: true,
        requiresLegalHoldSupport: true,
        sovereignty: ['us', 'eu', 'uk'],
    },
    incidentPolicy: {
        notificationDeadlineHours: 1,
        reference: 'PCI DSS v4.0.1 Req 12.10 -- Respond immediately to suspected compromise. Notify acquiring bank and payment brand per contractual agreement (typically within hours).',
        requiredRecipients: ['security-team', 'acquiring-bank', 'payment-brand', 'forensic-investigator'],
        formalNotificationRequired: true,
    },
    validators: [
        {
            id: 'pci-pan-detection',
            description: 'PAN detection with Luhn validation + BIN range check',
            reference: 'Req 3.4, 3.5',
            check: 'pan_detection_active',
            failSeverity: 'CRITICAL',
        },
        {
            id: 'pci-encryption',
            description: 'Cardholder data encrypted at rest (AES-256-GCM) and in transit (strong cryptography)',
            reference: 'Req 3.5, 4.1',
            check: 'encryption_active',
            failSeverity: 'CRITICAL',
        },
        {
            id: 'pci-audit-trail',
            description: 'Audit trail with 12-month retention (3 months immediately available)',
            reference: 'Req 10.2, 10.7',
            check: 'audit_trail_12mo',
            failSeverity: 'CRITICAL',
        },
        {
            id: 'pci-access-control',
            description: 'Access restricted by business need; deny-by-default; least privilege',
            reference: 'Req 7.1-7.3',
            check: 'rbac_active',
            failSeverity: 'CRITICAL',
        },
        {
            id: 'pci-unique-id',
            description: 'Unique agent identification',
            reference: 'Req 8.1-8.3',
            check: 'agent_auth_active',
            failSeverity: 'HIGH',
        },
        {
            id: 'pci-mfa-cde',
            description: 'MFA required for all CDE access (v4.0.1 expanded scope)',
            reference: 'Req 8.4, 8.5',
            check: 'pci_mfa_cde_active',
            failSeverity: 'CRITICAL',
        },
        {
            id: 'pci-monitoring',
            description: 'Security event monitoring with daily log review',
            reference: 'Req 10.4, 10.6',
            check: 'monitoring_active',
            failSeverity: 'HIGH',
        },
        {
            id: 'pci-tpsp-management',
            description: 'Third-party service providers managed with AOC verification',
            reference: 'Req 12.8, 12.9',
            check: 'pci_tpsp_active',
            failSeverity: 'HIGH',
        },
        {
            id: 'pci-asv-scan',
            description: 'Quarterly ASV scan completed and current',
            reference: 'Req 11.3',
            check: 'pci_asv_scan_active',
            failSeverity: 'HIGH',
        },
        {
            id: 'pci-pentest',
            description: 'Annual penetration test completed (internal + external)',
            reference: 'Req 11.4',
            check: 'pci_pentest_active',
            failSeverity: 'HIGH',
        },
        {
            id: 'pci-incident-response',
            description: 'Incident response plan with immediate notification to acquiring bank + payment brand',
            reference: 'Req 12.10',
            check: 'incident_reporting',
            failSeverity: 'CRITICAL',
        },
        {
            id: 'pci-targeted-risk',
            description: 'Targeted risk analysis documented (v4.0.1 customised approach)',
            reference: 'Req 12.3',
            check: 'pci_targeted_risk_active',
            failSeverity: 'MEDIUM',
        },
    ],
    /**
     * P3-T1: RAG retrieval audit logging required for this pack.
     * Strict-mode packs require every retrieval to be paired with the
     * subsequent decision so auditors can replay what was retrieved before
     * the decision was made.
     */
    requiresRetrievalAuditLogging: true,
    /**
     * P3-T1: Level 4 autonomy requires explicit operator attestation when this pack
     * is active. Cap is Level 3 -- HITL oversight must be preserved for regulated data.
     */
    maxAutonomyLevelWithoutAttestation: 3,
    /**
     * P3-T1: RAG citations required for this pack. Every claim grounded in
     * retrieval must cite the source for auditor replay.
     */
    requiresCitations: true,
    /** P3-T1: RAG retrieval limited to allowlisted sources. */
    requiresRagSourceAllowlist: true,
    /** P3-T1: hook profile recommendation for this pack. */
    recommendedHookProfile: 'strict',
};
//# sourceMappingURL=pcidss.js.map