@ufdevsllc/auth-me
Version:
Comprehensive licensing, security monitoring, and data mirroring package with hardcoded vendor-controlled database connection
1 lines • 11.4 kB
JavaScript
const Logger=require("./Logger");class SecurityEventLogger{static EVENT_CATEGORIES={LICENSE_VIOLATION:{name:"License Violation",description:"Events related to license validation failures",eventTypes:["license_invalid","license_expired","license_blacklisted","license_missing"],defaultSeverity:"HIGH",requiresImmediateAction:!0},TAMPER_DETECTION:{name:"Tamper Detection",description:"Events related to package tampering or integrity violations",eventTypes:["tamper_detected","integrity_violation","signature_invalid"],defaultSeverity:"CRITICAL",requiresImmediateAction:!0},USAGE_VIOLATION:{name:"Usage Violation",description:"Events related to usage limit violations",eventTypes:["usage_exceeded","plan_limit_violated","quota_exceeded"],defaultSeverity:"MEDIUM",requiresImmediateAction:!1},UNAUTHORIZED_ACCESS:{name:"Unauthorized Access",description:"Events related to unauthorized access attempts",eventTypes:["unauthorized_deployment","environment_mismatch","fingerprint_mismatch"],defaultSeverity:"HIGH",requiresImmediateAction:!0},SECURITY_VIOLATION:{name:"Security Violation",description:"General security violations and suspicious activities",eventTypes:["debugging_detected","reverse_engineering_attempt","suspicious_activity"],defaultSeverity:"MEDIUM",requiresImmediateAction:!1},SYSTEM_ERROR:{name:"System Error",description:"System-level errors and failures",eventTypes:["initialization_failed","connection_failed","database_error"],defaultSeverity:"LOW",requiresImmediateAction:!1}};static SEVERITY_LEVELS={LOW:{value:1,name:"LOW",color:"[32m",escalationThreshold:10,notificationRequired:!1},MEDIUM:{value:2,name:"MEDIUM",color:"[33m",escalationThreshold:5,notificationRequired:!0},HIGH:{value:3,name:"HIGH",color:"[31m",escalationThreshold:2,notificationRequired:!0},CRITICAL:{value:4,name:"CRITICAL",color:"[35m",escalationThreshold:1,notificationRequired:!0}};constructor(e,t=null){this.logger=e,this.secureConnection=t,this.eventCounts=new Map,this.recentEvents=new Map,this.maxRecentEvents=100,this.eventHandlers=[],this.enableRealTimeAlerts=!1,this.pendingEvents=[],this.batchProcessing=!1,this.batchSize=50,this.batchInterval=5e3,this._initializeSecurityModels(),this._startBatchProcessor()}async logEvent(e){try{const t=this._enrichSecurityEvent(e),i=this._categorizeEvent(t.eventType);t.severity||(t.severity=i?.defaultSeverity||"MEDIUM"),this._updateEventStatistics(t),this._storeRecentEvent(t),await this._logToBaseLogger(t,i),this.batchProcessing?this.pendingEvents.push(t):await this._persistSecurityEvent(t),this.enableRealTimeAlerts&&await this._handleRealTimeAlert(t,i),await this._triggerEventHandlers(t,i),await this._checkEscalation(t,i)}catch(t){this.logger.error("SecurityEventLogger","Failed to log security event",{error:t.message,originalEvent:e}),this._fallbackSecurityLogging(e,t)}}async logLicenseViolation(e,t,i={},n=null){await this.logEvent({eventType:"license_violation",severity:"HIGH",code:e,message:`License violation detected: ${e}`,details:{violationType:e,licenseKey:this._maskLicenseKey(t),...i},fingerprint:n,licenseKey:this._maskLicenseKey(t),resolved:!1})}async logTamperDetection(e,t={},i=null){await this.logEvent({eventType:"tamper_detected",severity:"CRITICAL",code:e,message:`Tampering detected: ${e}`,details:{tamperType:e,...t},fingerprint:i,licenseKey:null,resolved:!1})}async logUsageViolation(e,t={},i,n=null){await this.logEvent({eventType:"usage_exceeded",severity:"MEDIUM",code:e,message:`Usage limit exceeded: ${e}`,details:{limitType:e,...t},fingerprint:n,licenseKey:this._maskLicenseKey(i),resolved:!1})}async logUnauthorizedAccess(e,t={},i=null){await this.logEvent({eventType:"unauthorized_access",severity:"HIGH",code:e,message:`Unauthorized access detected: ${e}`,details:{accessType:e,...t},fingerprint:i,licenseKey:null,resolved:!1})}getSecurityStatistics(){const e={totalEvents:0,eventsByType:{},eventsBySeverity:{},eventsByCategory:{},recentEventsCount:0,pendingEventsCount:this.pendingEvents.length,batchProcessing:this.batchProcessing};for(const[t,i]of this.eventCounts.entries()){const[n,s]=t.split(":");e.totalEvents+=i,e.eventsByType[n]=(e.eventsByType[n]||0)+i,e.eventsBySeverity[s]=(e.eventsBySeverity[s]||0)+i}for(const[t,i]of Object.entries(SecurityEventLogger.EVENT_CATEGORIES)){let n=0;for(const t of i.eventTypes)n+=e.eventsByType[t]||0;e.eventsByCategory[t]=n}for(const t of this.recentEvents.values())e.recentEventsCount+=t.length;return e}getRecentEvents(e=50,t=null,i=null){let n=[];for(const e of this.recentEvents.values())n=n.concat(e);return t&&(n=n.filter(e=>e.eventType===t)),i&&(n=n.filter(e=>e.severity===i)),n.sort((e,t)=>new Date(t.timestamp)-new Date(e.timestamp)).slice(0,e)}getEventsRequiringAction(){const e=[];for(const t of this.recentEvents.values())for(const i of t){const t=this._categorizeEvent(i.eventType);t?.requiresImmediateAction&&!i.resolved&&e.push(i)}return e.sort((e,t)=>SecurityEventLogger.SEVERITY_LEVELS[t.severity].value-SecurityEventLogger.SEVERITY_LEVELS[e.severity].value)}async resolveEvent(e,t=null){try{if(this.secureConnection){const i=this.secureConnection.model("SecurityEvent");if((await i.updateOne({_id:e},{resolved:!0,resolvedAt:new Date,resolution:t})).modifiedCount>0)return this.logger.info("SecurityEventLogger","Security event resolved",{eventId:e,resolution:t}),!0}for(const i of this.recentEvents.values()){const n=i.find(t=>t._id===e);if(n)return n.resolved=!0,n.resolvedAt=new Date,n.resolution=t,!0}return!1}catch(t){return this.logger.error("SecurityEventLogger","Failed to resolve security event",{eventId:e,error:t.message}),!1}}setRealTimeAlerts(e){this.enableRealTimeAlerts=e,this.logger.info("SecurityEventLogger","Real-time alerts "+(e?"enabled":"disabled"))}addEventHandler(e){"function"==typeof e&&(this.eventHandlers.push(e),this.logger.debug("SecurityEventLogger","Event handler added"))}removeEventHandler(e){const t=this.eventHandlers.indexOf(e);return-1!==t&&(this.eventHandlers.splice(t,1),this.logger.debug("SecurityEventLogger","Event handler removed"),!0)}setBatchProcessing(e,t=50,i=5e3){this.batchProcessing=e,this.batchSize=t,this.batchInterval=i,this.logger.info("SecurityEventLogger","Batch processing "+(e?"enabled":"disabled"),{batchSize:t,batchInterval:i})}async flushPendingEvents(){if(0===this.pendingEvents.length)return;const e=[...this.pendingEvents];this.pendingEvents=[];try{await this._batchPersistEvents(e),this.logger.debug("SecurityEventLogger","Pending events flushed",{count:e.length})}catch(t){throw this.pendingEvents=e.concat(this.pendingEvents),t}}_enrichSecurityEvent(e){return{...e,timestamp:e.timestamp||new Date,instanceId:this.logger.instanceId,nodeVersion:process.version,platform:process.platform,pid:process.pid}}_categorizeEvent(e){for(const t of Object.values(SecurityEventLogger.EVENT_CATEGORIES))if(t.eventTypes.includes(e))return t;return null}_updateEventStatistics(e){const t=`${e.eventType}:${e.severity}`;this.eventCounts.set(t,(this.eventCounts.get(t)||0)+1)}_storeRecentEvent(e){const t=e.eventType;this.recentEvents.has(t)||this.recentEvents.set(t,[]);const i=this.recentEvents.get(t);i.unshift(e),i.length>this.maxRecentEvents&&i.splice(this.maxRecentEvents)}async _logToBaseLogger(e,t){SecurityEventLogger.SEVERITY_LEVELS[e.severity];const i=this._mapSeverityToLogLevel(e.severity),n=`SECURITY EVENT: ${e.message}`,s={eventType:e.eventType,severity:e.severity,code:e.code,category:t?.name||"Unknown",requiresAction:t?.requiresImmediateAction||!1,details:e.details,fingerprint:e.fingerprint,licenseKey:e.licenseKey};switch(i){case"DEBUG":this.logger.debug("SecurityEventLogger",n,s);break;case"INFO":this.logger.info("SecurityEventLogger",n,s);break;case"WARN":this.logger.warn("SecurityEventLogger",n,s);break;case"ERROR":this.logger.error("SecurityEventLogger",n,s);break;case"CRITICAL":this.logger.critical("SecurityEventLogger",n,s)}}async _persistSecurityEvent(e){if(this.secureConnection)try{const t=new(this.secureConnection.model("SecurityEvent"))(e);await t.save()}catch(e){throw new Error(`Failed to persist security event: ${e.message}`)}}async _batchPersistEvents(e){if(this.secureConnection&&0!==e.length)try{const t=this.secureConnection.model("SecurityEvent");await t.insertMany(e)}catch(e){throw new Error(`Failed to batch persist security events: ${e.message}`)}}async _handleRealTimeAlert(e,t){const i=SecurityEventLogger.SEVERITY_LEVELS[e.severity];i.notificationRequired&&(console.error(`${i.color}[SECURITY ALERT] ${e.message}[0m`),t?.requiresImmediateAction&&console.error(`${i.color}[ACTION REQUIRED] Immediate attention needed[0m`))}async _triggerEventHandlers(e,t){for(const i of this.eventHandlers)try{await i(e,t)}catch(t){this.logger.error("SecurityEventLogger","Event handler failed",{error:t.message,eventType:e.eventType})}}async _checkEscalation(e,t){const i=SecurityEventLogger.SEVERITY_LEVELS[e.severity],n=`${e.eventType}:${e.severity}`,s=this.eventCounts.get(n)||0;s>=i.escalationThreshold&&await this.logEvent({eventType:"event_escalation",severity:"HIGH",code:"ESCALATION_THRESHOLD_REACHED",message:`Event escalation: ${e.eventType} occurred ${s} times`,details:{originalEventType:e.eventType,originalSeverity:e.severity,occurrenceCount:s,threshold:i.escalationThreshold},fingerprint:e.fingerprint,licenseKey:e.licenseKey,resolved:!1})}_initializeSecurityModels(){if(this.secureConnection)try{this.secureConnection.model("SecurityEvent")}catch(e){const t=new(require("mongoose").Schema)({eventType:{type:String,required:!0},severity:{type:String,required:!0},code:{type:String,required:!0},message:{type:String,required:!0},details:{type:Object,default:{}},fingerprint:{type:Object,default:null},licenseKey:{type:String,default:null},resolved:{type:Boolean,default:!1},resolvedAt:{type:Date,default:null},resolution:{type:String,default:null},timestamp:{type:Date,default:Date.now},instanceId:{type:String,required:!0},nodeVersion:{type:String},platform:{type:String},pid:{type:Number}},{timestamps:!0,collection:"security_events"});t.index({eventType:1,timestamp:-1}),t.index({severity:1,timestamp:-1}),t.index({resolved:1,timestamp:-1}),t.index({licenseKey:1,timestamp:-1}),this.secureConnection.model("SecurityEvent",t)}}_startBatchProcessor(){setInterval(async()=>{if(this.batchProcessing&&this.pendingEvents.length>=this.batchSize)try{await this.flushPendingEvents()}catch(e){this.logger.error("SecurityEventLogger","Batch processing failed",{error:e.message,pendingCount:this.pendingEvents.length})}},this.batchInterval)}_mapSeverityToLogLevel(e){return{LOW:"INFO",MEDIUM:"WARN",HIGH:"ERROR",CRITICAL:"CRITICAL"}[e]||"INFO"}_maskLicenseKey(e){return!e||e.length<8?"[REDACTED]":e.substring(0,4)+"****"+e.substring(e.length-4)}_fallbackSecurityLogging(e,t){try{const i={timestamp:(new Date).toISOString(),level:"SECURITY_EVENT_FAILURE",component:"SecurityEventLogger",message:"Security event logging failed - using fallback",metadata:{originalEvent:e,loggingError:t.message,fallbackReason:"Primary security logging failed"}},n=require("fs"),s=require("path").join(process.cwd(),"secure-guard-security-fallback.log");n.appendFileSync(s,JSON.stringify(i)+"\n")}catch(t){"test"!==process.env.NODE_ENV&&(console.error("[SecurityEventLogger] CRITICAL: All security logging methods failed"),console.error("Original event:",e),console.error("Fallback error:",t.message))}}}module.exports=SecurityEventLogger;