"use strict";
/**
 * DataPilot Security Framework
 * Main entry point for all security components
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.SecurityUtils = exports.SecureDataPilot = exports.SecurityMonitor = exports.getSecurityAuditLogger = exports.SecurityAuditLogger = exports.DEFAULT_SECURITY_POLICY = exports.SecurityProfiles = exports.SecurityPolicyBuilder = exports.getSecurityConfig = exports.SecurityConfigManager = exports.SecureFileOperations = exports.getFileAccessController = exports.FileAccessController = exports.ExternalDataValidator = exports.getInputValidator = exports.InputValidator = void 0;
exports.initializeSecurity = initializeSecurity;
exports.getSecureDataPilot = getSecureDataPilot;
exports.securityMonitor = securityMonitor;
var input_validator_1 = require("./input-validator");
Object.defineProperty(exports, "InputValidator", { enumerable: true, get: function () { return input_validator_1.InputValidator; } });
Object.defineProperty(exports, "getInputValidator", { enumerable: true, get: function () { return input_validator_1.getInputValidator; } });
Object.defineProperty(exports, "ExternalDataValidator", { enumerable: true, get: function () { return input_validator_1.ExternalDataValidator; } });
var file_access_controller_1 = require("./file-access-controller");
Object.defineProperty(exports, "FileAccessController", { enumerable: true, get: function () { return file_access_controller_1.FileAccessController; } });
Object.defineProperty(exports, "getFileAccessController", { enumerable: true, get: function () { return file_access_controller_1.getFileAccessController; } });
Object.defineProperty(exports, "SecureFileOperations", { enumerable: true, get: function () { return file_access_controller_1.SecureFileOperations; } });
var security_config_1 = require("./security-config");
Object.defineProperty(exports, "SecurityConfigManager", { enumerable: true, get: function () { return security_config_1.SecurityConfigManager; } });
Object.defineProperty(exports, "getSecurityConfig", { enumerable: true, get: function () { return security_config_1.getSecurityConfig; } });
Object.defineProperty(exports, "SecurityPolicyBuilder", { enumerable: true, get: function () { return security_config_1.SecurityPolicyBuilder; } });
Object.defineProperty(exports, "SecurityProfiles", { enumerable: true, get: function () { return security_config_1.SecurityProfiles; } });
Object.defineProperty(exports, "DEFAULT_SECURITY_POLICY", { enumerable: true, get: function () { return security_config_1.DEFAULT_SECURITY_POLICY; } });
var audit_logger_1 = require("./audit-logger");
Object.defineProperty(exports, "SecurityAuditLogger", { enumerable: true, get: function () { return audit_logger_1.SecurityAuditLogger; } });
Object.defineProperty(exports, "getSecurityAuditLogger", { enumerable: true, get: function () { return audit_logger_1.getSecurityAuditLogger; } });
Object.defineProperty(exports, "SecurityMonitor", { enumerable: true, get: function () { return audit_logger_1.SecurityMonitor; } });
const input_validator_2 = require("./input-validator");
const file_access_controller_2 = require("./file-access-controller");
const security_config_2 = require("./security-config");
const audit_logger_2 = require("./audit-logger");
const types_1 = require("../core/types");
const logger_1 = require("../utils/logger");
/**
 * Initialize the security framework
 */
async function initializeSecurity(options) {
    try {
        logger_1.logger.info('Initializing DataPilot Security Framework', options);
        // Initialize security configuration
        const securityConfig = (0, security_config_2.getSecurityConfig)();
        if (options?.environment) {
            securityConfig.applyEnvironmentOverrides(options.environment);
        }
        // Validate security configuration
        const validation = securityConfig.validateConfiguration();
        if (!validation.isValid) {
            throw new types_1.DataPilotError(`Security configuration validation failed: ${validation.errors.join(', ')}`, 'SECURITY_CONFIG_INVALID');
        }
        if (validation.warnings.length > 0) {
            logger_1.logger.warn('Security configuration warnings', {
                warnings: validation.warnings,
            });
        }
        // Initialize audit logging
        const auditLogger = (0, audit_logger_2.getSecurityAuditLogger)();
        await auditLogger.logSecurityEvent('system_security', 'Security framework initialized', {
            environment: options?.environment,
            configValidation: validation,
        }, {
            severity: 'low',
            outcome: 'success',
        });
        // Enable advanced features if requested
        if (options?.enableAdvancedThreatDetection) {
            securityConfig.updateSecurityFeatures({
                enableAdvancedThreatDetection: true,
                enableRealTimeMonitoring: true,
                enableIntrusionDetection: true,
            });
        }
        logger_1.logger.info('DataPilot Security Framework initialized successfully', {
            environment: options?.environment,
            features: Object.keys(securityConfig.getSecurityFeatures()),
        });
    }
    catch (error) {
        logger_1.logger.error('Failed to initialize security framework', {
            error: error instanceof Error ? error.message : 'Unknown error',
        });
        throw error;
    }
}
/**
 * Secure wrapper for file operations
 */
class SecureDataPilot {
    inputValidator = (0, input_validator_2.getInputValidator)();
    fileController = (0, file_access_controller_2.getFileAccessController)();
    auditLogger = (0, audit_logger_2.getSecurityAuditLogger)();
    /**
     * Securely validate and process a file path
     */
    async validateAndProcessFile(filePath, operation, context) {
        try {
            // Log the operation attempt
            await this.auditLogger.logFileAccessEvent(filePath, operation, 'success', context?.userId, { originalPath: filePath }, context);
            // Validate the file path
            const validation = this.inputValidator.validateFilePath(filePath);
            if (!validation.isValid) {
                await this.auditLogger.logFileAccessEvent(filePath, operation, 'blocked', context?.userId, {
                    reason: 'Validation failed',
                    errors: validation.errors.map((e) => typeof e === 'string' ? e : e.message),
                }, context);
                return {
                    isValid: false,
                    errors: validation.errors.map((e) => typeof e === 'string' ? e : e.message),
                };
            }
            // Create secure file handle
            const handle = await this.fileController.createSecureHandle(validation.sanitizedValue, operation === 'analyze' ? 'read' : operation, undefined, context);
            return {
                isValid: true,
                sanitizedPath: validation.sanitizedValue,
                securityHandle: handle,
                errors: [],
            };
        }
        catch (error) {
            const errorMessage = error instanceof Error ? error.message : 'Unknown error';
            await this.auditLogger.logFileAccessEvent(filePath, operation, 'failure', context?.userId, { error: errorMessage }, context);
            return {
                isValid: false,
                errors: [errorMessage],
            };
        }
    }
    /**
     * Securely validate CLI options
     */
    validateCLIOptions(options, context) {
        try {
            const validation = this.inputValidator.validateCLIInput(options, context);
            // Log validation attempt
            this.auditLogger.logSecurityEvent('input_validation', 'CLI options validation', {
                optionKeys: Object.keys(options),
                isValid: validation.isValid,
                errorCount: validation.errors.length,
            }, {
                severity: validation.isValid ? 'low' : 'medium',
                outcome: validation.isValid ? 'success' : 'failure',
                context,
            });
            return {
                isValid: validation.isValid,
                sanitizedOptions: validation.sanitizedValue,
                errors: validation.errors.map((e) => typeof e === 'string' ? e : e.message),
                warnings: validation.warnings,
            };
        }
        catch (error) {
            const errorMessage = error instanceof Error ? error.message : 'Unknown error';
            this.auditLogger.logSecurityEvent('input_validation', 'CLI options validation failed', { error: errorMessage }, {
                severity: 'high',
                outcome: 'failure',
                context,
            });
            return {
                isValid: false,
                errors: [errorMessage],
                warnings: [],
            };
        }
    }
    /**
     * Get security status and statistics
     */
    getSecurityStatus() {
        const fileStats = this.fileController.getStatistics();
        const auditStats = this.auditLogger.getStatistics();
        const recentEvents = this.auditLogger.getEvents({ limit: 10 });
        const warnings = [];
        // Check for security issues
        if (fileStats.quarantinedFiles > 0) {
            warnings.push(`${fileStats.quarantinedFiles} files are quarantined`);
        }
        if (auditStats.eventsBySeverity.critical > 0) {
            warnings.push(`${auditStats.eventsBySeverity.critical} critical security events`);
        }
        if (auditStats.averageRiskScore > 7) {
            warnings.push('High average risk score detected');
        }
        return {
            isHealthy: warnings.length === 0,
            statistics: {
                fileAccess: fileStats,
                audit: auditStats,
            },
            recentEvents,
            warnings,
        };
    }
}
exports.SecureDataPilot = SecureDataPilot;
/**
 * Global security instance
 */
let globalSecureDataPilot;
/**
 * Get the global secure DataPilot instance
 */
function getSecureDataPilot() {
    if (!globalSecureDataPilot) {
        globalSecureDataPilot = new SecureDataPilot();
    }
    return globalSecureDataPilot;
}
/**
 * Security decorator for method execution monitoring
 */
function securityMonitor(operation) {
    return function (target, propertyName, descriptor) {
        const method = descriptor.value;
        descriptor.value = async function (...args) {
            const auditLogger = (0, audit_logger_2.getSecurityAuditLogger)();
            const startTime = Date.now();
            try {
                const result = await method.apply(this, args);
                await auditLogger.logSecurityEvent('system_security', `Method execution: ${operation}`, {
                    className: target.constructor.name,
                    methodName: propertyName,
                    duration: Date.now() - startTime,
                    argsCount: args.length,
                }, {
                    severity: 'low',
                    outcome: 'success',
                });
                return result;
            }
            catch (error) {
                await auditLogger.logSecurityEvent('system_security', `Method execution failed: ${operation}`, {
                    className: target.constructor.name,
                    methodName: propertyName,
                    error: error instanceof Error ? error.message : 'Unknown error',
                    duration: Date.now() - startTime,
                }, {
                    severity: 'medium',
                    outcome: 'failure',
                });
                throw error;
            }
        };
        return descriptor;
    };
}
/**
 * Security utilities
 */
exports.SecurityUtils = {
    /**
     * Sanitize error messages for safe display
     */
    sanitizeErrorMessage(error, hideSystemPaths = true) {
        const message = typeof error === 'string' ? error : error.message;
        if (!hideSystemPaths) {
            return message;
        }
        // Remove system paths and sensitive information
        return message
            .replace(/\/[^\s]+\/[^\s]+/g, '[PATH]') // Remove Unix paths
            .replace(/[A-Z]:\\[^\s]+/g, '[PATH]') // Remove Windows paths
            .replace(/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g, '[IP]') // Remove IP addresses
            .replace(/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/g, '[EMAIL]'); // Remove emails
    },
    /**
     * Generate secure random string
     */
    generateSecureToken(length = 32) {
        const crypto = require('crypto');
        return crypto.randomBytes(length).toString('hex');
    },
    /**
     * Hash sensitive data
     */
    hashSensitiveData(data, algorithm = 'sha256') {
        const crypto = require('crypto');
        return crypto.createHash(algorithm).update(data).digest('hex');
    },
};
//# sourceMappingURL=index.js.map