UNPKG

@ufdevsllc/auth-me

Version:

Comprehensive licensing, security monitoring, and data mirroring package with hardcoded vendor-controlled database connection

413 lines (370 loc) 14 kB
/** * ConfigManager - Handles production vs development mode configuration * Provides environment-specific settings and validation */ class ConfigManager { /** * @private * @type {string} */ static _mode = null; /** * @private * @type {Object} */ static _config = null; /** * Initialize configuration manager * @param {string} mode - Environment mode (production, development, test) */ static initialize(mode = null) { // Auto-detect mode if not provided if (!mode) { mode = ConfigManager._detectMode(); } ConfigManager._mode = mode; ConfigManager._config = ConfigManager._loadModeConfig(mode); } /** * Get current mode * @returns {string} Current environment mode */ static getMode() { if (!ConfigManager._mode) { ConfigManager.initialize(); } return ConfigManager._mode; } /** * Check if running in production mode * @returns {boolean} True if in production mode */ static isProduction() { return ConfigManager.getMode() === 'production'; } /** * Check if running in development mode * @returns {boolean} True if in development mode */ static isDevelopment() { return ConfigManager.getMode() === 'development'; } /** * Check if running in test mode * @returns {boolean} True if in test mode */ static isTest() { return ConfigManager.getMode() === 'test'; } /** * Get configuration for current mode * @returns {Object} Mode-specific configuration */ static getConfig() { if (!ConfigManager._config) { ConfigManager.initialize(); } return { ...ConfigManager._config }; } /** * Get specific configuration value * @param {string} key - Configuration key * @param {any} defaultValue - Default value if key not found * @returns {any} Configuration value */ static get(key, defaultValue = null) { const config = ConfigManager.getConfig(); return config[key] !== undefined ? config[key] : defaultValue; } /** * Validate configuration for current mode * @param {Object} userConfig - User-provided configuration * @returns {Object} Validated and merged configuration * @throws {Error} If configuration is invalid */ static validateConfig(userConfig) { const mode = ConfigManager.getMode(); const modeConfig = ConfigManager.getConfig(); // Merge user config with mode defaults const mergedConfig = { ...modeConfig.defaults, ...userConfig, options: { ...modeConfig.defaults.options, ...userConfig.options } }; // Apply mode-specific validations ConfigManager._validateModeSpecificConfig(mergedConfig, mode); return mergedConfig; } /** * Auto-detect environment mode * @private * @returns {string} Detected mode */ static _detectMode() { // Check NODE_ENV first if (process.env.NODE_ENV) { const env = process.env.NODE_ENV.toLowerCase(); if (['production', 'development', 'test'].includes(env)) { return env; } } // Check for test environment indicators if (process.env.JEST_WORKER_ID || process.argv.some(arg => arg.includes('jest'))) { return 'test'; } // Check for development indicators if (process.env.DEBUG || process.argv.includes('--dev')) { return 'development'; } // Default to production for safety return 'production'; } /** * Load configuration for specific mode * @private * @param {string} mode - Environment mode * @returns {Object} Mode-specific configuration */ static _loadModeConfig(mode) { const baseConfig = { security: { enableTamperDetection: true, enableEnvironmentBinding: true, enableUsageTracking: true, crashOnViolation: true }, logging: { verboseLogging: false, enableSecurityEventLogging: true, logLevel: 'info' }, performance: { enableCaching: true, cacheTimeout: 300000, // 5 minutes maxRetries: 3, retryDelay: 1000 }, validation: { strictSchemaValidation: true, validateEnvironmentBinding: true, requireLicenseKey: true } }; switch (mode) { case 'production': return { ...baseConfig, defaults: { options: { enableEnvironmentBinding: true, enableTamperDetection: true, enableUsageTracking: true, crashOnViolation: true, verboseLogging: false, enableDebugging: false, enableObfuscation: true, enableMinification: true, strictValidation: true } }, security: { ...baseConfig.security, enableAntiDebugging: true, enableObfuscation: true, enableIntegrityChecks: true, strictMode: true }, logging: { ...baseConfig.logging, verboseLogging: false, logLevel: 'warn', enableDebugLogs: false }, performance: { ...baseConfig.performance, enableCaching: true, aggressiveCaching: true }, validation: { ...baseConfig.validation, strictSchemaValidation: true, strictTypeChecking: true, allowMissingOptionalFields: false } }; case 'development': return { ...baseConfig, defaults: { options: { enableEnvironmentBinding: false, enableTamperDetection: false, enableUsageTracking: true, crashOnViolation: false, verboseLogging: true, enableDebugging: true, enableObfuscation: false, enableMinification: false, strictValidation: false } }, security: { ...baseConfig.security, enableTamperDetection: false, enableEnvironmentBinding: false, crashOnViolation: false, enableAntiDebugging: false, enableObfuscation: false, strictMode: false }, logging: { ...baseConfig.logging, verboseLogging: true, logLevel: 'debug', enableDebugLogs: true }, performance: { ...baseConfig.performance, enableCaching: false, maxRetries: 1 }, validation: { ...baseConfig.validation, strictSchemaValidation: false, strictTypeChecking: false, allowMissingOptionalFields: true, requireLicenseKey: false } }; case 'test': return { ...baseConfig, defaults: { options: { enableEnvironmentBinding: false, enableTamperDetection: false, enableUsageTracking: false, crashOnViolation: false, verboseLogging: false, enableDebugging: true, enableObfuscation: false, enableMinification: false, strictValidation: false } }, security: { ...baseConfig.security, enableTamperDetection: false, enableEnvironmentBinding: false, enableUsageTracking: false, crashOnViolation: false, enableAntiDebugging: false, strictMode: false }, logging: { ...baseConfig.logging, verboseLogging: false, logLevel: 'error', enableDebugLogs: false }, performance: { ...baseConfig.performance, enableCaching: false, maxRetries: 0 }, validation: { ...baseConfig.validation, strictSchemaValidation: false, requireLicenseKey: false, allowMissingOptionalFields: true } }; default: throw new Error(`Unknown environment mode: ${mode}`); } } /** * Validate mode-specific configuration * @private * @param {Object} config - Configuration to validate * @param {string} mode - Environment mode * @throws {Error} If configuration is invalid for the mode */ static _validateModeSpecificConfig(config, mode) { switch (mode) { case 'production': // Production mode validations if (!config.licenseKey && config.options?.requireLicenseKey !== false) { throw new Error('License key is required in production mode'); } if (!config.vendorEndpoint) { throw new Error('Vendor endpoint is required in production mode'); } if (config.options?.enableDebugging === true) { console.warn('[ConfigManager] Warning: Debugging is enabled in production mode'); } break; case 'development': // Development mode validations if (config.options?.crashOnViolation === true) { console.warn('[ConfigManager] Warning: crashOnViolation is enabled in development mode'); } break; case 'test': // Test mode validations if (config.options?.enableUsageTracking === true) { console.warn('[ConfigManager] Warning: Usage tracking is enabled in test mode'); } break; } // Common validations if (config.schemas && !Array.isArray(config.schemas)) { throw new Error('Schemas must be an array'); } if (config.options && typeof config.options !== 'object') { throw new Error('Options must be an object'); } } /** * Get environment-specific error messages * @param {string} errorCode - Error code * @returns {string} Environment-appropriate error message */ static getErrorMessage(errorCode) { const mode = ConfigManager.getMode(); const isProduction = mode === 'production'; const messages = { INVALID_LICENSE: isProduction ? 'License validation failed' : 'License validation failed - check your license key and vendor endpoint', TAMPER_DETECTED: isProduction ? 'Security violation detected' : 'Tamper detection triggered - package files may have been modified', ENVIRONMENT_MISMATCH: isProduction ? 'Environment validation failed' : 'Environment binding mismatch - license may not be authorized for this environment', USAGE_EXCEEDED: isProduction ? 'Usage limits exceeded' : 'Usage limits exceeded - check your license plan and current usage', CONNECTION_FAILED: isProduction ? 'Service connection failed' : 'Failed to connect to vendor endpoint - check network connectivity and endpoint URL', INITIALIZATION_FAILED: isProduction ? 'Initialization failed' : 'SecureGuard initialization failed - check configuration and dependencies' }; return messages[errorCode] || (isProduction ? 'An error occurred' : `Unknown error: ${errorCode}`); } /** * Reset configuration manager (for testing) * @private */ static _reset() { ConfigManager._mode = null; ConfigManager._config = null; } } module.exports = ConfigManager;