FunctionDeclarationObfuscator.ts 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import * as estraverse from 'estraverse';
  2. import * as ESTree from 'estree';
  3. import { ICustomNode } from '../interfaces/custom-nodes/ICustomNode';
  4. import { IOptions } from '../interfaces/IOptions';
  5. import { NodeType } from '../enums/NodeType';
  6. import { AbstractNodeObfuscator } from './AbstractNodeObfuscator';
  7. import { IdentifierReplacer } from './replacers/IdentifierReplacer';
  8. import { Node } from '../node/Node';
  9. import { NodeUtils } from '../node/NodeUtils';
  10. /**
  11. * replaces:
  12. * function foo () { //... };
  13. * foo();
  14. *
  15. * on:
  16. * function _0x12d45f () { //... };
  17. * _0x12d45f();
  18. */
  19. export class FunctionDeclarationObfuscator extends AbstractNodeObfuscator {
  20. /**
  21. * @type {IdentifierReplacer}
  22. */
  23. private identifierReplacer: IdentifierReplacer;
  24. /**
  25. * @param nodes
  26. * @param options
  27. */
  28. constructor(nodes: Map <string, ICustomNode>, options: IOptions) {
  29. super(nodes, options);
  30. this.identifierReplacer = new IdentifierReplacer(this.nodes, this.options);
  31. }
  32. /**
  33. * @param functionDeclarationNode
  34. * @param parentNode
  35. */
  36. public obfuscateNode (functionDeclarationNode: ESTree.FunctionDeclaration, parentNode: ESTree.Node): void {
  37. if (parentNode.type === NodeType.Program) {
  38. return;
  39. }
  40. this.storeFunctionName(functionDeclarationNode);
  41. this.replaceFunctionName(functionDeclarationNode);
  42. }
  43. /**
  44. * @param functionDeclarationNode
  45. */
  46. private storeFunctionName (functionDeclarationNode: ESTree.FunctionDeclaration): void {
  47. NodeUtils.typedReplace(functionDeclarationNode.id, NodeType.Identifier, {
  48. enter: (node: ESTree.Identifier) => this.identifierReplacer.storeNames(node.name)
  49. });
  50. }
  51. /**
  52. * @param functionDeclarationNode
  53. */
  54. private replaceFunctionName (functionDeclarationNode: ESTree.FunctionDeclaration): void {
  55. let scopeNode: ESTree.Node = NodeUtils.getBlockScopeOfNode(
  56. functionDeclarationNode
  57. );
  58. estraverse.replace(scopeNode, {
  59. enter: (node: ESTree.Node, parentNode: ESTree.Node): any => {
  60. if (Node.isReplaceableIdentifierNode(node, parentNode)) {
  61. node.name = this.identifierReplacer.replace(node.name);
  62. }
  63. }
  64. });
  65. }
  66. }