VariableDeclarationObfuscator.ts 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import * as estraverse from 'estraverse';
  2. import * as ESTree from 'estree';
  3. import { TNodeWithBlockStatement } from '../../types/TNodeWithBlockStatement';
  4. import { ICustomNode } from '../../interfaces/custom-nodes/ICustomNode';
  5. import { IOptions } from '../../interfaces/IOptions';
  6. import { NodeType } from '../../enums/NodeType';
  7. import { AbstractNodeTransformer } from '../AbstractNodeTransformer';
  8. import { IdentifierReplacer } from './replacers/IdentifierReplacer';
  9. import { Node } from '../../node/Node';
  10. import { NodeUtils } from '../../node/NodeUtils';
  11. /**
  12. * replaces:
  13. * var variable = 1;
  14. * variable++;
  15. *
  16. * on:
  17. * var _0x12d45f = 1;
  18. * _0x12d45f++;
  19. *
  20. */
  21. export class VariableDeclarationObfuscator extends AbstractNodeTransformer {
  22. /**
  23. * @type {IdentifierReplacer}
  24. */
  25. private identifierReplacer: IdentifierReplacer;
  26. /**
  27. * @param nodes
  28. * @param options
  29. */
  30. constructor(nodes: Map <string, ICustomNode>, options: IOptions) {
  31. super(nodes, options);
  32. this.identifierReplacer = new IdentifierReplacer(this.nodes, this.options);
  33. }
  34. /**
  35. * @param variableDeclarationNode
  36. * @param parentNode
  37. */
  38. public transformNode (variableDeclarationNode: ESTree.VariableDeclaration, parentNode: ESTree.Node): void {
  39. const blockScopeOfVariableDeclarationNode: TNodeWithBlockStatement = NodeUtils
  40. .getBlockScopeOfNode(variableDeclarationNode);
  41. if (blockScopeOfVariableDeclarationNode.type === NodeType.Program) {
  42. return;
  43. }
  44. const scopeNode: ESTree.Node = variableDeclarationNode.kind === 'var'
  45. ? blockScopeOfVariableDeclarationNode
  46. : parentNode;
  47. this.storeVariableNames(variableDeclarationNode);
  48. this.replaceVariableNames(scopeNode);
  49. }
  50. /**
  51. * @param variableDeclarationNode
  52. */
  53. private storeVariableNames (variableDeclarationNode: ESTree.VariableDeclaration): void {
  54. variableDeclarationNode.declarations
  55. .forEach((declarationNode: ESTree.VariableDeclarator) => {
  56. NodeUtils.typedReplace(declarationNode.id, NodeType.Identifier, {
  57. enter: (node: ESTree.Identifier) => this.identifierReplacer.storeNames(node.name)
  58. });
  59. });
  60. }
  61. /**
  62. * @param scopeNode
  63. */
  64. private replaceVariableNames (scopeNode: ESTree.Node): void {
  65. estraverse.replace(scopeNode, {
  66. enter: (node: ESTree.Node, parentNode: ESTree.Node): any => {
  67. if (!node.obfuscated && Node.isReplaceableIdentifierNode(node, parentNode)) {
  68. node.name = this.identifierReplacer.replace(node.name);
  69. }
  70. }
  71. });
  72. }
  73. }