ConditionalCommentObfuscatingGuard.ts 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import { injectable } from 'inversify';
  2. import * as ESTree from 'estree';
  3. import { IObfuscatingGuard } from '../../../interfaces/node-transformers/preparing-transformers/obfuscating-guards/IObfuscatingGuard';
  4. import { ObfuscatingGuardResult } from '../../../enums/node/ObfuscatingGuardResult';
  5. import { NodeGuards } from '../../../node/NodeGuards';
  6. @injectable()
  7. export class ConditionalCommentObfuscatingGuard implements IObfuscatingGuard {
  8. /**
  9. * @type {RegExp}
  10. */
  11. private static readonly obfuscationEnableCommentRegExp: RegExp = new RegExp('javascript-obfuscator *: *enable');
  12. /**
  13. * @type {RegExp}
  14. */
  15. private static readonly obfuscationDisableCommentRegExp: RegExp = new RegExp('javascript-obfuscator *: *disable');
  16. /**
  17. * @type {boolean}
  18. */
  19. private obfuscationAllowed: boolean = true;
  20. /**
  21. * @param {Comment} comment
  22. * @returns {boolean}
  23. */
  24. public static isConditionalComment (comment: ESTree.Comment): boolean {
  25. return ConditionalCommentObfuscatingGuard.obfuscationEnableCommentRegExp.test(comment.value) ||
  26. ConditionalCommentObfuscatingGuard.obfuscationDisableCommentRegExp.test(comment.value);
  27. }
  28. /**
  29. * @param {Node} node
  30. * @returns {ObfuscatingGuardResult}
  31. */
  32. public check (node: ESTree.Node): ObfuscatingGuardResult {
  33. if (NodeGuards.isNodeWithComments(node)) {
  34. const leadingComments: ESTree.Comment[] | undefined = node.leadingComments;
  35. if (leadingComments) {
  36. this.obfuscationAllowed = this.checkComments(leadingComments);
  37. }
  38. }
  39. return this.obfuscationAllowed
  40. ? ObfuscatingGuardResult.Obfuscate
  41. : ObfuscatingGuardResult.Ignore;
  42. }
  43. /**
  44. * @param {Comment[]} comments
  45. * @returns {boolean}
  46. */
  47. private checkComments (comments: ESTree.Comment[]): boolean {
  48. const commentsLength: number = comments.length;
  49. let obfuscationAllowed: boolean = this.obfuscationAllowed;
  50. for (let i: number = 0; i < commentsLength; i++) {
  51. const comment: ESTree.Comment = comments[i];
  52. if (ConditionalCommentObfuscatingGuard.obfuscationEnableCommentRegExp.test(comment.value)) {
  53. obfuscationAllowed = true;
  54. continue;
  55. }
  56. if (ConditionalCommentObfuscatingGuard.obfuscationDisableCommentRegExp.test(comment.value)) {
  57. obfuscationAllowed = false;
  58. }
  59. }
  60. return obfuscationAllowed;
  61. }
  62. }