Browse Source

Additional improvements of variables preserving

sanex3339 5 năm trước cách đây
mục cha
commit
78722782de
21 tập tin đã thay đổi với 171 bổ sung39 xóa
  1. 0 0
      dist/index.browser.js
  2. 0 0
      dist/index.cli.js
  3. 0 0
      dist/index.js
  4. 12 0
      src/custom-nodes/AbstractCustomNode.ts
  5. 6 1
      src/custom-nodes/string-array-nodes/StringArrayCallsWrapper.ts
  6. 15 1
      src/generators/identifier-names-generators/AbstractIdentifierNamesGenerator.ts
  7. 5 2
      src/generators/identifier-names-generators/DictionaryIdentifierNamesGenerator.ts
  8. 5 2
      src/generators/identifier-names-generators/MangledIdentifierNamesGenerator.ts
  9. 11 1
      src/interfaces/generators/identifier-names-generators/IIdentifierNamesGenerator.ts
  10. 6 1
      src/interfaces/node-transformers/obfuscating-transformers/obfuscating-replacers/IIdentifierObfuscatingReplacer.ts
  11. 11 2
      src/node-transformers/obfuscating-transformers/obfuscating-replacers/identifier-obfuscating-replacers/BaseIdentifierObfuscatingReplacer.ts
  12. 33 3
      src/node-transformers/preparing-transformers/VariablePreserveTransformer.ts
  13. 34 0
      src/node/NodeGuards.ts
  14. 4 8
      src/storages/string-array/StringArrayStorage.ts
  15. 14 3
      test/dev/dev.ts
  16. 1 1
      test/functional-tests/node-transformers/obfuscating-transformers/literal-transformer/LiteralTransformer.spec.ts
  17. 3 3
      test/functional-tests/node-transformers/obfuscating-transformers/scope-identifiers-transformer/class-declaration/ClassDeclaration.spec.ts
  18. 2 2
      test/functional-tests/node-transformers/obfuscating-transformers/scope-identifiers-transformer/function-declaration/FunctionDeclaration.spec.ts
  19. 6 6
      test/functional-tests/node-transformers/obfuscating-transformers/scope-identifiers-transformer/variable-declaration/VariableDeclaration.spec.ts
  20. 1 1
      test/unit-tests/generators/identifier-names-generators/DictionarylIdentifierNamesGenerator.spec.ts
  21. 2 2
      test/unit-tests/generators/identifier-names-generators/MangledlIdentifierNamesGenerator.spec.ts

Những thai đổi đã bị hủy bỏ vì nó quá lớn
+ 0 - 0
dist/index.browser.js


Những thai đổi đã bị hủy bỏ vì nó quá lớn
+ 0 - 0
dist/index.cli.js


Những thai đổi đã bị hủy bỏ vì nó quá lớn
+ 0 - 0
dist/index.js


+ 12 - 0
src/custom-nodes/AbstractCustomNode.ts

@@ -100,6 +100,18 @@ export abstract class AbstractCustomNode <
         return '';
     }
 
+    /**
+     * @param {string[]} additionalNames
+     * @returns {string[]}
+     */
+    protected getPreservedNames (additionalNames: string[]): string[] {
+        return Array.from(new Set([
+            ...Array.from(this.identifierNamesGenerator.getPreservedNames().values()),
+            ...additionalNames
+        ]).values())
+        .map((preservedName: string) => `^${preservedName}$`);
+    }
+
     /**
      * @param {TInitialData} args
      */

+ 6 - 1
src/custom-nodes/string-array-nodes/StringArrayCallsWrapper.ts

@@ -93,6 +93,8 @@ export class StringArrayCallsWrapper extends AbstractCustomNode {
     protected getNodeTemplate (): string {
         const decodeNodeTemplate: string = this.getDecodeStringArrayTemplate();
 
+        const preservedNames: string[] = this.getPreservedNames([this.stringArrayName]);
+
         return JavaScriptObfuscator.obfuscate(
             this.customNodeFormatter.formatTemplate(StringArrayCallsWrapperTemplate(), {
                 decodeNodeTemplate,
@@ -103,6 +105,9 @@ export class StringArrayCallsWrapper extends AbstractCustomNode {
                 ...NO_ADDITIONAL_NODES_PRESET,
                 identifierNamesGenerator: this.options.identifierNamesGenerator,
                 identifiersDictionary: this.options.identifiersDictionary,
+                reservedNames: [
+                    ...preservedNames
+                ],
                 seed: this.randomGenerator.getRawSeed()
             }
         ).getObfuscatedCode();
@@ -139,8 +144,8 @@ export class StringArrayCallsWrapper extends AbstractCustomNode {
                     StringArrayRc4DecodeNodeTemplate(this.randomGenerator),
                     {
                         atobPolyfill,
-                        rc4Polyfill: Rc4Template(),
                         selfDefendingCode,
+                        rc4Polyfill: Rc4Template(),
                         stringArrayCallsWrapperName: this.stringArrayCallsWrapperName
                     }
                 );

+ 15 - 1
src/generators/identifier-names-generators/AbstractIdentifierNamesGenerator.ts

@@ -41,11 +41,25 @@ export abstract class AbstractIdentifierNamesGenerator implements IIdentifierNam
         this.options = options;
     }
 
+    /**
+     * @returns {Set<string>}
+     */
+    public getPreservedNames (): Set<string> {
+        return this.preservedNamesSet;
+    }
+
+    /**
+     * @param {string} name
+     */
+    public preserveName (name: string): void {
+        this.preservedNamesSet.add(name);
+    }
+
     /**
      * @param {string} name
      * @param {TNodeWithLexicalScope} lexicalScopeNode
      */
-    public preserveName (name: string, lexicalScopeNode: TNodeWithLexicalScope): void {
+    public preserveNameForLexicalScope (name: string, lexicalScopeNode: TNodeWithLexicalScope): void {
         this.preservedNamesSet.add(name);
 
         const preservedNamesForLexicalScopeSet: Set<string> =

+ 5 - 2
src/generators/identifier-names-generators/DictionaryIdentifierNamesGenerator.ts

@@ -110,11 +110,14 @@ export class DictionaryIdentifierNamesGenerator extends AbstractIdentifierNamesG
      */
     public generateWithPrefix (): string {
         const prefix: string = this.options.identifiersPrefix ?
-            `${this.options.identifiersPrefix}_`
+            `${this.options.identifiersPrefix}`
             : '';
         const identifierName: string = this.generate();
+        const identifierNameWithPrefix: string = `${prefix}${identifierName}`;
 
-        return `${prefix}${identifierName}`.replace('__', '_');
+        this.preserveName(identifierNameWithPrefix);
+
+        return identifierNameWithPrefix;
     }
 
     /**

+ 5 - 2
src/generators/identifier-names-generators/MangledIdentifierNamesGenerator.ts

@@ -83,11 +83,14 @@ export class MangledIdentifierNamesGenerator extends AbstractIdentifierNamesGene
      */
     public generateWithPrefix (nameLength?: number): string {
         const prefix: string = this.options.identifiersPrefix ?
-            `${this.options.identifiersPrefix}_`
+            `${this.options.identifiersPrefix}`
             : '';
         const identifierName: string = this.generate(nameLength);
+        const identifierNameWithPrefix: string = `${prefix}${identifierName}`;
 
-        return `${prefix}${identifierName}`;
+        this.preserveName(identifierNameWithPrefix);
+
+        return identifierNameWithPrefix;
     }
 
     /**

+ 11 - 1
src/interfaces/generators/identifier-names-generators/IIdentifierNamesGenerator.ts

@@ -21,6 +21,11 @@ export interface IIdentifierNamesGenerator {
      */
     generateWithPrefix (nameLength?: number): string;
 
+    /**
+     * @returns {Set<string>}
+     */
+    getPreservedNames (): Set<string>;
+
     /**
      * @param {string} identifierName
      * @returns {boolean}
@@ -34,9 +39,14 @@ export interface IIdentifierNamesGenerator {
      */
     isValidIdentifierNameInLexicalScope (identifierName: string, lexicalScopeNode: TNodeWithLexicalScope): boolean;
 
+    /**
+     * @param {string} identifierName
+     */
+    preserveName (identifierName: string): void;
+
     /**
      * @param {string} identifierName
      * @param {TNodeWithLexicalScope} lexicalScope
      */
-    preserveName (identifierName: string, lexicalScope: TNodeWithLexicalScope): void;
+    preserveNameForLexicalScope (identifierName: string, lexicalScope: TNodeWithLexicalScope): void;
 }

+ 6 - 1
src/interfaces/node-transformers/obfuscating-transformers/obfuscating-replacers/IIdentifierObfuscatingReplacer.ts

@@ -17,9 +17,14 @@ export interface IIdentifierObfuscatingReplacer extends IObfuscatingReplacer <ES
      */
     storeLocalName (identifierNode: ESTree.Identifier, lexicalScopeNode: TNodeWithLexicalScope): void;
 
+    /**
+     * @param {Identifier} identifierNode
+     */
+    preserveName (identifierNode: ESTree.Identifier): void;
+
     /**
      * @param {Identifier} identifierNode
      * @param {TNodeWithLexicalScope} lexicalScopeNode
      */
-    preserveName (identifierNode: ESTree.Identifier, lexicalScopeNode: TNodeWithLexicalScope): void;
+    preserveNameForLexicalScope (identifierNode: ESTree.Identifier, lexicalScopeNode: TNodeWithLexicalScope): void;
 }

+ 11 - 2
src/node-transformers/obfuscating-transformers/obfuscating-replacers/identifier-obfuscating-replacers/BaseIdentifierObfuscatingReplacer.ts

@@ -108,14 +108,23 @@ export class BaseIdentifierObfuscatingReplacer extends AbstractObfuscatingReplac
         namesMap.set(identifierName, newIdentifierName);
     }
 
+    /**
+     * Preserve `name` to protect it from further using
+     *
+     * @param {Identifier} identifierNode
+     */
+    public preserveName (identifierNode: ESTree.Identifier): void {
+        this.identifierNamesGenerator.preserveName(identifierNode.name);
+    }
+
     /**
      * Preserve `name` to protect it from further using
      *
      * @param {Identifier} identifierNode
      * @param {TNodeWithLexicalScope} lexicalScopeNode
      */
-    public preserveName (identifierNode: ESTree.Identifier, lexicalScopeNode: TNodeWithLexicalScope): void {
-        this.identifierNamesGenerator.preserveName(identifierNode.name, lexicalScopeNode);
+    public preserveNameForLexicalScope (identifierNode: ESTree.Identifier, lexicalScopeNode: TNodeWithLexicalScope): void {
+        this.identifierNamesGenerator.preserveNameForLexicalScope(identifierNode.name, lexicalScopeNode);
     }
 
     /**

+ 33 - 3
src/node-transformers/preparing-transformers/VariablePreserveTransformer.ts

@@ -66,7 +66,13 @@ export class VariablePreserveTransformer extends AbstractNodeTransformer {
                             NodeGuards.isIdentifierNode(node)
                             && parentNode
                         ) {
-                            this.preserveIdentifierNameForLexicalScope(node);
+                            const isOnTheRootLexicalScope: boolean = this.enteredLexicalScopesStack.length === 1;
+
+                            if (isOnTheRootLexicalScope) {
+                                this.preserveIdentifierNameForRootLexicalScope(node, parentNode);
+                            } else {
+                                this.preserveIdentifierNameForLexicalScope(node, parentNode);
+                            }
 
                             return this.transformNode(node, parentNode);
                         }
@@ -94,10 +100,34 @@ export class VariablePreserveTransformer extends AbstractNodeTransformer {
 
     /**
      * @param {Identifier} identifierNode
+     * @param {Node} parentNode
+     */
+    private preserveIdentifierNameForRootLexicalScope (
+        identifierNode: ESTree.Identifier,
+        parentNode: ESTree.Node
+    ): void {
+        this.identifierObfuscatingReplacer.preserveName(identifierNode);
+    }
+
+    /**
+     * @param {Identifier} identifierNode
+     * @param {Node} parentNode
      */
-    private preserveIdentifierNameForLexicalScope (identifierNode: ESTree.Identifier): void {
+    private preserveIdentifierNameForLexicalScope (
+        identifierNode: ESTree.Identifier,
+        parentNode: ESTree.Node
+    ): void {
+        if (
+            !NodeGuards.parentNodeIsPropertyNode(identifierNode, parentNode)
+            && !NodeGuards.parentNodeIsMemberExpressionNode(identifierNode, parentNode)
+            && !NodeGuards.parentNodeIsMethodDefinitionNode(identifierNode, parentNode)
+            && !NodeGuards.isLabelIdentifierNode(identifierNode, parentNode)
+        ) {
+            return;
+        }
+
         for (const lexicalScope of this.enteredLexicalScopesStack) {
-            this.identifierObfuscatingReplacer.preserveName(identifierNode, lexicalScope);
+            this.identifierObfuscatingReplacer.preserveNameForLexicalScope(identifierNode, lexicalScope);
         }
     }
 

+ 34 - 0
src/node/NodeGuards.ts

@@ -309,6 +309,40 @@ export class NodeGuards {
         return node.type === NodeType.Property;
     }
 
+    /**
+     * @param {Node} node
+     * @param {Node} parentNode
+     * @returns {boolean}
+     */
+    public static parentNodeIsPropertyNode (node: ESTree.Node, parentNode: ESTree.Node): node is ESTree.Identifier {
+        return NodeGuards.isPropertyNode(parentNode)
+            && !parentNode.computed
+            && parentNode.key === node;
+    }
+
+    /**
+     * @param {Node} node
+     * @param {Node} parentNode
+     * @returns {boolean}
+     */
+    public static parentNodeIsMemberExpressionNode (node: ESTree.Node, parentNode: ESTree.Node): node is ESTree.Identifier {
+        return (
+            NodeGuards.isMemberExpressionNode(parentNode)
+            && !parentNode.computed
+            && parentNode.property === node
+        );
+    }
+
+    /**
+     * @param {Node} node
+     * @param {Node} parentNode
+     * @returns {boolean}
+     */
+    public static parentNodeIsMethodDefinitionNode (node: ESTree.Node, parentNode: ESTree.Node): node is ESTree.Identifier {
+        return NodeGuards.isMethodDefinitionNode(parentNode)
+            && !parentNode.computed;
+    }
+
     /**
      * @param {Node} node
      * @returns {boolean}

+ 4 - 8
src/storages/string-array/StringArrayStorage.ts

@@ -154,10 +154,8 @@ export class StringArrayStorage extends MapStorage <string, IStringArrayStorageI
      */
     public getStorageId (): string {
         if (!this.stringArrayStorageName) {
-            const baseStringArrayName: string = this.identifierNamesGenerator
-                .generate(StringArrayStorage.stringArrayNameLength);
-
-            this.stringArrayStorageName = `${this.options.identifiersPrefix}${baseStringArrayName}`;
+            this.stringArrayStorageName = this.identifierNamesGenerator
+                .generateWithPrefix(StringArrayStorage.stringArrayNameLength);
         }
 
         return this.stringArrayStorageName;
@@ -175,10 +173,8 @@ export class StringArrayStorage extends MapStorage <string, IStringArrayStorageI
      */
     public getStorageCallsWrapperName (): string {
         if (!this.stringArrayStorageCallsWrapperName) {
-            const baseStringArrayCallsWrapperName: string = this.identifierNamesGenerator
-                .generate(StringArrayStorage.stringArrayNameLength);
-
-            this.stringArrayStorageCallsWrapperName = `${this.options.identifiersPrefix}${baseStringArrayCallsWrapperName}`;
+            this.stringArrayStorageCallsWrapperName = this.identifierNamesGenerator
+                .generateWithPrefix(StringArrayStorage.stringArrayNameLength);
         }
 
         return this.stringArrayStorageCallsWrapperName;

+ 14 - 3
test/dev/dev.ts

@@ -7,13 +7,24 @@ import { NO_ADDITIONAL_NODES_PRESET } from '../../src/options/presets/NoCustomNo
 
     let obfuscatedCode: string = JavaScriptObfuscator.obfuscate(
         `
-            const sdasdas = '123';
+            const a = {x: 'abc'};
+
+            function foo (b, c) {
+                return a;
+                
+                function bar () {
+                    var a = 0;
+                    return a;
+                }
+            }
         `,
         {
             ...NO_ADDITIONAL_NODES_PRESET,
             compact: false,
-            identifierNamesGenerator: 'dictionary',
-            identifiersDictionary: ['a', 'b', 'c', 'd', 'e'],
+            // identifierNamesGenerator: 'dictionary',
+            // identifiersDictionary: ['a', 'b', 'c', 'd', 'e'],
+            identifierNamesGenerator: 'mangled',
+            transformObjectKeys: true,
             stringArray: true,
             stringArrayThreshold: 1
         }

+ 1 - 1
test/functional-tests/node-transformers/obfuscating-transformers/literal-transformer/LiteralTransformer.spec.ts

@@ -324,7 +324,7 @@ describe('LiteralTransformer', () => {
         });
 
         describe('Variant #11: string array calls wrapper name', () => {
-            const regExp: RegExp = /console\[c\('0x0'\)]\('a'\);/;
+            const regExp: RegExp = /console\[b\('0x0'\)]\('a'\);/;
 
             let obfuscatedCode: string;
 

+ 3 - 3
test/functional-tests/node-transformers/obfuscating-transformers/scope-identifiers-transformer/class-declaration/ClassDeclaration.spec.ts

@@ -483,9 +483,9 @@ describe('ScopeIdentifiersTransformer ClassDeclaration identifiers', () => {
         });
 
         describe('Variant #3: already renamed identifiers shouldn\'t be renamed twice', () => {
-            const classDeclarationRegExp: RegExp = /class *f *{/;
-            const variableDeclarationsRegExp: RegExp = /let g, *h, *i, *j;/;
-            const classReferenceRegExp: RegExp = /new f\(\);/;
+            const classDeclarationRegExp: RegExp = /class *b *{/;
+            const variableDeclarationsRegExp: RegExp = /let c, *d, *e, *f;/;
+            const classReferenceRegExp: RegExp = /new b\(\);/;
 
             let obfuscatedCode: string;
 

+ 2 - 2
test/functional-tests/node-transformers/obfuscating-transformers/scope-identifiers-transformer/function-declaration/FunctionDeclaration.spec.ts

@@ -145,8 +145,8 @@ describe('ScopeIdentifiersTransformer FunctionDeclaration identifiers', () => {
 
         describe('Variant #5: already renamed identifiers shouldn\'t be renamed twice', () => {
             describe('Variant #1', () => {
-                const functionDeclarationRegExp: RegExp = /function *f\(\) *{/;
-                const variableDeclarationsRegExp: RegExp = /let g, *h, *i, *j;/;
+                const functionDeclarationRegExp: RegExp = /function *a\(\) *{/;
+                const variableDeclarationsRegExp: RegExp = /let c, *d, *e, *f;/;
 
                 let obfuscatedCode: string;
 

+ 6 - 6
test/functional-tests/node-transformers/obfuscating-transformers/scope-identifiers-transformer/variable-declaration/VariableDeclaration.spec.ts

@@ -456,11 +456,11 @@ describe('ScopeIdentifiersTransformer VariableDeclaration identifiers', () => {
 
     describe('Variant #13: already renamed identifiers shouldn\'t be renamed twice', () => {
         describe('Variant #1', () => {
-            const variableDeclarationRegExp: RegExp = /var f *= *0x1;/;
-            const functionDeclarationRegExp1: RegExp = /function *g *\(\) *{}/;
-            const functionDeclarationRegExp2: RegExp = /function *h *\(\) *{}/;
-            const functionDeclarationRegExp3: RegExp = /function *i *\(\) *{}/;
-            const functionDeclarationRegExp4: RegExp = /function *j *\(\) *{}/;
+            const variableDeclarationRegExp: RegExp = /var b *= *0x1;/;
+            const functionDeclarationRegExp1: RegExp = /function *c *\(\) *{}/;
+            const functionDeclarationRegExp2: RegExp = /function *d *\(\) *{}/;
+            const functionDeclarationRegExp3: RegExp = /function *e *\(\) *{}/;
+            const functionDeclarationRegExp4: RegExp = /function *f *\(\) *{}/;
 
             let obfuscatedCode: string;
 
@@ -501,7 +501,7 @@ describe('ScopeIdentifiersTransformer VariableDeclaration identifiers', () => {
             const variableDeclarationRegExp1: RegExp = /var b *= *0x1;/;
             const variableDeclarationRegExp2: RegExp = /var c;/;
             const functionDeclarationRegExp: RegExp = /function *d *\(\) *{/;
-            const variableDeclarationRegExp3: RegExp = /var f *= *function *\(\) *{}/;
+            const variableDeclarationRegExp3: RegExp = /var e *= *function *\(\) *{}/;
 
             let obfuscatedCode: string;
 

+ 1 - 1
test/unit-tests/generators/identifier-names-generators/DictionarylIdentifierNamesGenerator.spec.ts

@@ -148,7 +148,7 @@ describe('DictionaryIdentifierNamesGenerator', () => {
             });
 
             describe('Variant #1: Should generate identifier names with prefix', () => {
-                const expectedDictionaryIdentifierNameRegExp: RegExp = /foo_[a|A]/;
+                const expectedDictionaryIdentifierNameRegExp: RegExp = /foo[a|A]/;
 
                 beforeEach(() => {
                     dictionaryIdentifierName = identifierNamesGenerator.generateWithPrefix();

+ 2 - 2
test/unit-tests/generators/identifier-names-generators/MangledlIdentifierNamesGenerator.spec.ts

@@ -146,7 +146,7 @@ describe('MangledIdentifierNamesGenerator', () => {
         });
 
         describe('Variant #1: initial mangled name', () => {
-            const expectedMangledIdentifierName: string = 'foo_a';
+            const expectedMangledIdentifierName: string = 'fooa';
 
             beforeEach(() => {
                 mangledIdentifierName = identifierNamesGenerator.generateWithPrefix();
@@ -158,7 +158,7 @@ describe('MangledIdentifierNamesGenerator', () => {
         });
 
         describe('Variant #2: second mangled name', () => {
-            const expectedMangledIdentifierName: string = 'foo_b';
+            const expectedMangledIdentifierName: string = 'foob';
 
             beforeEach(() => {
                 mangledIdentifierName = identifierNamesGenerator.generateWithPrefix();

Một số tệp đã không được hiển thị bởi vì quá nhiều tập tin thay đổi trong này khác