FunctionDeclarationObfuscator.ts 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import * as estraverse from 'estraverse';
  2. import { IFunctionDeclarationNode } from "../interfaces/nodes/IFunctionDeclarationNode";
  3. import { INode } from "../interfaces/nodes/INode";
  4. import { NodeType } from "../enums/NodeType";
  5. import { NodeObfuscator } from './NodeObfuscator';
  6. import { NodeUtils } from "../NodeUtils";
  7. /**
  8. * replaces:
  9. * function foo () { //... };
  10. * foo();
  11. *
  12. * on:
  13. * function _0x12d45f () { //... };
  14. * _0x12d45f();
  15. */
  16. export class FunctionDeclarationObfuscator extends NodeObfuscator {
  17. /**
  18. * @type {Map<string, string>}
  19. */
  20. private functionName: Map <string, string> = new Map <string, string> ();
  21. /**
  22. * @param functionDeclarationNode
  23. * @param parentNode
  24. */
  25. public obfuscateNode (functionDeclarationNode: IFunctionDeclarationNode, parentNode: INode): void {
  26. if (parentNode.type === NodeType.Program) {
  27. return;
  28. }
  29. this.storeFunctionName(functionDeclarationNode);
  30. this.replaceFunctionName(functionDeclarationNode);
  31. }
  32. /**
  33. * @param functionDeclarationNode
  34. */
  35. private storeFunctionName (functionDeclarationNode: IFunctionDeclarationNode): void {
  36. estraverse.traverse(functionDeclarationNode.id, {
  37. leave: (node: INode): any => this.storeIdentifiersNames(node, this.functionName)
  38. });
  39. }
  40. /**
  41. * @param functionDeclarationNode
  42. */
  43. private replaceFunctionName (functionDeclarationNode: IFunctionDeclarationNode): void {
  44. let scopeNode: INode = NodeUtils.getBlockScopeOfNode(
  45. functionDeclarationNode
  46. );
  47. estraverse.replace(scopeNode, {
  48. enter: (node: INode, parentNode: INode): any => {
  49. this.replaceIdentifiersWithRandomNames(node, parentNode, this.functionName);
  50. }
  51. });
  52. }
  53. }