UNPKG

@ufdevsllc/auth-me

Version:

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

1 lines 10.7 kB
const crypto=require("crypto"),fs=require("fs"),path=require("path");class TamperDetector{constructor(){this.integrityChecks=[],this.runtimeComponentHashes=new Map,this.debuggingDetected=!1,this._initializeCriticalFiles()}_initializeCriticalFiles(){const e=this._getPackageRoot(),t=["package.json","index.js","src/core/SecureGuard.js","src/core/LicenseValidator.js","src/core/EnvironmentFingerprinter.js","src/core/TamperDetector.js"];for(const s of t){const t=path.join(e,s);if(fs.existsSync(t))try{const e=this.calculateFileHash(t);this.integrityChecks.push({filePath:t,expectedHash:e,algorithm:"sha256"})}catch(e){console.warn(`[TamperDetector] Warning: Could not calculate hash for ${s}: ${e.message}`)}}}_getPackageRoot(){let e=__dirname;for(;e!==path.dirname(e);){if(fs.existsSync(path.join(e,"package.json")))return e;e=path.dirname(e)}return process.cwd()}addIntegrityCheck(e,t=null,s="sha256"){if(!fs.existsSync(e))throw new Error(`File does not exist: ${e}`);const o=t||this.calculateFileHash(e,s);this.integrityChecks.push({filePath:path.resolve(e),expectedHash:o,algorithm:s})}async verifyPackageIntegrity(){const e=[],t=[];for(const s of this.integrityChecks)try{const o=this.calculateFileHash(s.filePath,s.algorithm),r=o===s.expectedHash,n={isValid:r,filePath:s.filePath,expectedHash:s.expectedHash,actualHash:o};e.push(n),r||t.push(n)}catch(o){const r={isValid:!1,filePath:s.filePath,expectedHash:s.expectedHash,actualHash:"ERROR",error:o.message};e.push(r),t.push(r)}return{isValid:0===t.length,results:e,violations:t}}async verifyRuntimeComponents(){const e=[],t=[];try{if("test"===process.env.NODE_ENV||process.env.JEST_WORKER_ID)return{isValid:!0,components:["test_mode_skip"],violations:[]};const s=["SecureGuard","LicenseValidator","EnvironmentFingerprinter","TamperDetector"];for(const o of s)try{const s=path.join(__dirname,`${o}.js`);if(fs.existsSync(s)){const r=require(s);if("function"==typeof r||"object"==typeof r){e.push(o);const r=fs.readFileSync(s,"utf8"),n=crypto.createHash("sha256").update(r).digest("hex");this.runtimeComponentHashes.has(o)?n!==this.runtimeComponentHashes.get(o)&&t.push(o):this.runtimeComponentHashes.set(o,n)}else t.push(o)}else t.push(o)}catch(e){t.push(o)}this._detectGlobalModifications()&&t.push("global_modifications"),this._detectPrototypePollution()&&t.push("prototype_pollution")}catch(e){t.push("runtime_check_error")}return{isValid:0===t.length,components:e,violations:t}}_detectGlobalModifications(){try{const suspiciousGlobals=["eval","Function","require","process","global","__dirname","__filename"];for(const globalName of suspiciousGlobals)if(global[globalName]&&typeof global[globalName]!=typeof eval(globalName))return!0;return!1}catch(e){return!0}}_detectPrototypePollution(){try{const e={};if(e.constructor!==Object||e.toString!==Object.prototype.toString||e.valueOf!==Object.prototype.valueOf)return!0;const t=["__proto__","constructor","isAdmin","isAuthenticated"];for(const e of t)if(Object.prototype.hasOwnProperty(e)&&"constructor"!==e)return!0;return!1}catch(e){return!0}}async createSignatureFile(e){const t={};for(const e of this.integrityChecks)try{const s=this.calculateFileHash(e.filePath,e.algorithm);t[path.relative(this._getPackageRoot(),e.filePath)]={hash:s,algorithm:e.algorithm,timestamp:(new Date).toISOString()}}catch(t){console.warn(`[TamperDetector] Warning: Could not create signature for ${e.filePath}: ${t.message}`)}const s={version:"1.0.0",created:(new Date).toISOString(),signatures:t};fs.writeFileSync(e,JSON.stringify(s,null,2))}async verifySignatureFile(e){const t=[],s=[];try{if(!fs.existsSync(e))return s.push("Signature file does not exist"),{isValid:!1,violations:[],errors:s};const o=JSON.parse(fs.readFileSync(e,"utf8"));if(!o.signatures)return s.push("Invalid signature file format"),{isValid:!1,violations:[],errors:s};const r=this._getPackageRoot();for(const[e,n]of Object.entries(o.signatures)){const o=path.join(r,e);try{if(!fs.existsSync(o)){t.push(`Missing file: ${e}`);continue}this.calculateFileHash(o,n.algorithm)!==n.hash&&t.push(`Hash mismatch: ${e}`)}catch(t){s.push(`Error verifying ${e}: ${t.message}`)}}}catch(e){s.push(`Error reading signature file: ${e.message}`)}return{isValid:0===t.length&&0===s.length,violations:t,errors:s}}detectDebuggingTools(){try{const e=[process.env.NODE_OPTIONS&&process.env.NODE_OPTIONS.includes("--inspect"),process.env.NODE_OPTIONS&&process.env.NODE_OPTIONS.includes("--debug"),process.debugPort,"undefined"!=typeof v8debug,"undefined"!=typeof window&&window.chrome&&window.chrome.runtime,"undefined"!=typeof require&&(()=>{try{return require("debug"),!0}catch(e){return!1}})()].some(e=>!0===e);return e&&(this.debuggingDetected=!0),e}catch(e){return!0}}calculateFileHash(e,t="sha256"){try{const s=fs.readFileSync(e),o=crypto.createHash(t);return o.update(s),o.digest("hex")}catch(t){throw new Error(`Failed to calculate hash for ${e}: ${t.message}`)}}getIntegrityCheckSummary(){return{totalChecks:this.integrityChecks.length,files:this.integrityChecks.map(e=>({path:e.filePath,algorithm:e.algorithm})),runtimeComponents:Array.from(this.runtimeComponentHashes.keys()),debuggingDetected:this.debuggingDetected}}_resetRuntimeHashes(){this.runtimeComponentHashes.clear(),this.debuggingDetected=!1}clearIntegrityChecks(){this.integrityChecks=[],this.runtimeComponentHashes.clear()}async notifyVendorOfTampering(e,t){try{const s={timestamp:(new Date).toISOString(),eventType:"TAMPERING_DETECTED",severity:"CRITICAL",details:e,environment:{nodeVersion:process.version,platform:process.platform,arch:process.arch,hostname:require("os").hostname(),pid:process.pid},packageInfo:{name:"@ufdevsllc/auth-me",version:this._getPackageVersion()}};t&&t.startsWith("http")&&await this._sendWebhookNotification(t,s),await this._logSecurityEvent(s),"test"!==process.env.NODE_ENV&&console.warn("[TamperDetector] Vendor notified of tampering detection")}catch(t){this._fallbackLogging(e,t)}}async _sendWebhookNotification(e,t){const s=require("https"),o=require("http"),r=require("url");return new Promise((n,i)=>{const a=r.parse(e),c="https:"===a.protocol?s:o,l=JSON.stringify(t),h={hostname:a.hostname,port:a.port,path:a.path,method:"POST",headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(l),"User-Agent":"SecureGuard-TamperDetector/1.0"},timeout:5e3},u=c.request(h,e=>{let t="";e.on("data",e=>{t+=e}),e.on("end",()=>{e.statusCode>=200&&e.statusCode<300?n():i(new Error(`Webhook failed with status ${e.statusCode}: ${t}`))})});u.on("error",e=>{i(e)}),u.on("timeout",()=>{u.destroy(),i(new Error("Webhook request timeout"))}),u.write(l),u.end()})}async _logSecurityEvent(e){try{const t=require("fs"),s=require("path"),o=s.join(process.cwd(),"secure-guard-logs");t.existsSync(o)||t.mkdirSync(o,{recursive:!0});const r=s.join(o,`security-events-${(new Date).toISOString().split("T")[0]}.log`),n=JSON.stringify(e)+"\n";t.appendFileSync(r,n)}catch(e){"test"!==process.env.NODE_ENV&&console.error("[TamperDetector] Failed to log security event:",e.message)}}_fallbackLogging(e,t){try{const s=require("fs"),o="secure-guard-fallback.log",r={timestamp:(new Date).toISOString(),event:"TAMPERING_DETECTED",details:e,notificationError:t.message,fallbackReason:"Primary notification methods failed"};s.appendFileSync(o,JSON.stringify(r)+"\n")}catch(t){"test"!==process.env.NODE_ENV&&(console.error("[TamperDetector] CRITICAL: All logging methods failed. Tampering detected but could not notify vendor."),console.error("Tamper details:",e))}}_getPackageVersion(){try{const e=require("fs"),t=require("path").join(this._getPackageRoot(),"package.json");if(e.existsSync(t))return JSON.parse(e.readFileSync(t,"utf8")).version||"1.0.0"}catch(e){}return"1.0.0"}startContinuousIntegrityMonitoring(e={}){const t={intervalMs:3e4,onViolation:null,crashOnViolation:!0,...e};let s=0;const o=setInterval(async()=>{try{const e=await this.verifyPackageIntegrity(),o=await this.verifyRuntimeComponents(),r=this.detectDebuggingTools();if(e.isValid&&o.isValid&&!r)s=Math.max(0,s-1);else{s++;const n={packageIntegrity:e,runtimeComponents:o,debuggingDetected:r,violationCount:s,timestamp:(new Date).toISOString()};t.onViolation&&t.onViolation(n),process.env.VENDOR_ENDPOINT&&await this.notifyVendorOfTampering(n,process.env.VENDOR_ENDPOINT),s>=3&&t.crashOnViolation&&(console.error("[TamperDetector] CRITICAL: Multiple integrity violations detected. Application will terminate."),process.exit(1))}}catch(e){"test"!==process.env.NODE_ENV&&console.warn("[TamperDetector] Error during integrity monitoring:",e.message)}},t.intervalMs);return()=>{clearInterval(o)}}async verifyMemoryIntegrity(){const e=[],t={};try{const s=process.memoryUsage();if(t.memoryUsage=s,this._baselineMemory){const o=(s.heapUsed-this._baselineMemory.heapUsed)/this._baselineMemory.heapUsed;o>2&&(e.push("suspicious_memory_growth"),t.heapGrowthRatio=o)}else this._baselineMemory=s;const o=Object.keys(global);if(this._baselineGlobalKeys){const s=o.filter(e=>!this._baselineGlobalKeys.has(e));s.length>10&&(e.push("excessive_global_modifications"),t.newGlobalKeys=s)}else this._baselineGlobalKeys=new Set(o);const r=[Object.prototype,Array.prototype,Function.prototype];for(const s of r){const o=Object.getOwnPropertyNames(s),r=this._getExpectedPrototypeKeys(s),n=o.filter(e=>!r.includes(e));n.length>0&&(e.push("prototype_pollution_detected"),t.pollutedPrototype=s.constructor.name,t.unexpectedKeys=n)}}catch(s){e.push("memory_integrity_check_failed"),t.error=s.message}return{isValid:0===e.length,violations:e,details:t}}_getExpectedPrototypeKeys(e){return{Object:["constructor","toString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString"],Array:["constructor","length","push","pop","shift","unshift","slice","splice","indexOf","join","toString","valueOf"],Function:["constructor","call","apply","bind","toString","valueOf"]}[e.constructor.name]||[]}createHoneypotFunctions(){const e=[],t=function(){return console.warn("[TamperDetector] Honeypot triggered: Fake license validation accessed"),{valid:!0,expires:new Date(Date.now()+31536e6),features:["unlimited","premium"]}},s=function(){return console.warn("[TamperDetector] Honeypot triggered: Fake database connection accessed"),{connected:!0,host:"honeypot-db.example.com",authenticate:()=>Promise.resolve(!0),collection:()=>({find:()=>Promise.resolve([]),insertOne:()=>Promise.resolve({insertedId:"fake-id"})})}},o=function(){return console.warn("[TamperDetector] Honeypot triggered: Fake encryption key accessed"),"fake-encryption-key-do-not-use"};return e.push(t,s,o),global._validateLicense=t,global._connectDb=s,global._getKey=o,e}}module.exports=TamperDetector;