Closure-compiler: adding prefix to obfuscated variables

Viewed 235

My goal is adding prefix that will be prepended to all obfuscate variables. for example: instead of obfuscating myVar into x, it will use the prefix $pre so the result will be something like: $prex

I'm using closure-compiler. Following Closure-compiler wiki, I've used rename_variable_prefix with no success unfortunately.

Code example:

const ClosureCompiler = require('google-closure-compiler').jsCompiler;

console.log(ClosureCompiler.CONTRIB_PATH); // absolute path to the contrib folder which contains externs

const closureCompiler = new ClosureCompiler({
  compilation_level: 'ADVANCED',
  rename_variable_prefix: '$pre'
});

const compilerProcess = closureCompiler.run([{
 path: 'file-one.js',
 src: 'function add(node){
          let test = window["test"];
          if (node.hzix == test)return 1;
       }
       add(window["node"]);
       window.add = add;',
 sourceMap: null // optional input source map
}], (exitCode, stdOut, stdErr) => {
  //compilation complete
});

The result code is:

  {\n"version":3,\n"file":"compiled.js",\n"lineCount":1,\n"mappings":"AAAiGA,MAAAC,IAAA,CAAjGA,QAAY,CAACC,CAAD,CAAM,CAA2B,GAAIA,CAAAC,EAAJ,EAAfH,MAAAI,KAAe,CAAsB,MAAO,EAAxD;",\n"sources":["file-one.js"],\n"names":["window","add","node","hzix","test"]\n}\n',
src: 'window.add=function(a){if(a.a==window.test)return 1};

The result did not include the prefix '$pre'. What am i missing?

1 Answers

If it's any help, I got this to work in the Java closure compiler via the compiler option, renamePrefix. e.g.

m_options.renamePrefix = "$pre"; 

Where m_options is the CompilerOptions passed to e.g. compileModules:

m_compiler.compileModules(m_externals, m_modules, m_options);

My issue was that I had a collision with another global obfuscated variable from a 3rd party module, both using the global namespace. The result was a subtle and therefore dangerous bug that only occurred in minified code.

e.g. The minifier generates global symbols aa, ab, ga etc which could easily collide with the same symbols from another minified package - so you can see the inspiration for modules.

I think you would always want to at least prefix minified globals, otherwise this could be a ticking time bomb if you're also loading 3rd party libs.

Related