UNPKG

@ufdevsllc/auth-me

Version:

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

1 lines 7.53 kB
const SecureGuardError=require("./SecureGuardError"),Logger=require("./Logger"),SecurityEventLogger=require("./SecurityEventLogger");class ErrorHandler{static RETRY_CONFIG={MAX_RETRIES:3,BASE_DELAY:1e3,MAX_DELAY:3e4,BACKOFF_MULTIPLIER:2};static logger=null;static securityLogger=null;static initialize(r,e){ErrorHandler.logger=r,ErrorHandler.securityLogger=e,ErrorHandler.logger&&ErrorHandler.logger.info("ErrorHandler","Error handler initialized with logging system")}static async handle(r,e={}){try{if(await ErrorHandler.logSecurityEvent(r,e),r.isNetworkError()&&!1!==e.retryable)return await ErrorHandler.handleWithRetry(r,e);switch(r.severity){case SecureGuardError.SEVERITY.CRITICAL:return ErrorHandler.handleCriticalError(r,e);case SecureGuardError.SEVERITY.HIGH:return ErrorHandler.handleHighSeverityError(r,e);case SecureGuardError.SEVERITY.MEDIUM:return ErrorHandler.handleMediumSeverityError(r,e);case SecureGuardError.SEVERITY.LOW:return ErrorHandler.handleLowSeverityError(r,e);default:return ErrorHandler.handleUnknownError(r,e)}}catch(e){ErrorHandler.fallbackErrorHandling(r,e)}}static async handleWithRetry(r,e){const{retryFunction:o,maxRetries:a=ErrorHandler.RETRY_CONFIG.MAX_RETRIES}=e;if(!o)throw r;let t=r;for(let E=1;E<=a;E++)try{const t=ErrorHandler.calculateBackoffDelay(E);E>1&&(console.warn(`SecureGuard: Retrying operation (attempt ${E}/${a}) after ${t}ms delay`),await ErrorHandler.sleep(t));const n=await o();return E>1&&await ErrorHandler.logSecurityEvent(new SecureGuardError("RETRY_SUCCESS",SecureGuardError.SEVERITY.LOW,`Operation succeeded after ${E} attempts`,!1,{originalError:r.code,attempts:E}),e),n}catch(r){t=r instanceof SecureGuardError?r:new SecureGuardError("RETRY_FAILED",SecureGuardError.SEVERITY.MEDIUM,`Retry attempt ${E} failed: ${r.message}`,!1,{attempt:E,maxRetries:a},r),await ErrorHandler.logSecurityEvent(t,e)}throw new SecureGuardError("RETRY_EXHAUSTED",SecureGuardError.SEVERITY.HIGH,`All ${a} retry attempts failed`,!1,{originalError:r.code,maxRetries:a},t)}static calculateBackoffDelay(r){const e=ErrorHandler.RETRY_CONFIG.BASE_DELAY*Math.pow(ErrorHandler.RETRY_CONFIG.BACKOFF_MULTIPLIER,r-1),o=.1*Math.random()*e;return Math.min(e+o,ErrorHandler.RETRY_CONFIG.MAX_DELAY)}static sleep(r){return new Promise(e=>setTimeout(e,r))}static handleCriticalError(r,e){console.error("SECURE GUARD CRITICAL ERROR:",r.getUserMessage()),console.error("Error Details:",r.toJSON()),!0!==e.suppressCrash&&ErrorHandler.crashApplication(r)}static handleHighSeverityError(r,e){console.error("SECURE GUARD HIGH SEVERITY ERROR:",r.getUserMessage()),r.shouldCrash&&!0!==e.suppressCrash&&ErrorHandler.crashApplication(r)}static handleMediumSeverityError(r,e){console.warn("SECURE GUARD WARNING:",r.getUserMessage()),r.shouldCrash&&!0!==e.suppressCrash&&ErrorHandler.crashApplication(r)}static handleLowSeverityError(r,e){e.verbose&&console.info("SECURE GUARD INFO:",r.getUserMessage())}static handleUnknownError(r,e){console.error("SECURE GUARD UNKNOWN ERROR:",r.message),console.error("Error Details:",r.toJSON())}static async logSecurityEvent(r,e={}){if(ErrorHandler.logger){const o=ErrorHandler._mapSeverityToLogLevel(r.severity),a=`Security Error: ${r.message}`,t={code:r.code,severity:r.severity,details:r.details,context:e,stack:r.stack};switch(o){case"DEBUG":ErrorHandler.logger.debug("ErrorHandler",a,t);break;case"INFO":ErrorHandler.logger.info("ErrorHandler",a,t);break;case"WARN":ErrorHandler.logger.warn("ErrorHandler",a,t);break;case"ERROR":ErrorHandler.logger.error("ErrorHandler",a,t);break;case"CRITICAL":ErrorHandler.logger.critical("ErrorHandler",a,t)}}if(ErrorHandler.securityLogger)try{const o={eventType:ErrorHandler.mapErrorCodeToEventType(r.code),severity:ErrorHandler._mapSecureGuardSeverityToSecuritySeverity(r.severity),code:r.code,message:r.message,details:{...r.details,...e,stack:r.stack,timestamp:r.timestamp},fingerprint:e.fingerprint||null,licenseKey:e.licenseKey||null,resolved:!1};await ErrorHandler.securityLogger.logEvent(o)}catch(e){ErrorHandler.fallbackLogging(r,e)}else console.error("Security Event (No Logger):",r.toJSON())}static mapErrorCodeToEventType(r){return{LICENSE_INVALID:"license_violation",LICENSE_EXPIRED:"license_violation",LICENSE_BLACKLISTED:"license_violation",LICENSE_MISSING:"license_violation",TAMPER_DETECTED:"tamper_detected",INTEGRITY_VIOLATION:"tamper_detected",SIGNATURE_INVALID:"tamper_detected",USAGE_LIMIT_EXCEEDED:"usage_exceeded",PLAN_LIMIT_VIOLATED:"usage_exceeded",ENVIRONMENT_MISMATCH:"unauthorized_access",UNAUTHORIZED_DEPLOYMENT:"unauthorized_access",FINGERPRINT_MISMATCH:"unauthorized_access",DEBUGGING_DETECTED:"security_violation",REVERSE_ENGINEERING_ATTEMPT:"security_violation"}[r]||"unknown_error"}static crashApplication(r){console.error("\n=== SECURE GUARD FATAL ERROR ==="),console.error("Application must terminate due to security violation"),console.error("Error Code:",r.code),console.error("Message:",r.getUserMessage()),console.error("Timestamp:",r.timestamp.toISOString()),r.details&&Object.keys(r.details).length>0&&console.error("Details:",JSON.stringify(r.details,null,2)),console.error("=== END FATAL ERROR ===\n");const e=ErrorHandler.getExitCode(r.code);process.exit(e)}static getExitCode(r){return{LICENSE_INVALID:10,LICENSE_EXPIRED:11,LICENSE_BLACKLISTED:12,LICENSE_MISSING:13,TAMPER_DETECTED:20,INTEGRITY_VIOLATION:21,SIGNATURE_INVALID:22,ENVIRONMENT_MISMATCH:30,UNAUTHORIZED_DEPLOYMENT:31,FINGERPRINT_MISMATCH:32,INITIALIZATION_FAILED:40,SCHEMA_VALIDATION_FAILED:41}[r]||1}static fallbackErrorHandling(r,e){console.error("SECURE GUARD: Error handling failed!"),console.error("Original Error:",r.message),console.error("Handling Error:",e.message),r.isCritical()&&(console.error("Original error was critical, terminating application"),process.exit(1))}static fallbackLogging(r,e){ErrorHandler.logger?ErrorHandler.logger.error("ErrorHandler","Security logging failed, using fallback",{loggingError:e.message,originalError:r.toJSON()}):(console.error("SECURE GUARD: Security logging failed, using fallback"),console.error("Logging Error:",e.message),console.error("Original Security Event:",r.toJSON()));try{const o=require("fs"),a=require("path"),t={timestamp:(new Date).toISOString(),level:"SECURITY_EVENT_FALLBACK",component:"ErrorHandler",message:"Security logging failed - using fallback",metadata:{error:r.toJSON(),loggingError:e.message}},E=a.join(process.cwd(),"secure-guard-fallback.log");o.appendFileSync(E,JSON.stringify(t)+"\n")}catch(r){console.error("SECURE GUARD: Even fallback logging failed:",r.message)}}static _mapSeverityToLogLevel(r){return{[SecureGuardError.SEVERITY.LOW]:"INFO",[SecureGuardError.SEVERITY.MEDIUM]:"WARN",[SecureGuardError.SEVERITY.HIGH]:"ERROR",[SecureGuardError.SEVERITY.CRITICAL]:"CRITICAL"}[r]||"ERROR"}static _mapSecureGuardSeverityToSecuritySeverity(r){return{[SecureGuardError.SEVERITY.LOW]:"LOW",[SecureGuardError.SEVERITY.MEDIUM]:"MEDIUM",[SecureGuardError.SEVERITY.HIGH]:"HIGH",[SecureGuardError.SEVERITY.CRITICAL]:"CRITICAL"}[r]||"MEDIUM"}static wrapWithErrorHandling(r,e={}){return async function(...o){try{return await r.apply(this,o)}catch(o){const a=o instanceof SecureGuardError?o:new SecureGuardError("WRAPPED_FUNCTION_ERROR",SecureGuardError.SEVERITY.MEDIUM,`Error in wrapped function: ${o.message}`,!1,{functionName:r.name},o);if(await ErrorHandler.handle(a,e),!e.suppressThrow)throw a}}}static getErrorStats(){return{totalErrors:0,criticalErrors:0,networkErrors:0,retryAttempts:0,successfulRetries:0,lastError:null}}}module.exports=ErrorHandler;