"use strict";
/**
 * HIPAA Compliance Pack
 *
 * Health Insurance Portability and Accountability Act (1996) with:
 *   - Security Rule (45 CFR 164.302-318)
 *   - Privacy Rule (45 CFR 164.500-534)
 *   - Breach Notification Rule (45 CFR 164.400-414)
 *   - 2013 Omnibus Rule (BA direct liability; see HITECH pack)
 *   - HR 7898 Safe Harbor (Jan 2021; see HITECH pack for attestation)
 *
 * Current state (2026):
 *   - **2025 Security Rule NPRM** (6 Jan 2025): HHS issued a Notice of
 *     Proposed Rulemaking with significant proposed updates:
 *       - Mandatory MFA for all workforce access to ePHI
 *       - Mandatory encryption of ePHI at rest and in transit
 *         (currently addressable)
 *       - Removal of the "addressable" vs "required" distinction --
 *         all implementation specifications become required
 *       - Asset inventory and network map required annually
 *       - Vulnerability scanning every 6 months
 *       - Penetration testing annually
 *       - 24-hour notification when access terminates
 *       - Explicit Security Risk Analysis methodology
 *     Not yet finalised. When final, required modules and validators
 *     will expand. See docs/COMPLIANCE_PACK_REFERENCE.md#hipaa for
 *     full NPRM scope.
 *   - **Always activates alongside HITECH** when BA / BA subcontractor
 *     scope applies. HIPAA = covered entity baseline; HITECH layers
 *     BA chain + breach clock + penalty tier + HR 7898 Safe Harbor.
 *
 * @connexum/ai-governance
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.HIPAA_PACK = exports.HIPAA_REMEDIATIONS = exports.HIPAA_CATEGORY_CLASSIFIERS = void 0;
/**
 * PHI category classifiers for the pack-driven classifier (W1).
 * These patterns implement the 18 HIPAA Safe Harbor identifiers
 * (45 CFR 164.514(b)(2)). Previously this logic was hardcoded in
 * src/security/data-classifier.ts. It now lives here so the runtime
 * consults the pack, not a hardcoded string.
 */
exports.HIPAA_CATEGORY_CLASSIFIERS = {
    PHI: {
        references: ['45 CFR 164.514(b)(2) -- 18 Safe Harbor identifiers'],
        classifier: (input) => {
            // SSN
            if (/\b\d{3}-\d{2}-\d{4}\b/.test(input))
                return true;
            // MRN
            if (/\bMRN[:\s#]*\d{6,12}\b/i.test(input))
                return true;
            // Date of Birth
            if (/\b(?:DOB|Date\s+of\s+Birth|Birth\s*date)[:\s]*\d{1,2}[\/\-]\d{1,2}[\/\-]\d{2,4}\b/i.test(input))
                return true;
            // Phone numbers
            if (/\b(?:\+?1[-.\s]?)?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}\b/.test(input)) {
                const digits = input.replace(/\D/g, '');
                if (digits.length >= 10)
                    return true;
            }
            // Email
            if (/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/.test(input))
                return true;
            // Health plan beneficiary number
            if (/\b(?:member|subscriber|beneficiary|policy)\s*(?:id|#|number)[:\s]*[A-Z0-9]{6,20}\b/i.test(input))
                return true;
            // Vehicle / VIN
            if (/\b(?:VIN|vehicle\s+id)[:\s]*[A-HJ-NPR-Z0-9]{17}\b/i.test(input))
                return true;
            // Device identifiers
            if (/\b(?:device\s*(?:id|serial)|serial\s*(?:number|#))[:\s]*[A-Z0-9\-]{8,30}\b/i.test(input))
                return true;
            // Biometric identifiers
            if (/\b(?:fingerprint|retinal|biometric|voiceprint|faceprint)\s*(?:id|hash|template|data)[:\s]*\S+/i.test(input))
                return true;
            // ZIP code (geographic subdivision)
            if (/\b(?:zip\s*(?:code)?|postal)[:\s]*\d{5}(?:-\d{4})?\b/i.test(input))
                return true;
            // Driver license / state ID
            if (/\b(?:DL|Driver['']?s?\s*License|state\s*ID)[:\s#]*[A-Z0-9]{6,15}\b/i.test(input))
                return true;
            return false;
        },
    },
    PII: {
        references: ['45 CFR 164.514(b)(2) -- PHI context PII indicators'],
        classifier: (input) => {
            // UK NINO
            if (/\b[A-CEGHJ-PR-TW-Z]{2}\s?\d{2}\s?\d{2}\s?\d{2}\s?[A-D]\b/i.test(input))
                return true;
            // Passport
            if (/\b(?:passport)\s*(?:#|number|no\.?)?[:\s]*[A-Z0-9]{6,12}\b/i.test(input))
                return true;
            return false;
        },
    },
    CREDENTIALS: {
        references: ['HIPAA Security Rule -- access credential protection'],
        pattern: /\b(?:password|api[_-]?key|secret[_-]?key|access[_-]?token|private[_-]?key)\s*[=:]\s*["']?[A-Za-z0-9_\-\/+]{16,}["']?/i,
    },
};
/**
 * PR-5a-3: HIPAA PII Shield remediations — 4 auto-fix declarations.
 * Applied by `scanner --fix --apply` when HIPAA pack findings are present.
 * See docs/remediation/ for handler implementation notes.
 */
exports.HIPAA_REMEDIATIONS = [
    // ---------------------------------------------------------------------------
    // 1. Codemod: wrap bare PHI-bearing tool calls with GovernedToolExecutor
    // ---------------------------------------------------------------------------
    {
        fixes: 'UNGOVERNED_PHI_TOOL_CALL',
        appliesTo: {
            fileMatchers: ['**/*.ts', '**/*.tsx', '**/*.js', '**/*.py'],
            framework: 'any',
        },
        kind: 'codemod',
        payload: {
            kind: 'codemod',
            fileGlob: '**/*.ts',
            language: 'typescript',
            framework: 'auto',
            // Transform: insert GovernedToolExecutor import + wrap bare Read/Bash/mcp__* calls.
            // Real ts-morph integration is the production path; this regex-based fallback
            // exercises the sandbox execution path and is sufficient for test verification.
            // Full ts-morph AST integration is scoped to PR-5a-3-followup.
            transformSource: `
module.exports.transform = function(sourceCode, helpers) {
  var importStmt = "import { GovernedToolExecutor } from '@connexum/ai-governance/pii-shield/governed-tool-executor.js';";
  var result = sourceCode;

  // Insert import if not already present
  if (result.indexOf(importStmt) === -1) {
    result = importStmt + '\\n' + result;
  }

  // Wrap bare Read({ ... }) calls
  var pattern = /\\bRead\\(\\{([^}]*)\\}\\)/g;
  result = result.replace(pattern, function(match, args) {
    return "GovernedToolExecutor.current().invoke('Read', {" + args + "})";
  });

  // Wrap bare Bash({ ... }) calls
  var bashPattern = /\\bBash\\(\\{([^}]*)\\}\\)/g;
  result = result.replace(bashPattern, function(match, args) {
    return "GovernedToolExecutor.current().invoke('Bash', {" + args + "})";
  });

  // Wrap mcp__*({ ... }) calls (simplified regex)
  var mcpPattern = /\\b(mcp__[a-zA-Z0-9_]+)\\(\\{([^}]*)\\}\\)/g;
  result = result.replace(mcpPattern, function(match, toolName, args) {
    return "GovernedToolExecutor.current().invoke('" + toolName + "', {" + args + "})";
  });

  return result;
};
`,
            signature: 'UNSIGNED',
        },
        rationale: 'HIPAA §164.514: PHI-bearing tool calls must route through GovernedToolExecutor for input-side BLOCK + output-side STRIP_AND_TAG enforcement.',
        packRuleId: 'hipaa-phi-tool-wrapping',
    },
    // ---------------------------------------------------------------------------
    // 2. Config-patch: wire PostToolUse + PreToolUse PII Shield hooks
    // ---------------------------------------------------------------------------
    {
        fixes: 'HOOK_NOT_WIRED',
        appliesTo: {
            fileMatchers: ['.claude/settings.json'],
        },
        kind: 'config-patch',
        payload: {
            kind: 'config-patch',
            targetFile: '.claude/settings.json',
            patch: {
                hooks: {
                    PostToolUse: {
                        'Read|Bash|mcp__database__query|mcp__claude_ai_Google_Drive__read_file_content|mcp__claude_ai_Gmail__get_thread': {
                            command: 'npx @connexum/ai-governance pii-shield-tokenize',
                            timeout_ms: 5000,
                        },
                    },
                    PreToolUse: {
                        'Write|Edit|Bash|mcp__database__execute|mcp__claude_ai_Gmail__create_draft': {
                            command: 'npx @connexum/ai-governance pii-shield-detokenize',
                            timeout_ms: 5000,
                        },
                    },
                },
            },
        },
        rationale: 'HIPAA §164.312(b): audit controls must capture every PHI-bearing tool call. The PostToolUse hook fires INPUT_STRIPPED_AND_TAGGED; PreToolUse fires OUTPUT_REJOINED.',
        packRuleId: 'hipaa-hook-wiring',
    },
    // ---------------------------------------------------------------------------
    // 3. Doc-insert: add PHI Handling Posture section to CLAUDE.md / IDENTITY.md
    // ---------------------------------------------------------------------------
    {
        fixes: 'CLAUDE_MD_MISSING_PHI_POSTURE',
        appliesTo: {
            fileMatchers: ['CLAUDE.md', 'IDENTITY.md'],
        },
        kind: 'doc-insert',
        payload: {
            kind: 'doc-insert',
            targetFile: 'IDENTITY.md',
            sectionHeader: 'PHI Handling Posture',
            sectionContent: `This agent is bound to the HIPAA compliance pack. PHI-bearing tool results are tokenized at PostToolUse before reaching the LLM. Write-side tools have tokens reversed at PreToolUse before forwarding. Audit chain emits INPUT_STRIPPED_AND_TAGGED, OUTPUT_REJOINED, and BLOCK_ON_MISS events for every PHI-touching operation. See: https://my-cc.io/docs/pii-shield\n`,
        },
        rationale: 'HIPAA Safe Harbor §164.514(b)(2) compliance posture must be documented in customer-facing agent docs for auditor verification.',
        packRuleId: 'hipaa-claude-md-phi-posture',
    },
    // ---------------------------------------------------------------------------
    // 4. Wrapper-import: declare GovernedToolExecutor + phiHandling capability
    // ---------------------------------------------------------------------------
    {
        fixes: 'DECLARATION_MISSING',
        appliesTo: {
            fileMatchers: ['**/*.ts', '**/*.tsx', '**/*.py'],
            framework: 'any',
        },
        kind: 'wrapper-import',
        payload: {
            kind: 'wrapper-import',
            targetFile: 'agent.ts',
            language: 'typescript',
            importStatement: "import { GovernedToolExecutor } from '@connexum/ai-governance/pii-shield/governed-tool-executor.js';",
            bundlePatch: [
                {
                    fieldName: 'phiHandling',
                    fieldValue: "'tokenized'",
                    nearIdentifier: 'CapabilityBundle',
                },
            ],
        },
        rationale: "HIPAA §164.312(a)(1): CapabilityBundle.phiHandling must be declared as \"tokenized\" for the boot-time UNGOVERNED_PHI_TOOL_DETECTED guard to succeed.",
        packRuleId: 'hipaa-capability-bundle-declaration',
    },
];
exports.HIPAA_PACK = {
    categoryClassifiers: exports.HIPAA_CATEGORY_CLASSIFIERS,
    /**
     * P3.5: PHI is inherently subject-keyed -- every PHI disclosure must carry
     * a data subject ID to satisfy HIPAA §164.528 accounting-of-disclosures.
     */
    subjectKeyedCategories: ['PHI'],
    id: 'hipaa',
    name: 'HIPAA Security & Privacy',
    // PR-5a-3: bumped from 1.0.0 — 4 PII Shield remediations declared
    version: '1.1.0',
    contentHash: '814e2f05b899edc4945c4a0d789fd53560b681a4b259a069648c31fefd81be3b',
    description: 'HIPAA Security Rule (45 CFR 164.302-318) + Privacy Rule (45 CFR 164.500-534) + Breach Notification Rule (45 CFR 164.400-414) compliance for AI systems handling Protected Health Information (PHI). Supports 2013 Omnibus Rule BA scope and 2025 NPRM proposed direction.',
    authority: 'HHS Office for Civil Rights (OCR)',
    industries: ['healthcare', 'health-it', 'telehealth', 'pharma', 'insurance', 'clinical-research', 'ehr-vendor'],
    requiredModules: [
        {
            name: 'governance-runtime',
            required: true,
            reason: 'Access control; deny-by-default; minimum-necessary enforcement',
            reference: '45 CFR 164.312(a)(1) -- Access Control; 164.502(b) -- Minimum Necessary',
        },
        {
            name: 'audit-integrity',
            required: true,
            reason: 'Tamper-evident audit trail per 164.312(b)',
            reference: '45 CFR 164.312(b) -- Audit Controls',
        },
        {
            name: 'encryption-layer',
            required: true,
            reason: 'AES-256-GCM encryption for ePHI at rest and in transit',
            reference: '45 CFR 164.312(a)(2)(iv), 164.312(e)(2)(ii) -- Encryption and Decryption',
        },
        {
            name: 'data-classifier',
            required: true,
            reason: 'PHI detection across 18 HIPAA identifiers',
            reference: '45 CFR 164.312(e)(1) -- Transmission Security; 164.514(b) -- 18 identifiers',
        },
        {
            name: 'agent-auth',
            required: true,
            reason: 'Unique agent identification; person / entity authentication',
            reference: '45 CFR 164.312(a)(2)(i), 164.312(d) -- Authentication',
        },
        {
            name: 'session-persistence',
            required: true,
            reason: 'Automatic logoff after inactivity (15 min production default)',
            reference: '45 CFR 164.312(a)(2)(iii) -- Automatic Logoff',
        },
        {
            name: 'circuit-breaker',
            required: true,
            reason: 'Emergency access + contingency continuity',
            reference: '45 CFR 164.312(a)(2)(ii), 164.308(a)(7) -- Contingency Plan',
        },
        {
            name: 'event-bus',
            required: true,
            reason: 'Security incident monitoring and breach-clock triggering',
            reference: '45 CFR 164.308(a)(6) -- Security Incident Procedures',
        },
        {
            name: 'anomaly-detector',
            required: true,
            reason: 'Information system activity review; intrusion detection',
            reference: '45 CFR 164.308(a)(1)(ii)(D) -- Information System Activity Review',
        },
        {
            name: 'supply-chain',
            required: true,
            reason: 'Business associate oversight; BAA management',
            reference: '45 CFR 164.308(b) -- Business Associate Contracts',
        },
        {
            name: 'memory-integrity',
            required: true,
            reason: 'Integrity of ePHI (hash verification on read)',
            reference: '45 CFR 164.312(c)(1) -- Integrity',
        },
        {
            name: 'approval-queue',
            required: true,
            reason: 'Information access management; role-based authorisation',
            reference: '45 CFR 164.308(a)(4) -- Information Access Management',
        },
        {
            name: 'agent-registration-integrity',
            required: true,
            reason: 'Named actors in audit logs must be authorised and callable at action time',
            reference: '45 CFR 164.308(a)(3) Workforce Authorization and Supervision',
        },
    ],
    moduleConfig: {
        'encryption-layer': {
            algorithm: 'aes-256-gcm',
            encryptionRequiredForEphi: true,
        },
        'data-classifier': {
            enabledCategories: ['PHI', 'PII'],
            defaultAction: 'BLOCK',
            phiIdentifierCount: 18,
        },
        'session-persistence': {
            sessionTimeoutMs: 900000, // 15 min production default (164.312(a)(2)(iii))
            autoLogoffRequired: true,
        },
        // AIAG-034: MFA mandatory for HIPAA per HHS 2025 NPRM signal and
        // Security Rule 164.312(d) "Person or entity authentication" when
        // combined with 164.308(a)(4) Information Access Management.
        'agent-auth': {
            mfaRequired: true,
            mfaRequiredReason: '45 CFR 164.312(d) Person/Entity Authentication; HHS 2025 NPRM proposes mandatory MFA for workforce access to ePHI',
            allowedFactors: ['totp', 'webauthn', 'hardware-key'],
            smsFactorAllowed: false, // NIST 800-63B deprecates SMS as only factor
        },
        'audit-integrity': {
            maxEntriesPerFile: 10000,
            sixYearRetentionRequired: true,
        },
        'governance-runtime': {
            minimumNecessaryEnforced: true,
            denyByDefaultRequired: true,
            nprm2025Watch: true, // flag for 2025 NPRM proposed direction
        },
        'supply-chain': {
            baaManagementRequired: true,
        },
    },
    providerPolicy: {
        blockedProviders: ['deepseek', 'baidu', 'alibaba', 'meta', 'mistral'],
        requiredCapabilities: ['BAA'],
        blockReasons: {
            deepseek: 'No BAA. PRC National Intelligence Law conflicts with HIPAA Privacy Rule.',
            baidu: 'No BAA. PRC jurisdiction incompatible with HIPAA.',
            alibaba: 'No BAA. PRC jurisdiction incompatible with HIPAA.',
            meta: 'No BAA for self-hosted Llama. Use via BAA-covered platform (Azure OpenAI, AWS Bedrock).',
            mistral: 'No standard BAA available directly. Use via BAA-covered platform.',
        },
    },
    dataPolicy: {
        scanCategories: ['PHI', 'PII', 'CREDENTIALS'],
        categoryActions: {
            // Input-side: BLOCK fires before the tool executes (DENY verdict).
            // STRIP_AND_TAG is the output-side behaviour -- see pii_shield block below.
            PHI: 'BLOCK',
            PII: 'WARN',
            CREDENTIALS: 'BLOCK',
        },
        encryptionRequired: true,
        encryptionStandard: 'AES-256-GCM',
        minimumClassification: 'RESTRICTED',
        /**
         * PR-2: PII Shield -- HIPAA reference implementation.
         *
         * STRICT mode: all 18 Safe Harbor PHI identifiers are stripped and
         * replaced with reversible pseudonyms before any message crosses the
         * agent boundary. This is the bar that all healthcare packs must meet.
         *
         * References:
         *   45 CFR 164.514(b)(2) -- Safe Harbor de-identification method
         *   45 CFR 164.312(e)(1) -- Transmission Security
         *   2025 NPRM: proposed mandatory encryption at rest and in transit
         */
        pii_shield: {
            pii_shield_mode: 'STRICT',
            strip_classes: ['phi', 'gdpr-contact'],
            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: 2190, // 6 years per 164.530(j)
        sessionRetentionDays: 2190,
        incidentRetentionDays: 2190,
        reference: '45 CFR 164.530(j) -- 6-year retention for Privacy Rule documentation; 164.316(b)(2) for Security Rule policies',
        // P4-RET-02: HIPAA requires archival of PHI audit records within the 6-year
        // window to support HHS investigations. forceDelete=false signals PolicyMatrix
        // to prefer 'archive' over 'delete' for HIPAA-bound records.
        forceDelete: false,
        // P4-RET-02: Legal-hold consultation is mandatory for any HIPAA-governed record.
        requiresLegalHoldSupport: true,
        // P4-RET-02: HIPAA-covered data must remain in US or EU jurisdictions only.
        sovereignty: ['us', 'eu'],
    },
    incidentPolicy: {
        notificationDeadlineHours: 1440, // 60 days
        reference: '45 CFR 164.404 -- Notification to Individuals within 60 days of discovery. HHS notification per 164.408. See HITECH pack for BA chain + 500-record media escalation.',
        requiredRecipients: ['privacy-officer', 'security-officer', 'hhs-ocr', 'affected-individuals'],
        formalNotificationRequired: true,
    },
    validators: [
        {
            id: 'hipaa-phi-detection',
            description: 'PHI detection active across 18 HIPAA identifiers',
            reference: '45 CFR 164.312(e)(1); 164.514(b)',
            check: 'data_classifier_active',
            failSeverity: 'CRITICAL',
        },
        {
            id: 'hipaa-encryption',
            description: 'ePHI encrypted at rest (AES-256-GCM)',
            reference: '45 CFR 164.312(a)(2)(iv)',
            check: 'encryption_active',
            failSeverity: 'CRITICAL',
        },
        {
            id: 'hipaa-audit-trail',
            description: 'Tamper-evident audit trail with 6-year retention',
            reference: '45 CFR 164.312(b); 164.530(j)',
            check: 'audit_trail_exists',
            failSeverity: 'CRITICAL',
        },
        {
            id: 'hipaa-access-control',
            description: 'Unique user identification and deny-by-default RBAC',
            reference: '45 CFR 164.312(a)(2)(i)',
            check: 'rbac_active',
            failSeverity: 'CRITICAL',
        },
        {
            id: 'hipaa-auto-logoff',
            description: 'Automatic session timeout (15 min production default)',
            reference: '45 CFR 164.312(a)(2)(iii)',
            check: 'hipaa_auto_logoff_active',
            failSeverity: 'HIGH',
        },
        {
            id: 'hipaa-integrity',
            description: 'ePHI integrity mechanism (hash verification on read)',
            reference: '45 CFR 164.312(c)(1)',
            check: 'hipaa_integrity_active',
            failSeverity: 'HIGH',
        },
        {
            id: 'hipaa-auth',
            description: 'Agent authentication (unique identity per agent)',
            reference: '45 CFR 164.312(d)',
            check: 'agent_auth_active',
            failSeverity: 'HIGH',
        },
        {
            id: 'hipaa-baa-check',
            description: 'All LLM providers have signed BAA',
            reference: '45 CFR 164.308(b)',
            check: 'subservice_registry_active',
            failSeverity: 'CRITICAL',
        },
        {
            id: 'hipaa-incident-plan',
            description: 'Incident response plan with 60-day individual notification',
            reference: '45 CFR 164.308(a)(6), 164.404',
            check: 'incident_reporting',
            failSeverity: 'HIGH',
        },
        {
            id: 'hipaa-risk-assessment',
            description: 'Security Risk Analysis documented and current',
            reference: '45 CFR 164.308(a)(1)(ii)(A)',
            check: 'risk_assessment_active',
            failSeverity: 'MEDIUM',
        },
        {
            id: 'hipaa-minimum-necessary',
            description: 'Minimum-necessary standard enforced at access decisions',
            reference: '45 CFR 164.502(b)',
            check: 'hipaa_minimum_necessary_active',
            failSeverity: 'HIGH',
        },
    ],
    /**
     * P3-T1: Active provider health probe interval.
     * HIPAA 164.308(a)(1)(ii)(D) requires ongoing evaluation of technical
     * controls; provider compliance posture must be verified frequently.
     * 5 minutes is the minimum acceptable interval for PHI-handling agents.
     */
    providerHealthCheckIntervalMs: 300_000, // 5 minutes
    /**
     * 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',
    /** P3-T2: action isolation required for autonomous actions on PHI. */
    requiresActionIsolation: 'sourced-only',
    /**
     * PR-5a-3: PII Shield remediations — 4 auto-fix declarations.
     * Applied by `scanner --fix --apply` when HIPAA pack findings are present.
     * Changelog: PR-5a-3 adds 4 PII Shield remediations declared.
     */
    remediations: exports.HIPAA_REMEDIATIONS,
};
//# sourceMappingURL=hipaa.js.map