Browse Source

`sourceMapBaseUrl` wip implementation

sanex3339 8 years ago
parent
commit
bc1d4ef609

+ 13 - 1
README.md

@@ -225,7 +225,19 @@ Enables source map generation for obfuscated code.
 ### `sourceMapBaseUrl`
 Type: `string` Default: ``
 
-Inserts custom Url for source map
+Adds base url to the source map import url when `sourceMapMode: 'separate'`.
+ 
+##### :warning: this option designed for CLI usage
+
+CLI example:
+```
+javascript-obfuscator input.js --output out.js --sourceMap true --sourceMapBaseUrl 'http://localhost:9000'
+```
+
+Result import: 
+```
+//# sourceMappingURL=http://localhost:9000/out.js.map
+```
 
 ### `sourceMapMode`
 Type: `string` Default: `separate`

+ 14 - 7
dist/index.js

@@ -207,6 +207,14 @@ var Utils = function () {
         value: function isInteger(number) {
             return number % 1 === 0;
         }
+    }, {
+        key: 'normalizeUrl',
+        value: function normalizeUrl(url) {
+            if (!url.endsWith('/')) {
+                url += '/';
+            }
+            return url;
+        }
     }, {
         key: 'strEnumify',
         value: function strEnumify(obj) {
@@ -934,8 +942,8 @@ var JavaScriptObfuscatorInternal = function () {
     _createClass(JavaScriptObfuscatorInternal, [{
         key: 'getObfuscationResult',
         value: function getObfuscationResult() {
-            if (this.options.sourceMapBaseUrl) {
-                this.setSourceMapUrl(this.options.sourceMapBaseUrl);
+            if (this.sourceMapUrl) {
+                this.sourceMapUrl = this.options.sourceMapBaseUrl + this.sourceMapUrl;
             }
             return new SourceMapCorrector_1.SourceMapCorrector(new ObfuscationResult_1.ObfuscationResult(this.generatorOutput.code, this.generatorOutput.map), this.sourceMapUrl, this.options.sourceMapMode).correct();
         }
@@ -1545,7 +1553,7 @@ var JavaScriptObfuscatorCLI = function () {
         value: function configureCommands() {
             this.commands = new commander.Command().version(JavaScriptObfuscatorCLI.getBuildVersion(), '-v, --version').usage('<inputPath> [options]').option('-o, --output <path>', 'Output path for obfuscated code').option('--compact <boolean>', 'Disable one line output code compacting', JavaScriptObfuscatorCLI.parseBoolean).option('--debugProtection <boolean>', 'Disable browser Debug panel (can cause DevTools enabled browser freeze)', JavaScriptObfuscatorCLI.parseBoolean).option('--debugProtectionInterval <boolean>', 'Disable browser Debug panel even after page was loaded (can cause DevTools enabled browser freeze)', JavaScriptObfuscatorCLI.parseBoolean).option('--disableConsoleOutput <boolean>', 'Allow console.log, console.info, console.error and console.warn messages output into browser console', JavaScriptObfuscatorCLI.parseBoolean).option('--encodeUnicodeLiterals <boolean>', 'All literals in Unicode array become encoded in Base64 (this option can slightly slow down your code speed)', JavaScriptObfuscatorCLI.parseBoolean).option('--reservedNames <list>', 'Disable obfuscation of variable names, function names and names of function parameters that match the passed RegExp patterns (comma separated)', function (val) {
                 return val.split(',');
-            }).option('--rotateUnicodeArray <boolean>', 'Disable rotation of unicode array values during obfuscation', JavaScriptObfuscatorCLI.parseBoolean).option('--selfDefending <boolean>', 'Disables self-defending for obfuscated code', JavaScriptObfuscatorCLI.parseBoolean).option('--sourceMap <boolean>', 'Enables source map generation', JavaScriptObfuscatorCLI.parseBoolean).option('--sourceMapBaseUrl <boolean>', 'Inserts custom Url for source map').option('--sourceMapMode <string> [inline, separate]', 'Specify source map output mode', JavaScriptObfuscatorCLI.parseSourceMapMode).option('--unicodeArray <boolean>', 'Disables gathering of all literal strings into an array and replacing every literal string with an array call', JavaScriptObfuscatorCLI.parseBoolean).option('--unicodeArrayThreshold <number>', 'The probability that the literal string will be inserted into unicodeArray (Default: 0.8, Min: 0, Max: 1)', parseFloat).option('--wrapUnicodeArrayCalls <boolean>', 'Disables usage of special access function instead of direct array call', JavaScriptObfuscatorCLI.parseBoolean).option('--domainLock <list>', 'Blocks the execution of the code in domains that do not match the passed RegExp patterns (comma separated)', function (val) {
+            }).option('--rotateUnicodeArray <boolean>', 'Disable rotation of unicode array values during obfuscation', JavaScriptObfuscatorCLI.parseBoolean).option('--selfDefending <boolean>', 'Disables self-defending for obfuscated code', JavaScriptObfuscatorCLI.parseBoolean).option('--sourceMap <boolean>', 'Enables source map generation', JavaScriptObfuscatorCLI.parseBoolean).option('--sourceMapBaseUrl <boolean>', 'Adds base url to the source map import url when `--sourceMapMode=separate`').option('--sourceMapMode <string> [inline, separate]', 'Specify source map output mode', JavaScriptObfuscatorCLI.parseSourceMapMode).option('--unicodeArray <boolean>', 'Disables gathering of all literal strings into an array and replacing every literal string with an array call', JavaScriptObfuscatorCLI.parseBoolean).option('--unicodeArrayThreshold <number>', 'The probability that the literal string will be inserted into unicodeArray (Default: 0.8, Min: 0, Max: 1)', parseFloat).option('--wrapUnicodeArrayCalls <boolean>', 'Disables usage of special access function instead of direct array call', JavaScriptObfuscatorCLI.parseBoolean).option('--domainLock <list>', 'Blocks the execution of the code in domains that do not match the passed RegExp patterns (comma separated)', function (val) {
                 return val.split(',');
             }).parse(this.rawArguments);
             this.commands.on('--help', function () {
@@ -3347,7 +3355,9 @@ var OptionsNormalizer = function () {
         key: "sourceMapBaseUrl",
         value: function sourceMapBaseUrl(options) {
             if (options.sourceMapBaseUrl) {
-                Object.assign(options, OptionsNormalizer.SOURCE_MAP_BASE_URL_OPTIONS);
+                Object.assign(options, {
+                    sourceMapBaseUrl: Utils_1.Utils.normalizeUrl(options.sourceMapBaseUrl)
+                });
             }
             return options;
         }
@@ -3387,9 +3397,6 @@ OptionsNormalizer.SELF_DEFENDING_OPTIONS = {
     compact: true,
     selfDefending: true
 };
-OptionsNormalizer.SOURCE_MAP_BASE_URL_OPTIONS = {
-    sourceMapMode: 'separate'
-};
 OptionsNormalizer.normalizerRules = [OptionsNormalizer.domainLockRule, OptionsNormalizer.unicodeArrayRule, OptionsNormalizer.unicodeArrayThresholdRule, OptionsNormalizer.encodeUnicodeLiteralsRule, OptionsNormalizer.sourceMapBaseUrl, OptionsNormalizer.selfDefendingRule];
 exports.OptionsNormalizer = OptionsNormalizer;
 

+ 2 - 2
src/JavaScriptObfuscatorInternal.ts

@@ -84,8 +84,8 @@ export class JavaScriptObfuscatorInternal {
      * @returns {IObfuscationResult}
      */
     public getObfuscationResult (): IObfuscationResult {
-        if (this.options.sourceMapBaseUrl) {
-            this.setSourceMapUrl(this.options.sourceMapBaseUrl);
+        if (this.sourceMapUrl) {
+            this.sourceMapUrl = this.options.sourceMapBaseUrl + this.sourceMapUrl;
         }
 
         return new SourceMapCorrector(

+ 12 - 0
src/Utils.ts

@@ -152,6 +152,18 @@ export class Utils {
         return number % 1 === 0;
     }
 
+    /**
+     * @param url
+     * @returns {string}
+     */
+    public static normalizeUrl (url: string): string {
+        if (!url.endsWith('/')) {
+            url += '/';
+        }
+
+        return url;
+    }
+
     /**
      * @param obj
      * @returns {T}

+ 1 - 1
src/cli/JavaScriptObfuscatorCLI.ts

@@ -132,7 +132,7 @@ export class JavaScriptObfuscatorCLI {
             .option('--rotateUnicodeArray <boolean>', 'Disable rotation of unicode array values during obfuscation', JavaScriptObfuscatorCLI.parseBoolean)
             .option('--selfDefending <boolean>', 'Disables self-defending for obfuscated code', JavaScriptObfuscatorCLI.parseBoolean)
             .option('--sourceMap <boolean>', 'Enables source map generation', JavaScriptObfuscatorCLI.parseBoolean)
-            .option('--sourceMapBaseUrl <boolean>', 'Inserts custom Url for source map')
+            .option('--sourceMapBaseUrl <boolean>', 'Adds base url to the source map import url when `--sourceMapMode=separate`')
             .option(
                 '--sourceMapMode <string> [inline, separate]',
                 'Specify source map output mode',

+ 3 - 8
src/options/OptionsNormalizer.ts

@@ -33,13 +33,6 @@ export class OptionsNormalizer {
         selfDefending: true
     };
 
-    /**
-     * @type {IObfuscatorOptions}
-     */
-    private static SOURCE_MAP_BASE_URL_OPTIONS: IObfuscatorOptions = {
-        sourceMapMode: 'separate'
-    };
-
     /**
      * @type {TOptionsNormalizerRule[]}
      */
@@ -116,7 +109,9 @@ export class OptionsNormalizer {
      */
     private static sourceMapBaseUrl (options: IOptions): IOptions {
         if (options.sourceMapBaseUrl) {
-            Object.assign(options, OptionsNormalizer.SOURCE_MAP_BASE_URL_OPTIONS);
+            Object.assign(options, {
+                sourceMapBaseUrl: Utils.normalizeUrl(options.sourceMapBaseUrl)
+            });
         }
 
         return options;

+ 7 - 6
test/functional-tests/JavaScriptObfuscatorInternal.spec.ts

@@ -10,10 +10,9 @@ describe('JavaScriptObfuscatorInternal', () => {
     describe(`setSourceMapUrl (url: string)`, () => {
         let javaScriptObfuscator: JavaScriptObfuscatorInternal,
             obfuscationResult: IObfuscationResult,
-            sourceMapUrl: string;
+            sourceMapUrl: string = 'test.map.js';
 
         it('should link obfuscated code with source map', () => {
-            sourceMapUrl = 'test.map.js';
             javaScriptObfuscator = new JavaScriptObfuscatorInternal(
                 `var test = 1;`,
                 Object.assign({}, NO_CUSTOM_NODES_PRESET, {
@@ -33,23 +32,25 @@ describe('JavaScriptObfuscatorInternal', () => {
             assert.isOk(JSON.parse(obfuscationResult.getSourceMap()).mappings);
         });
 
-        it('should properly add source map import to the obfuscated code if `sourceMapBaseUrl` is set', () => {
-            sourceMapUrl = 'http://localhost:9000/';
+        it('should properly add base url to source map import inside obfuscated code if `sourceMapBaseUrl` is set', () => {
+            let sourceMapBaseUrl: string = 'http://localhost:9000';
+
             javaScriptObfuscator = new JavaScriptObfuscatorInternal(
                 `var test = 1;`,
                 Object.assign({}, NO_CUSTOM_NODES_PRESET, {
                     sourceMap: true,
-                    sourceMapBaseUrl: sourceMapUrl
+                    sourceMapBaseUrl: sourceMapBaseUrl
                 })
             );
 
             javaScriptObfuscator.obfuscate();
+            javaScriptObfuscator.setSourceMapUrl(sourceMapUrl);
 
             obfuscationResult = javaScriptObfuscator.getObfuscationResult();
 
             assert.match(
                 obfuscationResult.getObfuscatedCode(),
-                new RegExp(`sourceMappingURL=${sourceMapUrl}$`))
+                new RegExp(`sourceMappingURL=${sourceMapBaseUrl}/${sourceMapUrl}$`))
             ;
             assert.isOk(JSON.parse(obfuscationResult.getSourceMap()).mappings);
         });

+ 1 - 3
test/unit-tests/OptionsNormalizer.spec.ts

@@ -31,7 +31,6 @@ describe('OptionsNormalizer', () => {
             optionsPreset2 = Object.assign({}, DEFAULT_PRESET, {
                 rotateUnicodeArray: true,
                 sourceMapBaseUrl: 'http://localhost:9000',
-                sourceMapMode: 'inline',
                 unicodeArray: true,
                 unicodeArrayThreshold: 0,
                 wrapUnicodeArrayCalls: true
@@ -52,8 +51,7 @@ describe('OptionsNormalizer', () => {
             });
             expectedOptionsPreset2 = Object.assign({}, DEFAULT_PRESET, {
                 rotateUnicodeArray: false,
-                sourceMapBaseUrl: 'http://localhost:9000',
-                sourceMapMode: 'separate',
+                sourceMapBaseUrl: 'http://localhost:9000/',
                 unicodeArray: false,
                 unicodeArrayThreshold: 0,
                 wrapUnicodeArrayCalls: false

+ 6 - 0
test/unit-tests/Utils.spec.ts

@@ -75,6 +75,12 @@ describe('Utils', () => {
         });
     });
 
+    describe('normalizeUrl (url: string): string', () => {
+        it('should normalize given url', () => {
+            assert.equal(Utils.normalizeUrl('http://localhost:9000'), 'http://localhost:9000/');
+        });
+    });
+
     describe('stringToJSFuck (string: string): string', () => {
         let expected: string = `${JSFuck.s} + ${JSFuck.t} + ${JSFuck.r} + ${JSFuck.i} + ${JSFuck.n} + ${JSFuck.g}`;