ScopeIdentifiersTransformer.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. import { inject, injectable, } from 'inversify';
  2. import { ServiceIdentifiers } from '../../container/ServiceIdentifiers';
  3. import * as eslintScope from 'eslint-scope';
  4. import * as ESTree from 'estree';
  5. import * as estraverse from 'estraverse';
  6. import { TIdentifierObfuscatingReplacerFactory } from '../../types/container/node-transformers/TIdentifierObfuscatingReplacerFactory';
  7. import { TNodeWithLexicalScope } from '../../types/node/TNodeWithLexicalScope';
  8. import { IIdentifierObfuscatingReplacer } from '../../interfaces/node-transformers/obfuscating-transformers/obfuscating-replacers/IIdentifierObfuscatingReplacer';
  9. import { IOptions } from '../../interfaces/options/IOptions';
  10. import { IRandomGenerator } from '../../interfaces/utils/IRandomGenerator';
  11. import { IScopeAnalyzer } from '../../interfaces/analyzers/scope-analyzer/IScopeAnalyzer';
  12. import { IVisitor } from '../../interfaces/node-transformers/IVisitor';
  13. import { IdentifierObfuscatingReplacer } from '../../enums/node-transformers/obfuscating-transformers/obfuscating-replacers/IdentifierObfuscatingReplacer';
  14. import { TransformationStage } from '../../enums/node-transformers/TransformationStage';
  15. import { AbstractNodeTransformer } from '../AbstractNodeTransformer';
  16. import { NodeGuards } from '../../node/NodeGuards';
  17. import { NodeMetadata } from '../../node/NodeMetadata';
  18. /**
  19. * Replaces all replaceable identifiers in scope
  20. */
  21. @injectable()
  22. export class ScopeIdentifiersTransformer extends AbstractNodeTransformer {
  23. /**
  24. * @type {string}
  25. */
  26. private static readonly argumentsVariableName: string = 'arguments';
  27. /**
  28. * @type {string[]}
  29. */
  30. private static readonly globalScopeNames: string[] = [
  31. 'global',
  32. 'module'
  33. ];
  34. /**
  35. * @type {IIdentifierObfuscatingReplacer}
  36. */
  37. private readonly identifierObfuscatingReplacer: IIdentifierObfuscatingReplacer;
  38. /**
  39. * @type {Map<TNodeWithLexicalScope, boolean>}
  40. */
  41. private readonly lexicalScopesWithObjectPatternWithoutDeclarationMap: Map<TNodeWithLexicalScope, boolean> = new Map();
  42. /**
  43. * @type {IScopeAnalyzer}
  44. */
  45. private readonly scopeAnalyzer: IScopeAnalyzer;
  46. /**
  47. * @param {TIdentifierObfuscatingReplacerFactory} identifierObfuscatingReplacerFactory
  48. * @param {IRandomGenerator} randomGenerator
  49. * @param {IOptions} options
  50. * @param {IScopeAnalyzer} scopeAnalyzer
  51. */
  52. constructor (
  53. @inject(ServiceIdentifiers.Factory__IIdentifierObfuscatingReplacer)
  54. identifierObfuscatingReplacerFactory: TIdentifierObfuscatingReplacerFactory,
  55. @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator,
  56. @inject(ServiceIdentifiers.IOptions) options: IOptions,
  57. @inject(ServiceIdentifiers.IScopeAnalyzer) scopeAnalyzer: IScopeAnalyzer
  58. ) {
  59. super(randomGenerator, options);
  60. this.identifierObfuscatingReplacer = identifierObfuscatingReplacerFactory(
  61. IdentifierObfuscatingReplacer.BaseIdentifierObfuscatingReplacer
  62. );
  63. this.scopeAnalyzer = scopeAnalyzer;
  64. }
  65. /**
  66. * @param {TransformationStage} transformationStage
  67. * @returns {IVisitor | null}
  68. */
  69. public getVisitor (transformationStage: TransformationStage): IVisitor | null {
  70. switch (transformationStage) {
  71. case TransformationStage.Obfuscating:
  72. return {
  73. enter: (node: ESTree.Node, parentNode: ESTree.Node | null) => {
  74. if (parentNode && NodeGuards.isProgramNode(node)) {
  75. this.analyzeNode(node, parentNode);
  76. return this.transformNode(node, parentNode);
  77. }
  78. }
  79. };
  80. default:
  81. return null;
  82. }
  83. }
  84. /**
  85. * @param {Program} programNode
  86. * @param {Node | null} parentNode
  87. * @returns {Node}
  88. */
  89. public analyzeNode (programNode: ESTree.Program, parentNode: ESTree.Node | null): void {
  90. this.scopeAnalyzer.analyze(programNode);
  91. }
  92. /**
  93. * @param {VariableDeclaration} programNode
  94. * @param {NodeGuards} parentNode
  95. * @returns {NodeGuards}
  96. */
  97. public transformNode (programNode: ESTree.Program, parentNode: ESTree.Node): ESTree.Node {
  98. const globalScope: eslintScope.Scope = this.scopeAnalyzer.acquireScope(programNode);
  99. this.traverseScopeVariables(globalScope);
  100. return programNode;
  101. }
  102. /**
  103. * @param {Scope} scope
  104. */
  105. private traverseScopeVariables (scope: eslintScope.Scope): void {
  106. const lexicalScope: eslintScope.Scope = scope.variableScope;
  107. const nodeWithLexicalScope: TNodeWithLexicalScope | null = NodeGuards.isNodeWithBlockLexicalScope(lexicalScope.block)
  108. ? lexicalScope.block
  109. : null;
  110. const isGlobalDeclaration: boolean = ScopeIdentifiersTransformer.globalScopeNames.includes(lexicalScope.type);
  111. if (!nodeWithLexicalScope) {
  112. return;
  113. }
  114. for (const variable of scope.variables) {
  115. if (variable.name === ScopeIdentifiersTransformer.argumentsVariableName) {
  116. continue;
  117. }
  118. if (!this.options.renameGlobals && isGlobalDeclaration) {
  119. const isImportBindingOrCatchClauseIdentifier: boolean = variable.defs
  120. .every((definition: eslintScope.Definition) =>
  121. definition.type === 'ImportBinding'
  122. || definition.type === 'CatchClause'
  123. );
  124. // skip all global identifiers except import statement and catch clause parameter identifiers
  125. if (!isImportBindingOrCatchClauseIdentifier) {
  126. continue;
  127. }
  128. }
  129. this.transformScopeVariableIdentifiers(variable, nodeWithLexicalScope, isGlobalDeclaration);
  130. }
  131. for (const childScope of scope.childScopes) {
  132. this.traverseScopeVariables(childScope);
  133. }
  134. }
  135. /**
  136. * @param {Variable} variable
  137. * @param {TNodeWithLexicalScope} lexicalScopeNode
  138. * @param {boolean} isGlobalDeclaration
  139. */
  140. private transformScopeVariableIdentifiers (
  141. variable: eslintScope.Variable,
  142. lexicalScopeNode: TNodeWithLexicalScope,
  143. isGlobalDeclaration: boolean
  144. ): void {
  145. for (const identifier of variable.identifiers) {
  146. if (!this.isReplaceableIdentifierNode(identifier, lexicalScopeNode, variable)) {
  147. continue;
  148. }
  149. this.storeIdentifierName(identifier, lexicalScopeNode, isGlobalDeclaration);
  150. this.replaceIdentifierName(identifier, lexicalScopeNode, variable);
  151. }
  152. }
  153. /**
  154. * @param {Identifier} identifierNode
  155. * @param {TNodeWithLexicalScope} lexicalScopeNode
  156. * @param {boolean} isGlobalDeclaration
  157. */
  158. private storeIdentifierName (
  159. identifierNode: ESTree.Identifier,
  160. lexicalScopeNode: TNodeWithLexicalScope,
  161. isGlobalDeclaration: boolean
  162. ): void {
  163. if (isGlobalDeclaration) {
  164. this.identifierObfuscatingReplacer.storeGlobalName(identifierNode, lexicalScopeNode);
  165. } else {
  166. this.identifierObfuscatingReplacer.storeLocalName(identifierNode, lexicalScopeNode);
  167. }
  168. }
  169. /**
  170. * @param {Identifier} identifierNode
  171. * @param {TNodeWithLexicalScope} lexicalScopeNode
  172. * @param {Variable} variable
  173. */
  174. private replaceIdentifierName (
  175. identifierNode: ESTree.Identifier,
  176. lexicalScopeNode: TNodeWithLexicalScope,
  177. variable: eslintScope.Variable
  178. ): void {
  179. const newIdentifier: ESTree.Identifier = this.identifierObfuscatingReplacer
  180. .replace(identifierNode, lexicalScopeNode);
  181. identifierNode.name = newIdentifier.name;
  182. // rename of references
  183. variable.references.forEach((reference: eslintScope.Reference) => {
  184. reference.identifier.name = identifierNode.name;
  185. });
  186. }
  187. /**
  188. * @param {Identifier} identifierNode
  189. * @param {TNodeWithLexicalScope} lexicalScopeNode
  190. * @param {Variable} variable
  191. * @returns {boolean}
  192. */
  193. private isReplaceableIdentifierNode (
  194. identifierNode: ESTree.Identifier,
  195. lexicalScopeNode: TNodeWithLexicalScope,
  196. variable: eslintScope.Variable
  197. ): identifierNode is ESTree.Identifier & { parentNode: ESTree.Node } {
  198. const parentNode: ESTree.Node | undefined = identifierNode.parentNode;
  199. return !!parentNode
  200. && !NodeMetadata.isIgnoredNode(identifierNode)
  201. && !this.isProhibitedPropertyNode(identifierNode, parentNode)
  202. && !this.isProhibitedClassDeclarationNameIdentifierNode(variable, identifierNode, parentNode)
  203. && !this.isProhibitedExportNamedClassDeclarationIdentifierNode(identifierNode, parentNode)
  204. && !this.isProhibitedExportNamedFunctionDeclarationIdentifierNode(identifierNode, parentNode)
  205. && !this.isProhibitedExportNamedVariableDeclarationIdentifierNode(identifierNode, parentNode)
  206. && !this.isProhibitedImportSpecifierNode(identifierNode, parentNode)
  207. && !this.isProhibitedVariableNameUsedInObjectPatternNode(variable, identifierNode, lexicalScopeNode)
  208. && !NodeGuards.isLabelIdentifierNode(identifierNode, parentNode);
  209. }
  210. /**
  211. * @param {Variable} variable
  212. * @param {Identifier} identifierNode
  213. * @param {Node} parentNode
  214. * @returns {identifierNode is Identifier}
  215. */
  216. private isProhibitedClassDeclarationNameIdentifierNode (
  217. variable: eslintScope.Variable,
  218. identifierNode: ESTree.Identifier,
  219. parentNode: ESTree.Node
  220. ): identifierNode is ESTree.Identifier {
  221. return NodeGuards.isClassDeclarationNode(variable.scope.block)
  222. && NodeGuards.isClassDeclarationNode(parentNode)
  223. && parentNode.id === identifierNode;
  224. }
  225. /**
  226. * @param {Identifier} identifierNode
  227. * @param {Node} parentNode
  228. * @returns {identifierNode is Identifier}
  229. */
  230. private isProhibitedExportNamedClassDeclarationIdentifierNode (
  231. identifierNode: ESTree.Identifier,
  232. parentNode: ESTree.Node
  233. ): identifierNode is ESTree.Identifier {
  234. return NodeGuards.isClassDeclarationNode(parentNode)
  235. && parentNode.id === identifierNode
  236. && !!parentNode.parentNode
  237. && NodeGuards.isExportNamedDeclarationNode(parentNode.parentNode);
  238. }
  239. /**
  240. * @param {Identifier} identifierNode
  241. * @param {Node} parentNode
  242. * @returns {identifierNode is Identifier}
  243. */
  244. private isProhibitedExportNamedFunctionDeclarationIdentifierNode (
  245. identifierNode: ESTree.Identifier,
  246. parentNode: ESTree.Node
  247. ): identifierNode is ESTree.Identifier {
  248. return NodeGuards.isFunctionDeclarationNode(parentNode)
  249. && parentNode.id === identifierNode
  250. && !!parentNode.parentNode
  251. && NodeGuards.isExportNamedDeclarationNode(parentNode.parentNode);
  252. }
  253. /**
  254. * @param {Identifier} identifierNode
  255. * @param {Node} parentNode
  256. * @returns {identifierNode is Identifier}
  257. */
  258. private isProhibitedExportNamedVariableDeclarationIdentifierNode (
  259. identifierNode: ESTree.Identifier,
  260. parentNode: ESTree.Node
  261. ): identifierNode is ESTree.Identifier {
  262. return NodeGuards.isVariableDeclaratorNode(parentNode)
  263. && parentNode.id === identifierNode
  264. && !!parentNode.parentNode
  265. && NodeGuards.isVariableDeclarationNode(parentNode.parentNode)
  266. && !!parentNode.parentNode.parentNode
  267. && NodeGuards.isExportNamedDeclarationNode(parentNode.parentNode.parentNode);
  268. }
  269. /**
  270. * @param {Identifier} identifierNode
  271. * @param {Node} parentNode
  272. * @returns {boolean}
  273. */
  274. private isProhibitedImportSpecifierNode (identifierNode: ESTree.Identifier, parentNode: ESTree.Node): boolean {
  275. return NodeGuards.isImportSpecifierNode(parentNode)
  276. && parentNode.imported.name === parentNode.local.name;
  277. }
  278. /**
  279. * @param {Node} node
  280. * @param {Node} parentNode
  281. * @returns {boolean}
  282. */
  283. private isProhibitedPropertyNode (node: ESTree.Node, parentNode: ESTree.Node): node is ESTree.Identifier {
  284. return NodeGuards.isPropertyNode(parentNode)
  285. && !parentNode.computed
  286. && parentNode.key === node;
  287. }
  288. /**
  289. * Should not rename identifiers that used inside destructing assignment without declaration
  290. *
  291. * var a, b; // should not be renamed
  292. * ({a, b} = {a: 1, b: 2});
  293. *
  294. * @param {Variable} variable
  295. * @param {Identifier} identifierNode
  296. * @param {TNodeWithLexicalScope} lexicalScopeNode
  297. * @returns {boolean}
  298. */
  299. private isProhibitedVariableNameUsedInObjectPatternNode (
  300. variable: eslintScope.Variable,
  301. identifierNode: ESTree.Identifier,
  302. lexicalScopeNode: TNodeWithLexicalScope
  303. ): boolean {
  304. let isLexicalScopeHasObjectPatternWithoutDeclaration: boolean | undefined =
  305. this.lexicalScopesWithObjectPatternWithoutDeclarationMap.get(lexicalScopeNode);
  306. // lexical scope was traversed before and object pattern without declaration was not found
  307. if (isLexicalScopeHasObjectPatternWithoutDeclaration === false) {
  308. return false;
  309. }
  310. const hasVarDefinitions: boolean = variable.defs.some((definition: eslintScope.Definition) => (<any>definition).kind === 'var');
  311. if (!hasVarDefinitions) {
  312. return false;
  313. }
  314. let isProhibitedVariableDeclaration: boolean = false;
  315. estraverse.traverse(lexicalScopeNode, {
  316. enter: (node: ESTree.Node, parentNode: ESTree.Node | null): void | estraverse.VisitorOption => {
  317. if (
  318. NodeGuards.isObjectPatternNode(node)
  319. && parentNode
  320. && NodeGuards.isAssignmentExpressionNode(parentNode)
  321. ) {
  322. isLexicalScopeHasObjectPatternWithoutDeclaration = true;
  323. const properties: ESTree.Property[] = node.properties;
  324. for (const property of properties) {
  325. if (property.computed || !property.shorthand) {
  326. continue;
  327. }
  328. if (!NodeGuards.isIdentifierNode(property.key)) {
  329. continue;
  330. }
  331. if (identifierNode.name !== property.key.name) {
  332. continue;
  333. }
  334. isProhibitedVariableDeclaration = true;
  335. return estraverse.VisitorOption.Break;
  336. }
  337. }
  338. }
  339. });
  340. this.lexicalScopesWithObjectPatternWithoutDeclarationMap.set(
  341. lexicalScopeNode,
  342. isLexicalScopeHasObjectPatternWithoutDeclaration ?? false
  343. );
  344. return isProhibitedVariableDeclaration;
  345. }
  346. }