StringLiteralControlFlowReplacer.spec.ts 3.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import { assert } from 'chai';
  2. import { NO_ADDITIONAL_NODES_PRESET } from '../../../../../../src/options/presets/NoCustomNodes';
  3. import { readFileAsString } from '../../../../../helpers/readFileAsString';
  4. import { getRegExpMatch } from '../../../../../helpers/getRegExpMatch';
  5. import { JavaScriptObfuscator } from '../../../../../../src/JavaScriptObfuscatorFacade';
  6. describe('StringLiteralControlFlowReplacer', () => {
  7. describe('replace', () => {
  8. const variableMatch: string = '_0x([a-f0-9]){4,6}';
  9. describe('Variant #1 - base behavior', () => {
  10. const controlFlowStorageStringLiteralRegExp: RegExp = new RegExp(
  11. `var ${variableMatch} *= *\\{'\\w{5}' *: *'test'\\};`
  12. );
  13. const controlFlowStorageCallRegExp: RegExp = new RegExp(
  14. `var ${variableMatch} *= *${variableMatch}\\['\\w{5}'\\];`
  15. );
  16. let obfuscatedCode: string;
  17. before(() => {
  18. const code: string = readFileAsString(__dirname + '/fixtures/input-1.js');
  19. obfuscatedCode = JavaScriptObfuscator.obfuscate(
  20. code,
  21. {
  22. ...NO_ADDITIONAL_NODES_PRESET,
  23. controlFlowFlattening: true,
  24. controlFlowFlatteningThreshold: 1
  25. }
  26. ).getObfuscatedCode();
  27. });
  28. it('should add string literal node as property of control flow storage node', () => {
  29. assert.match(obfuscatedCode, controlFlowStorageStringLiteralRegExp);
  30. });
  31. it('should replace string literal node with call to control flow storage node', () => {
  32. assert.match(obfuscatedCode, controlFlowStorageCallRegExp);
  33. });
  34. });
  35. describe('Variant #2 - same storage key for same string values', () => {
  36. const storageKeyRegExp: RegExp = /'(\w{5})': 'value'/;
  37. const expectedStorageCallsMatchesCount: number = 5;
  38. let storageCallsMatchesCount: number;
  39. before(() => {
  40. const code: string = readFileAsString(__dirname + '/fixtures/same-storage-key-for-same-string-values.js');
  41. const obfuscatedCode: string = JavaScriptObfuscator.obfuscate(
  42. code,
  43. {
  44. ...NO_ADDITIONAL_NODES_PRESET,
  45. compact: false,
  46. controlFlowFlattening: true,
  47. controlFlowFlatteningThreshold: 1
  48. }
  49. ).getObfuscatedCode();
  50. const storageKeyMatch = getRegExpMatch(obfuscatedCode, storageKeyRegExp);
  51. const storageCallsRegExp = new RegExp(`${variableMatch}\\[\'${storageKeyMatch}\']`, 'g')
  52. storageCallsMatchesCount = obfuscatedCode.match(storageCallsRegExp)?.length ?? 0;
  53. });
  54. it('should add string literal nodes with same values under same storage item', () => {
  55. assert.equal(storageCallsMatchesCount, expectedStorageCallsMatchesCount);
  56. });
  57. });
  58. });
  59. });