ScopeIdentifiersTransformer.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  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. // rename of function default parameter identifiers if exists
  187. (<any>variable.scope.block).defaults?.forEach((node: ESTree.Node) => {
  188. if (NodeGuards.isIdentifierNode(node) && node.name === variable.name) {
  189. node.name = identifierNode.name;
  190. }
  191. });
  192. }
  193. /**
  194. * @param {Identifier} identifierNode
  195. * @param {TNodeWithLexicalScope} lexicalScopeNode
  196. * @param {Variable} variable
  197. * @returns {boolean}
  198. */
  199. private isReplaceableIdentifierNode (
  200. identifierNode: ESTree.Identifier,
  201. lexicalScopeNode: TNodeWithLexicalScope,
  202. variable: eslintScope.Variable
  203. ): identifierNode is ESTree.Identifier & { parentNode: ESTree.Node } {
  204. const parentNode: ESTree.Node | undefined = identifierNode.parentNode;
  205. return !!parentNode
  206. && !NodeMetadata.isIgnoredNode(identifierNode)
  207. && !this.isProhibitedPropertyNode(identifierNode, parentNode)
  208. && !this.isProhibitedClassDeclarationNameIdentifierNode(variable, identifierNode, parentNode)
  209. && !this.isProhibitedExportNamedClassDeclarationIdentifierNode(identifierNode, parentNode)
  210. && !this.isProhibitedExportNamedFunctionDeclarationIdentifierNode(identifierNode, parentNode)
  211. && !this.isProhibitedExportNamedVariableDeclarationIdentifierNode(identifierNode, parentNode)
  212. && !this.isProhibitedImportSpecifierNode(identifierNode, parentNode)
  213. && !this.isProhibitedVariableNameUsedInObjectPatternNode(variable, identifierNode, lexicalScopeNode)
  214. && !NodeGuards.isLabelIdentifierNode(identifierNode, parentNode);
  215. }
  216. /**
  217. * @param {Variable} variable
  218. * @param {Identifier} identifierNode
  219. * @param {Node} parentNode
  220. * @returns {identifierNode is Identifier}
  221. */
  222. private isProhibitedClassDeclarationNameIdentifierNode (
  223. variable: eslintScope.Variable,
  224. identifierNode: ESTree.Identifier,
  225. parentNode: ESTree.Node
  226. ): identifierNode is ESTree.Identifier {
  227. return NodeGuards.isClassDeclarationNode(variable.scope.block)
  228. && NodeGuards.isClassDeclarationNode(parentNode)
  229. && parentNode.id === identifierNode;
  230. }
  231. /**
  232. * @param {Identifier} identifierNode
  233. * @param {Node} parentNode
  234. * @returns {identifierNode is Identifier}
  235. */
  236. private isProhibitedExportNamedClassDeclarationIdentifierNode (
  237. identifierNode: ESTree.Identifier,
  238. parentNode: ESTree.Node
  239. ): identifierNode is ESTree.Identifier {
  240. return NodeGuards.isClassDeclarationNode(parentNode)
  241. && parentNode.id === identifierNode
  242. && !!parentNode.parentNode
  243. && NodeGuards.isExportNamedDeclarationNode(parentNode.parentNode);
  244. }
  245. /**
  246. * @param {Identifier} identifierNode
  247. * @param {Node} parentNode
  248. * @returns {identifierNode is Identifier}
  249. */
  250. private isProhibitedExportNamedFunctionDeclarationIdentifierNode (
  251. identifierNode: ESTree.Identifier,
  252. parentNode: ESTree.Node
  253. ): identifierNode is ESTree.Identifier {
  254. return NodeGuards.isFunctionDeclarationNode(parentNode)
  255. && parentNode.id === identifierNode
  256. && !!parentNode.parentNode
  257. && NodeGuards.isExportNamedDeclarationNode(parentNode.parentNode);
  258. }
  259. /**
  260. * @param {Identifier} identifierNode
  261. * @param {Node} parentNode
  262. * @returns {identifierNode is Identifier}
  263. */
  264. private isProhibitedExportNamedVariableDeclarationIdentifierNode (
  265. identifierNode: ESTree.Identifier,
  266. parentNode: ESTree.Node
  267. ): identifierNode is ESTree.Identifier {
  268. return NodeGuards.isVariableDeclaratorNode(parentNode)
  269. && parentNode.id === identifierNode
  270. && !!parentNode.parentNode
  271. && NodeGuards.isVariableDeclarationNode(parentNode.parentNode)
  272. && !!parentNode.parentNode.parentNode
  273. && NodeGuards.isExportNamedDeclarationNode(parentNode.parentNode.parentNode);
  274. }
  275. /**
  276. * @param {Identifier} identifierNode
  277. * @param {Node} parentNode
  278. * @returns {boolean}
  279. */
  280. private isProhibitedImportSpecifierNode (identifierNode: ESTree.Identifier, parentNode: ESTree.Node): boolean {
  281. return NodeGuards.isImportSpecifierNode(parentNode)
  282. && parentNode.imported.name === parentNode.local.name;
  283. }
  284. /**
  285. * @param {Node} node
  286. * @param {Node} parentNode
  287. * @returns {boolean}
  288. */
  289. private isProhibitedPropertyNode (node: ESTree.Node, parentNode: ESTree.Node): node is ESTree.Identifier {
  290. return NodeGuards.isPropertyNode(parentNode)
  291. && !parentNode.computed
  292. && parentNode.key === node;
  293. }
  294. /**
  295. * Should not rename identifiers that used inside destructing assignment without declaration
  296. *
  297. * var a, b; // should not be renamed
  298. * ({a, b} = {a: 1, b: 2});
  299. *
  300. * @param {Variable} variable
  301. * @param {Identifier} identifierNode
  302. * @param {TNodeWithLexicalScope} lexicalScopeNode
  303. * @returns {boolean}
  304. */
  305. private isProhibitedVariableNameUsedInObjectPatternNode (
  306. variable: eslintScope.Variable,
  307. identifierNode: ESTree.Identifier,
  308. lexicalScopeNode: TNodeWithLexicalScope
  309. ): boolean {
  310. let isLexicalScopeHasObjectPatternWithoutDeclaration: boolean | undefined =
  311. this.lexicalScopesWithObjectPatternWithoutDeclarationMap.get(lexicalScopeNode);
  312. // lexical scope was traversed before and object pattern without declaration was not found
  313. if (isLexicalScopeHasObjectPatternWithoutDeclaration === false) {
  314. return false;
  315. }
  316. const hasVarDefinitions: boolean = variable.defs.some((definition: eslintScope.Definition) => (<any>definition).kind === 'var');
  317. if (!hasVarDefinitions) {
  318. return false;
  319. }
  320. let isProhibitedVariableDeclaration: boolean = false;
  321. estraverse.traverse(lexicalScopeNode, {
  322. enter: (node: ESTree.Node, parentNode: ESTree.Node | null): void | estraverse.VisitorOption => {
  323. if (
  324. NodeGuards.isObjectPatternNode(node)
  325. && parentNode
  326. && NodeGuards.isAssignmentExpressionNode(parentNode)
  327. ) {
  328. isLexicalScopeHasObjectPatternWithoutDeclaration = true;
  329. const properties: ESTree.Property[] = node.properties;
  330. for (const property of properties) {
  331. if (property.computed || !property.shorthand) {
  332. continue;
  333. }
  334. if (!NodeGuards.isIdentifierNode(property.key)) {
  335. continue;
  336. }
  337. if (identifierNode.name !== property.key.name) {
  338. continue;
  339. }
  340. isProhibitedVariableDeclaration = true;
  341. return estraverse.VisitorOption.Break;
  342. }
  343. }
  344. }
  345. });
  346. this.lexicalScopesWithObjectPatternWithoutDeclarationMap.set(
  347. lexicalScopeNode,
  348. isLexicalScopeHasObjectPatternWithoutDeclaration ?? false
  349. );
  350. return isProhibitedVariableDeclaration;
  351. }
  352. }