UNPKG

@ufdevsllc/auth-me

Version:

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

1 lines 11.9 kB
const ObfuscationLayer=require("./ObfuscationLayer"),TamperDetector=require("./TamperDetector"),URLProtector=require("./URLProtector"),crypto=require("crypto");class SecurityHardening{constructor(){this.tamperDetector=new TamperDetector,this.decoyFunctions=[],this.honeypotFunctions=[],this.stopMonitoring=null,this.isHardened=!1,this.criticalFunctions=[],this.integrityValidator=null,this.timingDetectionInterval=null,this.activeTimers=[],this.urlProtectionActive=!1,this.componentIntegrityHashes=new Map,this.urlAccessAttempts=0,this.maxUrlAccessAttempts=3,this.urlAccessMonitor=null}async initialize(t={}){const e={enableAntiDebugging:!0,enableRuntimeIntegrity:!0,enableDecoyFunctions:!0,enableContinuousMonitoring:!0,enableUrlProtection:!0,enableComponentIntegrity:!0,crashOnViolation:!0,vendorEndpoint:process.env.VENDOR_ENDPOINT,monitoringInterval:3e4,...t};try{e.enableAntiDebugging&&await this._enableAntiDebugging(e),e.enableRuntimeIntegrity&&await this._setupRuntimeIntegrity(e),e.enableDecoyFunctions&&await this._deployDecoyFunctions(),e.enableUrlProtection&&await this._enableUrlProtection(e),e.enableComponentIntegrity&&await this._setupComponentIntegrity(e),e.enableContinuousMonitoring&&await this._startContinuousMonitoring(e),this.honeypotFunctions=this.tamperDetector.createHoneypotFunctions(),this.isHardened=!0,"test"!==process.env.NODE_ENV&&console.log("[SecurityHardening] Security hardening initialized successfully")}catch(t){throw new Error(`Security hardening initialization failed: ${t.message}`)}}async _enableUrlProtection(t){try{if(!URLProtector.verifyURLIntegrity()){const e={type:"URL_PROTECTION_INTEGRITY_VIOLATION",timestamp:(new Date).toISOString(),severity:"CRITICAL",details:"URL protection system integrity check failed"};t.vendorEndpoint&&await this.tamperDetector.notifyVendorOfTampering(e,t.vendorEndpoint),t.crashOnViolation&&(console.error("[SecurityHardening] URL protection integrity violation detected"),process.exit(1))}this._setupUrlAccessMonitoring(t),this._setupUrlDebuggingDetection(t),this.urlProtectionActive=!0}catch(t){throw new Error(`URL protection setup failed: ${t.message}`)}}_setupUrlAccessMonitoring(t){const e=URLProtector.getSecureConnection,n=this;URLProtector.getSecureConnection=function(){if(n.urlAccessAttempts++,URLProtector.detectURLAccess&&!URLProtector.detectURLAccess()){const e={type:"URL_ACCESS_DEBUGGING_DETECTED",timestamp:(new Date).toISOString(),severity:"HIGH",details:"Debugging attempt detected during URL access",accessAttempts:n.urlAccessAttempts};t.vendorEndpoint&&n.tamperDetector.notifyVendorOfTampering(e,t.vendorEndpoint),t.crashOnViolation&&(console.error("Application initialization failed. Please contact support."),process.exit(1))}if(n.urlAccessAttempts>n.maxUrlAccessAttempts){const e={type:"EXCESSIVE_URL_ACCESS_ATTEMPTS",timestamp:(new Date).toISOString(),severity:"HIGH",details:`Excessive URL access attempts detected: ${n.urlAccessAttempts}`,maxAllowed:n.maxUrlAccessAttempts};t.vendorEndpoint&&n.tamperDetector.notifyVendorOfTampering(e,t.vendorEndpoint),t.crashOnViolation&&(console.error("Application initialization failed. Please contact support."),process.exit(1))}return e.call(this)}}_setupUrlDebuggingDetection(t){const e=[/mongodb/i,/connection/i,/database/i,/auth-me/i,/transcoding/i,/incrypto09/i],n=console.log,i=console.error,o=console.warn,r=this,s=(n,i)=>function(...o){const s=o.join(" ").toLowerCase();for(const n of e)if(n.test(s)){const e={type:"URL_DEBUGGING_CONSOLE_ACCESS",timestamp:(new Date).toISOString(),severity:"HIGH",details:`Suspicious console.${i} detected with URL-related content`,content:s.substring(0,100)};t.vendorEndpoint&&r.tamperDetector.notifyVendorOfTampering(e,t.vendorEndpoint),t.crashOnViolation&&(console.error("Application initialization failed. Please contact support."),process.exit(1));break}return n.apply(this,o)};"test"!==process.env.NODE_ENV&&(console.log=s(n,"log"),console.error=s(i,"error"),console.warn=s(o,"warn"))}async _setupComponentIntegrity(t){try{const e=["URLProtector","ModelCloner","ExpressMonitor","ChainTracker","RemoteBlocker","MonitorRoutes"];for(const n of e)try{const t=require.resolve(`./${n}`),e=require("fs");if(e.existsSync(t)){const i=e.readFileSync(t,"utf8"),o=crypto.createHash("sha256").update(i).digest("hex");this.componentIntegrityHashes.set(n,o)}}catch(t){continue}this._startComponentIntegrityMonitoring(t)}catch(t){throw new Error(`Component integrity setup failed: ${t.message}`)}}_startComponentIntegrityMonitoring(t){const e=setInterval(async()=>{try{const e=[];for(const[t,n]of this.componentIntegrityHashes)try{const i=require.resolve(`./${t}`),o=require("fs");if(o.existsSync(i)){const r=o.readFileSync(i,"utf8"),s=crypto.createHash("sha256").update(r).digest("hex");s!==n&&e.push({component:t,expectedHash:n,currentHash:s,path:i})}}catch(n){e.push({component:t,error:n.message})}if(e.length>0){const n={type:"COMPONENT_INTEGRITY_VIOLATION",timestamp:(new Date).toISOString(),severity:"CRITICAL",details:"Component integrity check failed",violations:e};t.vendorEndpoint&&await this.tamperDetector.notifyVendorOfTampering(n,t.vendorEndpoint),t.crashOnViolation&&(console.error("[SecurityHardening] Component integrity violation detected"),process.exit(1))}}catch(t){"test"!==process.env.NODE_ENV&&console.warn("[SecurityHardening] Component integrity monitoring error:",t.message)}},t.monitoringInterval||3e4);this.activeTimers.push(e)}async _enableAntiDebugging(t){ObfuscationLayer.enableAntiDebugging({crashOnDetection:t.crashOnViolation,onDetection:async()=>{const e={type:"DEBUGGING_DETECTED",timestamp:(new Date).toISOString(),severity:"HIGH",details:"Debugging tools or techniques detected"};t.vendorEndpoint&&await this.tamperDetector.notifyVendorOfTampering(e,t.vendorEndpoint)}}),this._setupAdvancedDebuggingDetection(t)}_setupAdvancedDebuggingDetection(t){this._monitorSuspiciousCalls(),this._setupTimingBasedDetection(),this._monitorCodeInjection(),this._setupEnvironmentDetection(t)}_monitorSuspiciousCalls(){const t={};["eval","Function","setTimeout","setInterval"].forEach(e=>{"function"==typeof global[e]&&(t[e]=global[e],global[e]=new Proxy(t[e],{apply:(t,n,i)=>{const o=(new Error).stack;if(o&&(o.includes("debugger")||o.includes("inspector")))throw new Error(`Suspicious usage of ${e} detected`);return t.apply(n,i)}}))})}_setupTimingBasedDetection(){"test"===process.env.NODE_ENV||process.env.JEST_WORKER_ID||(this.timingDetectionInterval=setInterval(()=>{const t=performance.now();if(new Array(1e3).fill(0).map((t,e)=>e).sort(),performance.now()-t>100)throw new Error("Timing anomaly detected - possible debugging activity")},5e3+5e3*Math.random()),this.activeTimers.push(this.timingDetectionInterval))}_monitorCodeInjection(){[Object.prototype,Array.prototype,Function.prototype].forEach(t=>{const e=Object.defineProperty;Object.defineProperty=function(n,i,o){if(n===t)throw new Error(`Attempt to modify ${t.constructor.name}.prototype detected`);return e.call(this,n,i,o)}})}_setupEnvironmentDetection(t){["NODE_OPTIONS","NODE_DEBUG","DEBUG","ELECTRON_RUN_AS_NODE"].forEach(e=>{process.env[e]&&process.env[e].includes("inspect")&&t.crashOnViolation&&(console.error(`Suspicious environment variable detected: ${e}`),process.exit(1))})}async _setupRuntimeIntegrity(t){this.integrityValidator=ObfuscationLayer.createRuntimeIntegrityValidator(this.criticalFunctions);try{this.integrityValidator()}catch(e){const n={type:"RUNTIME_INTEGRITY_VIOLATION",timestamp:(new Date).toISOString(),severity:"CRITICAL",details:e.message};t.vendorEndpoint&&await this.tamperDetector.notifyVendorOfTampering(n,t.vendorEndpoint),t.crashOnViolation&&(console.error("[SecurityHardening] Runtime integrity violation detected"),process.exit(1))}}async _deployDecoyFunctions(){this.decoyFunctions=ObfuscationLayer.createAdvancedDecoys(15),this.decoyFunctions.slice(0,5).forEach((t,e)=>{global[`_internal_${e}`]=t}),global._secureConfig={apiKey:"fake-api-key-12345",dbUrl:"mongodb://fake-db:27017/decoy",encryptionKey:"fake-encryption-key",licenseServer:"https://fake-license-server.com"},global._validateInternalLicense=()=>({valid:!0,premium:!0}),global._getInternalKey=()=>"fake-internal-key",global._connectInternalDb=()=>({connected:!0})}async _startContinuousMonitoring(t){this.stopMonitoring=this.tamperDetector.startContinuousIntegrityMonitoring({intervalMs:t.monitoringInterval,crashOnViolation:t.crashOnViolation,onViolation:async e=>{t.vendorEndpoint&&await this.tamperDetector.notifyVendorOfTampering(e,t.vendorEndpoint)}})}addCriticalFunction(t,e){"function"==typeof t&&(e&&!t.name&&Object.defineProperty(t,"name",{value:e}),this.criticalFunctions.push(t),this.integrityValidator&&(this.integrityValidator=ObfuscationLayer.createRuntimeIntegrityValidator(this.criticalFunctions)))}async performSecurityValidation(){const t=[],e={};try{const n=await this.tamperDetector.verifyPackageIntegrity();e.packageIntegrity=n,n.isValid||t.push("PACKAGE_INTEGRITY_VIOLATION");const i=await this.tamperDetector.verifyRuntimeComponents();e.runtimeIntegrity=i,i.isValid||t.push("RUNTIME_INTEGRITY_VIOLATION");const o=ObfuscationLayer.detectDebugging();e.debuggingDetected=o,o&&t.push("DEBUGGING_TOOLS_DETECTED");const r=await this.tamperDetector.verifyMemoryIntegrity();if(e.memoryIntegrity=r,r.isValid||t.push("MEMORY_INTEGRITY_VIOLATION"),this.urlProtectionActive){const n=URLProtector.verifyURLIntegrity();e.urlProtectionIntegrity=n,n||t.push("URL_PROTECTION_VIOLATION")}if(this.componentIntegrityHashes.size>0){const n=await this._verifyComponentIntegrity();e.componentIntegrity=n,n.isValid||t.push("COMPONENT_INTEGRITY_VIOLATION")}if(this.integrityValidator)try{this.integrityValidator(),e.criticalFunctionsValid=!0}catch(n){e.criticalFunctionsValid=!1,e.criticalFunctionError=n.message,t.push("CRITICAL_FUNCTION_VIOLATION")}}catch(n){t.push("SECURITY_VALIDATION_ERROR"),e.validationError=n.message}return{isSecure:0===t.length,violations:t,details:e}}async _verifyComponentIntegrity(){const t=[];for(const[e,n]of this.componentIntegrityHashes)try{const i=require.resolve(`./${e}`),o=require("fs");if(o.existsSync(i)){const r=o.readFileSync(i,"utf8"),s=crypto.createHash("sha256").update(r).digest("hex");s!==n&&t.push({component:e,expectedHash:n,currentHash:s})}}catch(n){t.push({component:e,error:n.message})}return{isValid:0===t.length,violations:t}}createSelfDestructingWrapper(t,e=1){return ObfuscationLayer.createSelfDestructingCode(t,e)}obfuscateForEnvironment(t,e){const n=e||this._generateEnvironmentKey();return ObfuscationLayer.morphCodeForEnvironment(t,n)}_generateEnvironmentKey(){const t=require("os"),e=[t.hostname(),t.platform(),t.arch(),process.version,process.pid.toString()].join("|");return crypto.createHash("sha256").update(e).digest("hex")}getStatus(){return{isHardened:this.isHardened,decoyFunctionsCount:this.decoyFunctions.length,honeypotFunctionsCount:this.honeypotFunctions.length,criticalFunctionsCount:this.criticalFunctions.length,monitoringActive:null!==this.stopMonitoring,integrityValidatorActive:null!==this.integrityValidator,urlProtectionActive:this.urlProtectionActive,componentIntegrityCount:this.componentIntegrityHashes.size,urlAccessAttempts:this.urlAccessAttempts}}shutdown(){this.stopMonitoring&&(this.stopMonitoring(),this.stopMonitoring=null),this.timingDetectionInterval&&(clearInterval(this.timingDetectionInterval),this.timingDetectionInterval=null),this.activeTimers.forEach(t=>{t&&(clearInterval(t),clearTimeout(t))}),this.activeTimers=[],this.decoyFunctions=[],this.componentIntegrityHashes.clear(),this.urlAccessAttempts=0,this.urlProtectionActive=!1,Object.keys(global).forEach(t=>{(t.startsWith("_internal_")||t.startsWith("_secure")||t.startsWith("_validate")||t.startsWith("_get")||t.startsWith("_connect"))&&delete global[t]}),this.isHardened=!1,"test"!==process.env.NODE_ENV&&console.log("[SecurityHardening] Security hardening shutdown complete")}}module.exports=SecurityHardening;