0

I have a few small Javascript files for a website. At this moment, I use script to put them in a file and then run terser to minimize it. With the minimized version, the website runs without any problem.

Now I would like to obfuscate it with JavaScript-Obfuscator (https://obfuscator.io/). I created a gulp task to generate the obfuscated version

gulp.task('obfus', function() {
    gulp.src('src/main/webapp/js/mysite.min.js')
        .pipe(javascriptObfuscator({
                compact: true
        })).pipe(gulp.dest('src/main/webapp/js/dist'));
});

However, I got this error when running the website:

Uncaught ReferenceError: loc is not defined
    at eval (eval at exampledomain.<computed> (mysite.min.js?:1:71178), <anonymous>:1:39)

Here is the line of code where the error happens:

eval('exampledomain.build' + type + '(loc)'); 

I need to use "eval" to call different functions based on "type".

How to fix this problem?

curious1
  • 14,155
  • 37
  • 130
  • 231
  • 2
    Why is `eval` used at all? – Sebastian Simon Dec 25 '22 at 04:23
  • I updated the line of "eval". It basically calls different functions depending on a parameter called "type". – curious1 Dec 25 '22 at 04:27
  • 2
    Okay, then this line should be `exampledomain["build" + type](loc);` or ``exampledomain[`build${type}`](loc);`` instead. Absolutely no reason to use `eval`. – Sebastian Simon Dec 25 '22 at 04:31
  • It appears that the problem is resolved after updating the line of code based on your suggestion. Could you please make it the answer? Also explain why the obfuscated code generates the error because of "eval" if you happen to know why? – curious1 Dec 25 '22 at 04:41
  • 2
    The obfuscator you found doesn’t inspect strings to be `eval`’d. Some other obfuscator might do it. This is a basic use case for [bracket notation vs. dot notation](/q/4968406/4642212). Your question is already closed as a duplicate with a relevant Q&A. – Sebastian Simon Dec 25 '22 at 04:50
  • Thanks for the info and pointing to me to the right place! Best. – curious1 Dec 25 '22 at 04:52

1 Answers1

0
gulp.task('obfus', function() {
  return gulp.src('src/main/webapp/js/mysite.min.js')
    .pipe(javascriptObfuscator({
      compact: true
    }))
    .pipe(gulp.dest('src/main/webapp/js/dist'));
});

I made the following changes:

Added a return statement before the gulp.src call to ensure that the task returns a stream. This is important because it allows Gulp to correctly handle errors that may occur during the task execution.

Added indentation to make the code more readable and easier to understand.

  • 1
    Thanks for chiming in! I am a little confused. I don't have the problem in obfuscating the code. The problem is that the obfuscated code has an error. – curious1 Dec 25 '22 at 04:39