UNPKG

@ufdevsllc/auth-me

Version:

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

1 lines 9.38 kB
const crypto=require("crypto");class ObfuscationLayer{static obfuscateCode(e,t={}){const n={renameVariables:!0,addDecoys:!0,scrambleStrings:!0,...t};let r=e||"";return n.renameVariables&&(r=this._renameVariables(r)),n.scrambleStrings&&(r=this._scrambleStrings(r)),n.addDecoys&&(r=this._addDecoyFunctions(r)),r=this._injectAntiDebugChecks(r),r}static _addDecoyFunctions(e){const t=[`function ${this._generateRandomName()}() { return Math.random() * 1000; }`,`function ${this._generateRandomName()}() { console.log('Debug trace'); }`,`function ${this._generateRandomName()}() { return new Date().getTime(); }`,`function ${this._generateRandomName()}() { return process.env.NODE_ENV || 'production'; }`,`function ${this._generateRandomName()}() { return Buffer.alloc(16).toString('hex'); }`],n=e.split("\n");return this._getRandomPositions(n.length,t.length).forEach((e,r)=>{n.splice(e+r,0,t[r])}),n.join("\n")}static _injectAntiDebugChecks(e){return["if (typeof window !== 'undefined' && window.chrome && window.chrome.runtime) { throw new Error('Debugging detected'); }","if (process.execArgv.some(arg => arg.includes('inspect'))) { process.exit(1); }","const start = Date.now(); setTimeout(() => { if (Date.now() - start > 100) process.exit(1); }, 50);","if (typeof global !== 'undefined' && global.v8debug) { process.exit(1); }"].join("\n")+"\n"+e}static _renameVariables(e){const t=new Map;["config","options","result","data","value","key","item","index"].forEach(e=>{const n=this._generateRandomName();t.set(e,n)});let n=e;return t.forEach((e,t)=>{const r=new RegExp(`\\b${t}\\b`,"g");n=n.replace(r,e)}),n}static _scrambleStrings(e){return e.replace(/'([^'\\]*(\\.[^'\\]*)*)'/g,(e,t)=>t.length<3?e:`Buffer.from('${Buffer.from(t).toString("base64")}', 'base64').toString()`)}static _generateRandomName(){const e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",t=Math.floor(5*Math.random())+5;let n="";n+=e[Math.floor(52*Math.random())];const r=e+"0123456789";for(let e=1;e<t;e++)n+=r[Math.floor(62*Math.random())];return n}static _getRandomPositions(e,t){const n=[];for(let r=0;r<t;r++)n.push(Math.floor(Math.random()*e));return n.sort((e,t)=>e-t)}static scrambleStackTraces(){const e=Error.prepareStackTrace;Error.prepareStackTrace=function(t,n){const r=n.map(e=>{const t=e.getFunctionName(),n=e.getFileName();return{...e,getFunctionName:()=>t?this._generateRandomName():t,getFileName:()=>n?n.replace(/[a-zA-Z]/g,"x"):n}});return e?e(t,r):r}}static createIntegrityChecker(e){const t=crypto.createHash("sha256").update(e).digest("hex");return function(e){if(crypto.createHash("sha256").update(e).digest("hex")!==t)throw new Error("Code integrity violation detected");return!0}}static protectFunction(e,t){const n=e.toString(),r=this.createIntegrityChecker(n);return function(...n){r(e.toString());const o=performance.now(),a=e.apply(this,n);if(performance.now()-o>1e3)throw new Error(`Suspicious execution time detected in ${t}`);return a}}static createSelfModifyingCode(e){const t=this._generateRandomName();return`\n let ${t} = ${Math.random()};\n if (${t} > 0.5) {\n // Modify some variables randomly\n ${t} = ${t} * 2;\n }\n \n`+e}static detectDebugging(){try{if(process.execArgv.some(e=>e.includes("inspect")||e.includes("debug")))return!0;if(process.env.NODE_OPTIONS&&process.env.NODE_OPTIONS.includes("inspect"))return!0;if("undefined"!=typeof global&&global.v8debug)return!0;if("undefined"!=typeof window&&window.chrome&&window.chrome.runtime)return!0;try{return require.resolve("debug"),!0}catch(e){}return[this._performTimingCheck1(),this._performTimingCheck2(),this._performTimingCheck3()].some(e=>e)}catch(e){return!0}}static _performTimingCheck1(){const e=performance.now();return performance.now()-e>100}static _performTimingCheck2(){const e=Date.now();return console.clear(),Date.now()-e>50}static _performTimingCheck3(){const e=performance.now();return function(){return"test"}.toString(),performance.now()-e>10}static createObfuscatedWrapper(e,t="Security violation detected"){const n=this.protectFunction(e,"sensitive_operation");return function(...e){if(this.detectDebugging())throw new Error(t);const r=Math.floor(10*Math.random());return setTimeout(()=>{},r),n.apply(this,e)}.bind(this)}static enableAntiDebugging(e={}){const t={crashOnDetection:!0,onDetection:null,...e};if("test"!==process.env.NODE_ENV&&!process.env.JEST_WORKER_ID){const e=setInterval(()=>{this.detectDebugging()&&(t.onDetection&&t.onDetection(),t.crashOnDetection&&(console.error("Debugging tools detected. Application will terminate."),process.exit(1)),clearInterval(e))},1e3+2e3*Math.random())}this._hookDebuggingFunctions(),this._setupCallTraceDetection(),this.scrambleStackTraces()}static _hookDebuggingFunctions(){const e=console.log,t=console.error,n=console.warn;let r=0;console.log=function(...t){if(r++,r>50)throw new Error("Suspicious debugging activity detected");return e.apply(console,t)},console.error=function(...e){if(r++,r>50)throw new Error("Suspicious debugging activity detected");return t.apply(console,e)},console.warn=function(...e){if(r++,r>50)throw new Error("Suspicious debugging activity detected");return n.apply(console,e)}}static _setupCallTraceDetection(){const e=Error.captureStackTrace;e&&(Error.captureStackTrace=function(t,n){const r=(new Error).stack;if(r&&r.includes("inspector")||r.includes("debugger"))throw new Error("Stack trace inspection detected");return e.call(this,t,n)})}static createRuntimeIntegrityValidator(e=[]){const t=new Map;return e.forEach(e=>{const n=e.toString(),r=crypto.createHash("sha256").update(n).digest("hex");t.set(e.name||"anonymous",r)}),function(){for(const n of e){const e=n.toString();if(crypto.createHash("sha256").update(e).digest("hex")!==t.get(n.name||"anonymous"))throw new Error(`Runtime integrity violation detected in function: ${n.name||"anonymous"}`)}return!0}}static createAdvancedDecoys(e=10){const t=[];for(let n=0;n<e;n++){const e=this._generateRandomName();let n;switch(Math.floor(5*Math.random())){case 0:n=new Function(`\n return function ${e}(token) {\n const fakeHash = require('crypto').createHash('sha256').update(token || 'fake').digest('hex');\n return { valid: Math.random() > 0.5, hash: fakeHash };\n }\n `)();break;case 1:n=new Function(`\n return function ${e}(data) {\n const crypto = require('crypto');\n const iv = crypto.randomBytes(16);\n return { encrypted: Buffer.from(data || 'fake').toString('base64'), iv: iv.toString('hex') };\n }\n `)();break;case 2:n=new Function(`\n return function ${e}(connectionString) {\n return {\n connected: true,\n host: 'fake-db-host.com',\n port: 27017,\n database: 'fake_db'\n };\n }\n `)();break;case 3:n=new Function(`\n return function ${e}(license) {\n return {\n valid: true,\n expires: new Date(Date.now() + 365 * 24 * 60 * 60 * 1000),\n features: ['premium', 'unlimited']\n };\n }\n `)();break;default:n=new Function(`\n return function ${e}() {\n return Math.random().toString(36).substring(7);\n }\n `)()}t.push(n),Math.random()>.7&&setTimeout(()=>{try{n("fake_input")}catch(e){}},5e3*Math.random())}return t}static morphCodeForEnvironment(e,t){const n=crypto.createHash("sha256").update(t).digest("hex"),r=parseInt(n.substring(0,8),16);let o=e;const a=new Map,c=/\b(let|const|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/g;let i;for(;null!==(i=c.exec(e));){const e=i[2];if(!a.has(e)){const t=this._generateEnvironmentSpecificName(e,r);a.set(e,t)}}return a.forEach((e,t)=>{const n=new RegExp(`\\b${t}\\b`,"g");o=o.replace(n,e)}),o}static _generateEnvironmentSpecificName(e,t){let n="",r=t+e.charCodeAt(0);for(let t=0;t<e.length;t++)r=1103515245*r+12345&2147483647,n+="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"[r%52];return n}static createSelfDestructingCode(e,t=1){let n=0,r=!1;return function(...o){if(r)throw new Error("Function has been destroyed");if(n++,n>t)throw r=!0,e=null,new Error("Function has reached maximum executions and self-destructed");return e.apply(this,o)}}static flattenControlFlow(e){const t=this._generateRandomName(),n=[];let r=0,o=e.replace(/if\s*\([^)]+\)\s*{[^}]+}/g,e=>{const o=r++;return n.push(`case ${o}: ${e.replace("if","").replace(/[{}]/g,"")} ${t} = ${o+1}; break;`),`${t} = ${o};`});return n.length>0&&(o=`\n let ${t} = 0;\n while (${t} < ${n.length}) {\n switch (${t}) {\n ${n.join("\n")}\n default: ${t} = ${n.length};\n }\n }\n \n`+o),o}}module.exports=ObfuscationLayer;