瀏覽代碼

Fixed wrong names generation for the custom nodes

sanex3339 5 年之前
父節點
當前提交
dd7c1df9f9

文件差異過大導致無法顯示
+ 0 - 0
dist/index.browser.js


文件差異過大導致無法顯示
+ 0 - 0
dist/index.cli.js


文件差異過大導致無法顯示
+ 0 - 0
dist/index.js


+ 3 - 3
package.json

@@ -69,9 +69,9 @@
     "eslint-plugin-jsdoc": "21.0.0",
     "eslint-plugin-no-null": "1.0.2",
     "eslint-plugin-prefer-arrow": "1.1.7",
-    "eslint-plugin-unicorn": "16.1.0",
+    "eslint-plugin-unicorn": "16.1.1",
     "fork-ts-checker-notifier-webpack-plugin": "2.0.0",
-    "fork-ts-checker-webpack-plugin": "4.0.3",
+    "fork-ts-checker-webpack-plugin": "4.0.4",
     "mocha": "7.0.1",
     "nyc": "15.0.0",
     "pjson": "1.0.9",
@@ -81,7 +81,7 @@
     "threads": "1.1.0",
     "ts-loader": "6.2.1",
     "ts-node": "6.1.0",
-    "typescript": "3.8.0-beta",
+    "typescript": "3.8.1-rc",
     "webpack": "4.41.6",
     "webpack-cli": "3.3.11",
     "webpack-node-externals": "1.7.2"

+ 1 - 21
src/custom-nodes/CustomNodeObfuscator.ts

@@ -7,8 +7,6 @@ import { ICustomNodeObfuscator } from '../interfaces/custom-nodes/ICustomNodeObf
 import { IOptions } from '../interfaces/options/IOptions';
 import { IRandomGenerator } from '../interfaces/utils/IRandomGenerator';
 
-import { IdentifierNamesGenerator } from '../enums/generators/identifier-names-generators/IdentifierNamesGenerator';
-
 import { NO_ADDITIONAL_NODES_PRESET } from '../options/presets/NoCustomNodes';
 
 import { JavaScriptObfuscator } from '../JavaScriptObfuscatorFacade';
@@ -43,24 +41,8 @@ export class CustomNodeObfuscator implements ICustomNodeObfuscator {
      * @returns {string}
      */
     public obfuscateTemplate (template: string, additionalOptions: TInputOptions = {}): string {
-        /**
-         * During the first pass we should rename all identifiers to a random one
-         */
-        const firstPassObfuscatedCode = JavaScriptObfuscator.obfuscate(
+        return JavaScriptObfuscator.obfuscate(
             template,
-            {
-                ...NO_ADDITIONAL_NODES_PRESET,
-                identifierNamesGenerator: IdentifierNamesGenerator.HexadecimalIdentifierNamesGenerator,
-                seed: 1
-            }
-        ).getObfuscatedCode();
-
-        /**
-         * During the seconds pass we should obfuscate template to the same format as the main code
-         * Also, we should add additional transformations that depends on the custom node
-         */
-        const secondPassObfuscatedCode = JavaScriptObfuscator.obfuscate(
-            firstPassObfuscatedCode,
             {
                 ...NO_ADDITIONAL_NODES_PRESET,
                 identifierNamesGenerator: this.options.identifierNamesGenerator,
@@ -69,7 +51,5 @@ export class CustomNodeObfuscator implements ICustomNodeObfuscator {
                 ...additionalOptions
             }
         ).getObfuscatedCode();
-
-        return secondPassObfuscatedCode;
     }
 }

+ 1 - 1
src/custom-nodes/domain-lock-nodes/DomainLockNode.ts

@@ -90,7 +90,7 @@ export class DomainLockNode extends AbstractCustomNode {
             : GlobalVariableNoEvalTemplate();
 
         return this.customNodeFormatter.formatTemplate(DomainLockNodeTemplate(), {
-            domainLockFunctionName: this.randomGenerator.getRandomString(5),
+            domainLockFunctionName: this.identifierNamesGenerator.generate(),
             diff,
             domains: hiddenDomainsString,
             globalVariableTemplate,

+ 1 - 1
src/custom-nodes/domain-lock-nodes/group/DomainLockCustomNodeGroup.ts

@@ -91,7 +91,7 @@ export class DomainLockCustomNodeGroup extends AbstractCustomNodeGroup {
             return;
         }
 
-        const callsControllerFunctionName: string = this.randomGenerator.getRandomString(5);
+        const callsControllerFunctionName: string = this.identifierNamesGenerator.generate();
 
         const domainLockNode: ICustomNode<TInitialData<DomainLockNode>> =
             this.customNodeFactory(CustomNode.DomainLockNode);

+ 6 - 3
src/custom-nodes/object-expression-keys-transformer-nodes/ObjectExpressionVariableDeclarationHostNode.ts

@@ -14,6 +14,7 @@ import { IRandomGenerator } from '../../interfaces/utils/IRandomGenerator';
 
 import { AbstractCustomNode } from '../AbstractCustomNode';
 import { NodeFactory } from '../../node/NodeFactory';
+import { NodeGuards } from '../../node/NodeGuards';
 
 @injectable()
 export class ObjectExpressionVariableDeclarationHostNode extends AbstractCustomNode {
@@ -60,12 +61,14 @@ export class ObjectExpressionVariableDeclarationHostNode extends AbstractCustomN
      * @returns {TStatement[]}
      */
     protected getNodeStructure (nodeTemplate: string): TStatement[] {
+        const variableDeclarationName: string = NodeGuards.isProgramNode(this.lexicalScopeNode)
+            ? this.identifierNamesGenerator.generate()
+            : this.identifierNamesGenerator.generateForLexicalScope(this.lexicalScopeNode);
+
         const structure: TStatement = NodeFactory.variableDeclarationNode(
             [
                 NodeFactory.variableDeclaratorNode(
-                    NodeFactory.identifierNode(
-                        this.identifierNamesGenerator.generateForLexicalScope(this.lexicalScopeNode)
-                    ),
+                    NodeFactory.identifierNode(variableDeclarationName),
                     NodeFactory.objectExpressionNode(this.properties)
                 )
             ],

+ 1 - 1
src/custom-nodes/self-defending-nodes/SelfDefendingUnicodeNode.ts

@@ -79,7 +79,7 @@ export class SelfDefendingUnicodeNode extends AbstractCustomNode {
     protected getNodeTemplate (): string {
         return this.customNodeObfuscator.obfuscateTemplate(
             this.customNodeFormatter.formatTemplate(SelfDefendingTemplate(this.escapeSequenceEncoder), {
-                selfDefendingFunctionName: this.randomGenerator.getRandomString(5),
+                selfDefendingFunctionName: this.identifierNamesGenerator.generate(),
                 singleNodeCallControllerFunctionName: this.callsControllerFunctionName
             }),
             {

+ 1 - 1
src/custom-nodes/self-defending-nodes/group/SelfDefendingCustomNodeGroup.ts

@@ -91,7 +91,7 @@ export class SelfDefendingCustomNodeGroup extends AbstractCustomNodeGroup {
             return;
         }
 
-        const callsControllerFunctionName: string = this.randomGenerator.getRandomString(5);
+        const callsControllerFunctionName: string = this.identifierNamesGenerator.generate();
 
         const selfDefendingUnicodeNode: ICustomNode<TInitialData<SelfDefendingUnicodeNode>> =
             this.customNodeFactory(CustomNode.SelfDefendingUnicodeNode);

+ 2 - 0
src/interfaces/utils/IRandomGenerator.ts

@@ -1,3 +1,5 @@
+// eslint-disable-next-line @typescript-eslint/ban-ts-comment
+// @ts-ignore
 import type * as Chance from 'chance';
 
 export interface IRandomGenerator {

+ 7 - 4
test/dev/dev.ts

@@ -7,16 +7,19 @@ import { NO_ADDITIONAL_NODES_PRESET } from '../../src/options/presets/NoCustomNo
 
     let obfuscatedCode: string = JavaScriptObfuscator.obfuscate(
         `
-            function foo () {
+            const a = '123';
+            const b = '234';
+            const c = '345';
             
-            }
+            console.log(a, b, c);
         `,
         {
             ...NO_ADDITIONAL_NODES_PRESET,
             compact: false,
             identifierNamesGenerator: 'mangled',
-            renameGlobals: true,
-            reservedNames: ['a'],
+            selfDefending: true,
+            stringArray: true,
+            stringArrayThreshold: 1,
             log: true
         }
     ).getObfuscatedCode();

+ 67 - 0
test/functional-tests/generators/identifier-names-generators/mangled-identifier-names-generator/MangledIdentifierNamesGenerator.spec.ts

@@ -299,5 +299,72 @@ describe('MangledIdentifierNamesGenerator', () => {
                 });
             });
         });
+
+        describe('Variant #3: Should generate different names set for different lexical scopes: nested functions', () => {
+            describe('Variant #1: `renameGlobals` option is disabled', () => {
+                const regExp: RegExp = new RegExp(`` +
+                    `var foo *= *'abc'; *` +
+                    `function bar *\\(a, *b\\) *{` +
+                        `function c *\\(e, *f\\) *{ *} *` +
+                        `function d *\\(e, *f\\) *{ *} *` +
+                    `} *` +
+                    `function baz *\\(a, *b\\) *{` +
+                        `function c *\\(e, *f\\) *{ *} *` +
+                        `function d *\\(e, *f\\) *{ *} *` +
+                    `}` +
+                ``);
+
+                let obfuscatedCode: string;
+
+                before(() => {
+                    const code: string = readFileAsString(__dirname + '/fixtures/lexical-block-scope-identifiers-2.js');
+
+                    obfuscatedCode = JavaScriptObfuscator.obfuscate(
+                        code,
+                        {
+                            ...NO_ADDITIONAL_NODES_PRESET,
+                            identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator
+                        }
+                    ).getObfuscatedCode();
+                });
+
+                it('Match #1: should generate valid identifier names', () => {
+                    assert.match(obfuscatedCode, regExp);
+                });
+            });
+
+            describe('Variant #2: `renameGlobals` option is enabled', () => {
+                const regExp: RegExp = new RegExp(`` +
+                    `var a *= *'abc'; *` +
+                    `function b *\\(d, *e\\) *{` +
+                        `function f *\\(h, *i\\) *{ *} *` +
+                        `function g *\\(h, *i\\) *{ *} *` +
+                    `} *` +
+                    `function c *\\(d, *e\\) *{` +
+                        `function f *\\(h, *i\\) *{ *} *` +
+                        `function g *\\(h, *i\\) *{ *} *` +
+                    `}` +
+                    ``);
+
+                let obfuscatedCode: string;
+
+                before(() => {
+                    const code: string = readFileAsString(__dirname + '/fixtures/lexical-block-scope-identifiers-2.js');
+
+                    obfuscatedCode = JavaScriptObfuscator.obfuscate(
+                        code,
+                        {
+                            ...NO_ADDITIONAL_NODES_PRESET,
+                            identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator,
+                            renameGlobals: true
+                        }
+                    ).getObfuscatedCode();
+                });
+
+                it('Match #1: should generate valid identifier names', () => {
+                    assert.match(obfuscatedCode, regExp);
+                });
+            });
+        });
     });
 });

+ 9 - 0
test/functional-tests/generators/identifier-names-generators/mangled-identifier-names-generator/fixtures/lexical-block-scope-identifiers-2.js

@@ -0,0 +1,9 @@
+var foo = 'abc';
+function bar (hawk, bark) {
+    function pig (dog, cat) {}
+    function bird (duck, bear) {}
+}
+function baz (eagle, cow) {
+    function rabbit (mouse, lion) {}
+    function bird (tiger, kiwi) {}
+}

+ 2 - 2
test/functional-tests/node-transformers/preparing-transformers/variable-preserve-transformer/VariablePreserveTransformer.spec.ts

@@ -98,8 +98,8 @@ describe('VariablePreserveTransformer', () => {
         });
 
         describe('Variant #2: `renameGlobals` option is enabled', () => {
-            const transformObjectKeysNameRegExp: RegExp = /const b *= *{};/;
-            const identifierNameRegExp: RegExp = /const c *= *b;/;
+            const transformObjectKeysNameRegExp: RegExp = /const c *= *{};/;
+            const identifierNameRegExp: RegExp = /const d *= *c;/;
 
             let obfuscatedCode: string;
 

+ 68 - 63
test/runtime-tests/JavaScriptObfuscatorRuntime.spec.ts

@@ -70,70 +70,75 @@ describe('JavaScriptObfuscator runtime eval', function () {
                     }
                 ).getObfuscatedCode();
 
-                assert.equal(
-                    eval(`
-                ${getEnvironmentCode()}
-                ${obfuscatedCode}
-                const code = generate({
-                    "type": "Program",
-                    "body": [
-                        {
-                            "type": "FunctionDeclaration",
-                            "id": {
-                                "type": "Identifier",
-                                "name": "test",
-                                "range": [
-                                    9,
-                                    13
-                                ]
-                            },
-                            "params": [],
-                            "body": {
-                                "type": "BlockStatement",
-                                "body": [
-                                    {
-                                        "type": "ReturnStatement",
-                                        "argument": {
-                                            "type": "Literal",
-                                            "value": "foo",
-                                            "raw": "'foo'",
-                                            "range": [
-                                                30,
-                                                35
-                                            ]
-                                        },
+                let evaluationResult: string;
+
+                try {
+                    evaluationResult = eval(`
+                        ${getEnvironmentCode()}
+                        ${obfuscatedCode}
+                        const code = generate({
+                            "type": "Program",
+                            "body": [
+                                {
+                                    "type": "FunctionDeclaration",
+                                    "id": {
+                                        "type": "Identifier",
+                                        "name": "test",
                                         "range": [
-                                            23,
-                                            36
+                                            9,
+                                            13
                                         ]
-                                    }
-                                ],
-                                "range": [
-                                    17,
-                                    38
-                                ]
-                            },
-                            "generator": false,
-                            "expression": false,
-                            "async": false,
+                                    },
+                                    "params": [],
+                                    "body": {
+                                        "type": "BlockStatement",
+                                        "body": [
+                                            {
+                                                "type": "ReturnStatement",
+                                                "argument": {
+                                                    "type": "Literal",
+                                                    "value": "foo",
+                                                    "raw": "'foo'",
+                                                    "range": [
+                                                        30,
+                                                        35
+                                                    ]
+                                                },
+                                                "range": [
+                                                    23,
+                                                    36
+                                                ]
+                                            }
+                                        ],
+                                        "range": [
+                                            17,
+                                            38
+                                        ]
+                                    },
+                                    "generator": false,
+                                    "expression": false,
+                                    "async": false,
+                                    "range": [
+                                        0,
+                                        38
+                                    ]
+                                }
+                            ],
+                            "sourceType": "module",
                             "range": [
                                 0,
                                 38
-                            ]
-                        }
-                    ],
-                    "sourceType": "module",
-                    "range": [
-                        0,
-                        38
-                    ],
-                    "comments": []
-                });
-                
-                eval(\`\${code} test();\`);
-            `),
-                    'foo'
-                );
+                            ],
+                            "comments": []
+                        });
+                        
+                        eval(\`\${code} test();\`);
+                    `)
+                } catch (e) {
+                    throw new Error(`Evaluation error: ${e.message}. Code: ${obfuscatedCode}`);
+                }
+
+                assert.equal(evaluationResult, 'foo');
             });
         });
 
@@ -151,10 +156,10 @@ describe('JavaScriptObfuscator runtime eval', function () {
 
                 assert.equal(
                     eval(`
-                    ${getEnvironmentCode()}
-                    ${obfuscatedCode}
-                    sha256('test');
-                `),
+                        ${getEnvironmentCode()}
+                        ${obfuscatedCode}
+                        sha256('test');
+                    `),
                     '9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08'
                 );
             });

+ 12 - 12
yarn.lock

@@ -1791,10 +1791,10 @@ [email protected]:
   resolved "https://registry.yarnpkg.com/eslint-plugin-prefer-arrow/-/eslint-plugin-prefer-arrow-1.1.7.tgz#4534dd8d2e519cd579a951f95802137365d524a2"
   integrity sha512-epsA4g804mRovlOHSbeO1xxW7REGeUjULRME9MJTJDOVscNIA01AkR66TP4cmHDfD+w72EQ9cPhf37MbZiFI2w==
 
[email protected].0:
-  version "16.1.0"
-  resolved "https://registry.yarnpkg.com/eslint-plugin-unicorn/-/eslint-plugin-unicorn-16.1.0.tgz#7af9f2d056c0997776a112c66c6c4f02792bdc56"
-  integrity sha512-aZbnl0TGXpQngzY5Ou0sj7YxTZYxfdWKhyLV/MWBeNQ2gGWMiq7CoJApZQJq5al2zKkep3CIWI7RFmUWnKSBxg==
[email protected].1:
+  version "16.1.1"
+  resolved "https://registry.yarnpkg.com/eslint-plugin-unicorn/-/eslint-plugin-unicorn-16.1.1.tgz#012c598d71914ef30f5d386dd85110e59f2ef999"
+  integrity sha512-IMxCsntb0T8s660Irc40gtzXtxuXHcOn36G9G8OYKfiseBD/kNrA1cNJhsJ0xQteDASGrFwqdzBsYEkUvczhOA==
   dependencies:
     ci-info "^2.0.0"
     clean-regexp "^1.0.0"
@@ -2200,10 +2200,10 @@ [email protected]:
   dependencies:
     node-notifier "^6.0.0"
 
[email protected].3:
-  version "4.0.3"
-  resolved "https://registry.yarnpkg.com/fork-ts-checker-webpack-plugin/-/fork-ts-checker-webpack-plugin-4.0.3.tgz#958f4e4ec3e7fd9d4ad5a50a4442abce77dca19a"
-  integrity sha512-5hGeMYKg817Hp6rvdc2EOS/T/Cq0JW9LLJDZtVUPlNIojIuP7YbOAdrHEk4Irw1097YQUr56kWIiYhqNPzfNzQ==
[email protected].4:
+  version "4.0.4"
+  resolved "https://registry.yarnpkg.com/fork-ts-checker-webpack-plugin/-/fork-ts-checker-webpack-plugin-4.0.4.tgz#ba1be68d63dcf509f6d1b08fb8e19efb6d7e8a96"
+  integrity sha512-6IEqHH6s+tv5sho5d3dn7dfcnbjKHwfqL74kRfpAP2e8MCHuMh5ixtYrbdfPO4Zat3S5gwULOoVArjK3HMwNdA==
   dependencies:
     babel-code-frame "^6.22.0"
     chalk "^2.4.1"
@@ -5223,10 +5223,10 @@ typedarray@^0.0.6:
   resolved "https://registry.yarnpkg.com/typedarray/-/typedarray-0.0.6.tgz#867ac74e3864187b1d3d47d996a78ec5c8830777"
   integrity sha1-hnrHTjhkGHsdPUfZlqeOxciDB3c=
 
[email protected].0-beta:
-  version "3.8.0-beta"
-  resolved "https://registry.yarnpkg.com/typescript/-/typescript-3.8.0-beta.tgz#acdcaf9f24c7e20b1ff0a6329d1e8d63691e2e13"
-  integrity sha512-mQEmQUJg0CQBhf/GSVnGscKv/jrKsrLxE01AhdjYmBNoXX2Iah3i38ufxXByXacK6Fc5Nr9oMz7MjpjgddiknA==
[email protected].1-rc:
+  version "3.8.1-rc"
+  resolved "https://registry.yarnpkg.com/typescript/-/typescript-3.8.1-rc.tgz#f94333c14da70927ccd887be2e91be652a9a09f6"
+  integrity sha512-aOIe066DyZn2uYIiND6fXMUUJ70nxwu/lKhA92QuQzXyC86fr0ywo1qvO8l2m0EnDcfjprYPuFRgNgDj7U2GlQ==
 
 union-value@^1.0.0:
   version "1.0.1"

部分文件因文件數量過多而無法顯示