@xbibzlibrary/obfuscator
Version: 
Advanced polymorphic obfuscation library for JavaScript, JSON and CSS with multi-layer encryption and browser compatibility
466 lines (390 loc) • 15.5 kB
JavaScript
/**
 * Xbibz Library Obfuscator - Main Module
 * Advanced polymorphic obfuscation for JavaScript, JSON, and CSS
 * @version 1.0.0
 * @author Xbibz Official
 */
const JSONObfuscator = require('./obfuscators/json-obfuscator');
const JavaScriptObfuscator = require('./obfuscators/javascript-obfuscator');
const CSSObfuscator = require('./obfuscators/css-obfuscator');
const BrowserDetector = require('./utils/browser-detector');
const CryptoUtils = require('./utils/crypto-utils');
const StringManipulator = require('./utils/string-manipulator');
class XbibzObfuscator {
    constructor(options = {}) {
        this.options = {
            obfuscationLevel: 8,
            enablePolymorphism: true,
            enableEncryption: true,
            enableCompression: false,
            browserCompatibility: true,
            autoPolyfills: true,
            debugMode: false,
            ...options
        };
        // Initialize components
        this.jsonObfuscator = new JSONObfuscator();
        this.jsObfuscator = new JavaScriptObfuscator();
        this.cssObfuscator = new CSSObfuscator();
        this.browserDetector = new BrowserDetector();
        this.cryptoUtils = new CryptoUtils();
        this.stringManipulator = new StringManipulator();
        // Set obfuscation levels
        this.jsonObfuscator.setObfuscationLevel(this.options.obfuscationLevel);
        this.jsObfuscator.setObfuscationLevel(this.options.obfuscationLevel);
        this.cssObfuscator.setObfuscationLevel(this.options.obfuscationLevel);
        // Apply browser compatibility
        if (this.options.browserCompatibility) {
            this.applyBrowserCompatibility();
        }
        // Initialize logging
        this.setupLogging();
        this.log('Xbibz Obfuscator initialized', 'info');
        this.log(`Obfuscation level: ${this.options.obfuscationLevel}`, 'debug');
        this.log(`Browser: ${this.browserDetector.browser} ${this.browserDetector.version}`, 'debug');
    }
    applyBrowserCompatibility() {
        if (this.options.autoPolyfills) {
            this.browserDetector.applyPolyfills();
        }
        // Apply browser-specific optimizations
        const browserInfo = this.browserDetector.getBrowserInfo();
        
        if (browserInfo.name === 'ie') {
            this.options.obfuscationLevel = Math.min(this.options.obfuscationLevel, 5);
            this.log('Internet Explorer detected, reducing obfuscation level', 'warn');
        }
        if (!browserInfo.features.crypto) {
            this.options.enableEncryption = false;
            this.log('Crypto API not available, disabling encryption', 'warn');
        }
    }
    setupLogging() {
        this.logLevels = {
            error: 0,
            warn: 1,
            info: 2,
            debug: 3
        };
        this.currentLogLevel = this.options.debugMode ? 
            this.logLevels.debug : this.logLevels.info;
    }
    log(message, level = 'info') {
        if (this.logLevels[level] <= this.currentLogLevel) {
            const timestamp = new Date().toISOString();
            const prefix = `[XbibzObfuscator:${level.toUpperCase()}]`;
            
            switch (level) {
                case 'error':
                    console.error(`${timestamp} ${prefix} ${message}`);
                    break;
                case 'warn':
                    console.warn(`${timestamp} ${prefix} ${message}`);
                    break;
                case 'info':
                    console.info(`${timestamp} ${prefix} ${message}`);
                    break;
                case 'debug':
                    console.debug(`${timestamp} ${prefix} ${message}`);
                    break;
            }
        }
    }
    // JSON Obfuscation
    obfuscateJSON(jsonData, options = {}) {
        this.log('Starting JSON obfuscation', 'info');
        
        try {
            const jsonString = typeof jsonData === 'string' ? 
                jsonData : JSON.stringify(jsonData, null, 2);
            if (!this.jsonObfuscator.validateJSON(jsonString)) {
                throw new Error('Invalid JSON data');
            }
            const result = this.jsonObfuscator.obfuscateJSONString(jsonString, {
                encryption: this.options.enableEncryption,
                structureTransformation: true,
                polymorphism: this.options.enablePolymorphism,
                layers: true,
                ...options
            });
            this.log('JSON obfuscation completed successfully', 'info');
            return result;
        } catch (error) {
            this.log(`JSON obfuscation failed: ${error.message}`, 'error');
            throw error;
        }
    }
    deobfuscateJSON(obfuscatedJSON, password) {
        this.log('Starting JSON deobfuscation', 'info');
        
        try {
            const result = this.jsonObfuscator.deobfuscateJSONString(obfuscatedJSON, password);
            this.log('JSON deobfuscation completed successfully', 'info');
            return result;
        } catch (error) {
            this.log(`JSON deobfuscation failed: ${error.message}`, 'error');
            throw error;
        }
    }
    // JavaScript Obfuscation
    obfuscateJavaScript(code, options = {}) {
        this.log('Starting JavaScript obfuscation', 'info');
        
        try {
            // Validate code syntax
            const validation = this.jsObfuscator.validateCode(code);
            if (!validation.valid) {
                throw new Error(`Invalid JavaScript: ${validation.error}`);
            }
            const result = this.jsObfuscator.obfuscateCode(code, {
                controlFlow: true,
                strings: true,
                variables: true,
                functions: true,
                deadCode: this.options.obfuscationLevel >= 6,
                antiDebug: this.options.obfuscationLevel >= 7,
                antiTamper: this.options.obfuscationLevel >= 8,
                polymorphism: this.options.enablePolymorphism,
                layers: true,
                ...options
            });
            this.log('JavaScript obfuscation completed successfully', 'info');
            
            // Generate obfuscation report
            if (this.options.debugMode) {
                const report = this.jsObfuscator.generateObfuscationReport(code);
                this.log(`Obfuscation report: ${JSON.stringify(report)}`, 'debug');
            }
            return result;
        } catch (error) {
            this.log(`JavaScript obfuscation failed: ${error.message}`, 'error');
            throw error;
        }
    }
    createJavaScriptVariant(code, variantId) {
        this.log(`Creating polymorphic variant ${variantId}`, 'debug');
        
        try {
            const variant = this.jsObfuscator.createPolymorphicVariant(code, variantId);
            this.log(`Polymorphic variant ${variantId} created successfully`, 'debug');
            return variant;
        } catch (error) {
            this.log(`Variant creation failed: ${error.message}`, 'error');
            throw error;
        }
    }
    // CSS Obfuscation
    obfuscateCSS(cssCode, options = {}) {
        this.log('Starting CSS obfuscation', 'info');
        
        try {
            const result = this.cssObfuscator.obfuscateCSS(cssCode, {
                mangleClassNames: true,
                mangleIds: true,
                mangleAnimations: true,
                encryptValues: this.options.enableEncryption,
                transformProperties: true,
                addRedundantRules: this.options.obfuscationLevel >= 5,
                splitSelectors: this.options.obfuscationLevel >= 6,
                obfuscateMediaQueries: this.options.obfuscationLevel >= 7,
                ...options
            });
            this.log('CSS obfuscation completed successfully', 'info');
            return result;
        } catch (error) {
            this.log(`CSS obfuscation failed: ${error.message}`, 'error');
            throw error;
        }
    }
    generateObfuscatedCSS(cssCode, options = {}) {
        this.log('Generating obfuscated CSS with JavaScript runtime', 'info');
        
        try {
            const result = this.cssObfuscator.generateObfuscatedCSS(cssCode, options);
            this.log('CSS with runtime obfuscation generated successfully', 'info');
            return result;
        } catch (error) {
            this.log(`CSS generation failed: ${error.message}`, 'error');
            throw error;
        }
    }
    // Multi-format obfuscation
    obfuscateMultiFormat(data, type = 'auto', options = {}) {
        this.log(`Starting multi-format obfuscation for type: ${type}`, 'info');
        
        try {
            let detectedType = type;
            
            if (type === 'auto') {
                detectedType = this.detectDataType(data);
                this.log(`Auto-detected data type: ${detectedType}`, 'debug');
            }
            switch (detectedType) {
                case 'json':
                    return this.obfuscateJSON(data, options);
                case 'javascript':
                    return this.obfuscateJavaScript(data, options);
                case 'css':
                    return this.obfuscateCSS(data, options);
                default:
                    throw new Error(`Unsupported data type: ${detectedType}`);
            }
        } catch (error) {
            this.log(`Multi-format obfuscation failed: ${error.message}`, 'error');
            throw error;
        }
    }
    detectDataType(data) {
        if (typeof data !== 'string') {
            return 'javascript';
        }
        // Try to parse as JSON
        try {
            JSON.parse(data);
            return 'json';
        } catch (e) {
            // Not JSON
        }
        // Check for CSS patterns
        if (data.includes('{') && data.includes('}') && 
            (data.includes(':') || data.includes('@'))) {
            return 'css';
        }
        // Check for JavaScript patterns
        if (data.includes('function') || data.includes('var ') || 
            data.includes('const ') || data.includes('let ')) {
            return 'javascript';
        }
        return 'unknown';
    }
    // Batch processing
    async processBatch(items, processor, options = {}) {
        this.log(`Starting batch processing of ${items.length} items`, 'info');
        
        const results = [];
        const errors = [];
        
        for (let i = 0; i < items.length; i++) {
            try {
                this.log(`Processing item ${i + 1}/${items.length}`, 'debug');
                const result = await processor(items[i], options);
                results.push(result);
            } catch (error) {
                this.log(`Item ${i + 1} failed: ${error.message}`, 'error');
                errors.push({
                    index: i,
                    error: error.message,
                    item: items[i]
                });
            }
        }
        this.log(`Batch processing completed: ${results.length} success, ${errors.length} errors`, 'info');
        
        return {
            results,
            errors,
            total: items.length,
            successful: results.length,
            failed: errors.length
        };
    }
    // Performance monitoring
    startPerformanceTracking() {
        this.browserDetector.startPerformanceMonitor();
        this.log('Performance tracking started', 'debug');
    }
    getPerformanceMetrics() {
        const metrics = this.browserDetector.getPerformanceMetrics();
        
        if (metrics) {
            this.log(`Performance metrics: ${JSON.stringify(metrics)}`, 'debug');
        }
        
        return metrics;
    }
    // Utility methods
    generateEncryptionKey(length = 32) {
        return this.cryptoUtils.generateKey(length, 'alphanumeric');
    }
    validateObfuscationResult(original, obfuscated) {
        const originalSize = original.length;
        const obfuscatedSize = obfuscated.length;
        const ratio = (obfuscatedSize / originalSize * 100).toFixed(2);
        
        return {
            originalSize,
            obfuscatedSize,
            sizeRatio: ratio + '%',
            efficiency: originalSize > 0 ? 
                ((obfuscatedSize - originalSize) / originalSize * 100).toFixed(2) + '%' : 'N/A'
        };
    }
    // Configuration management
    updateConfiguration(newOptions) {
        this.options = { ...this.options, ...newOptions };
        
        // Update component configurations
        if (newOptions.obfuscationLevel !== undefined) {
            this.jsonObfuscator.setObfuscationLevel(newOptions.obfuscationLevel);
            this.jsObfuscator.setObfuscationLevel(newOptions.obfuscationLevel);
            this.cssObfuscator.setObfuscationLevel(newOptions.obfuscationLevel);
        }
        
        this.log('Configuration updated', 'info');
        return this.getConfiguration();
    }
    getConfiguration() {
        return {
            ...this.options,
            browserInfo: this.browserDetector.getBrowserInfo(),
            obfuscationStats: {
                json: this.jsonObfuscator.getObfuscationInfo(),
                javascript: this.jsObfuscator.getObfuscationStats(),
                css: this.cssObfuscator.getObfuscationInfo()
            }
        };
    }
    // Error handling and recovery
    setupErrorHandling() {
        window.addEventListener('error', (event) => {
            this.log(`Global error: ${event.message}`, 'error');
        });
        window.addEventListener('unhandledrejection', (event) => {
            this.log(`Unhandled promise rejection: ${event.reason}`, 'error');
        });
    }
    // Public API for browser usage
    static create(options = {}) {
        return new XbibzObfuscator(options);
    }
    // Plugin system
    registerPlugin(plugin) {
        if (typeof plugin === 'function') {
            plugin(this);
            this.log('Plugin registered successfully', 'info');
        } else {
            this.log('Invalid plugin - must be a function', 'error');
        }
    }
    // Export for different environments
    static get Version() {
        return '1.0.0';
    }
    static get Authors() {
        return ['Xbibz Official'];
    }
    static get Features() {
        return {
            JSON_Obfuscation: true,
            JavaScript_Obfuscation: true,
            CSS_Obfuscation: true,
            Polymorphic_Engine: true,
            Advanced_Encryption: true,
            Browser_Compatibility: true,
            Multi_Layer_Obfuscation: true
        };
    }
}
// Export for CommonJS
if (typeof module !== 'undefined' && module.exports) {
    module.exports = XbibzObfuscator;
}
// Export for AMD
if (typeof define === 'function' && define.amd) {
    define([], () => XbibzObfuscator);
}
// Export for browser globals
if (typeof window !== 'undefined') {
    window.XbibzObfuscator = XbibzObfuscator;
}
// Auto-initialize for browser with default options
if (typeof window !== 'undefined' && typeof document !== 'undefined') {
    document.addEventListener('DOMContentLoaded', () => {
        if (!window.xbibzObfuscator) {
            window.xbibzObfuscator = new XbibzObfuscator();
            window.xbibzObfuscator.log('Xbibz Obfuscator auto-initialized', 'info');
        }
    });
}
module.exports = XbibzObfuscator;