JavaScriptObfuscatorCLI.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. import * as commander from 'commander';
  2. import * as path from 'path';
  3. import { TInputCLIOptions } from '../types/options/TInputCLIOptions';
  4. import { TInputOptions } from '../types/options/TInputOptions';
  5. import { TSourceCodeData } from '../types/cli/TSourceCodeData';
  6. import { IFileData } from '../interfaces/cli/IFileData';
  7. import { IInitializable } from '../interfaces/IInitializable';
  8. import { IObfuscationResult } from '../interfaces/IObfuscationResult';
  9. import { initializable } from '../decorators/Initializable';
  10. import { DEFAULT_PRESET } from '../options/presets/Default';
  11. import { ArraySanitizer } from './sanitizers/ArraySanitizer';
  12. import { BooleanSanitizer } from './sanitizers/BooleanSanitizer';
  13. import { IdentifierNamesGeneratorSanitizer } from './sanitizers/IdentifierNamesGeneratorSanitizer';
  14. import { ObfuscationTargetSanitizer } from './sanitizers/ObfuscatingTargetSanitizer';
  15. import { SourceMapModeSanitizer } from './sanitizers/SourceMapModeSanitizer';
  16. import { StringArrayEncodingSanitizer } from './sanitizers/StringArrayEncodingSanitizer';
  17. import { CLIUtils } from './utils/CLIUtils';
  18. import { JavaScriptObfuscator } from '../JavaScriptObfuscatorFacade';
  19. import { SourceCodeReader } from './utils/SourceCodeReader';
  20. export class JavaScriptObfuscatorCLI implements IInitializable {
  21. /**
  22. * @type {BufferEncoding}
  23. */
  24. public static readonly encoding: BufferEncoding = 'utf8';
  25. /**
  26. * @type {string}
  27. */
  28. public static obfuscatedFilePrefix: string = '-obfuscated';
  29. /**
  30. * @type {string}
  31. */
  32. private static readonly baseIdentifiersPrefix: string = 'a';
  33. /**
  34. * @type {string[]}
  35. */
  36. private readonly arguments: string[];
  37. /**
  38. * @type {string[]}
  39. */
  40. private readonly rawArguments: string[];
  41. /**
  42. * @type {commander.CommanderStatic}
  43. */
  44. @initializable()
  45. private commands!: commander.CommanderStatic;
  46. /**
  47. * @type {TInputCLIOptions}
  48. */
  49. @initializable()
  50. private inputCLIOptions!: TInputCLIOptions;
  51. /**
  52. * @type {string}
  53. */
  54. @initializable()
  55. private inputPath!: string;
  56. /**
  57. * @param {string[]} argv
  58. */
  59. constructor (argv: string[]) {
  60. this.rawArguments = argv;
  61. this.arguments = argv.slice(2);
  62. }
  63. /**
  64. * @param {TObject} options
  65. * @returns {TInputOptions}
  66. */
  67. private static filterOptions (options: TInputCLIOptions): TInputOptions {
  68. const filteredOptions: TInputOptions = {};
  69. Object
  70. .keys(options)
  71. .forEach((option: keyof TInputCLIOptions) => {
  72. if (options[option] === undefined) {
  73. return;
  74. }
  75. filteredOptions[option] = options[option];
  76. });
  77. return filteredOptions;
  78. }
  79. /**
  80. * @param {string} sourceCode
  81. * @param {string} outputCodePath
  82. * @param {TInputOptions} options
  83. */
  84. private static processSourceCodeWithoutSourceMap (
  85. sourceCode: string,
  86. outputCodePath: string,
  87. options: TInputOptions
  88. ): void {
  89. const obfuscatedCode: string = JavaScriptObfuscator.obfuscate(sourceCode, options).getObfuscatedCode();
  90. CLIUtils.writeFile(outputCodePath, obfuscatedCode);
  91. }
  92. /**
  93. * @param {string} sourceCode
  94. * @param {string} outputCodePath
  95. * @param {TInputOptions} options
  96. */
  97. private static processSourceCodeWithSourceMap (
  98. sourceCode: string,
  99. outputCodePath: string,
  100. options: TInputOptions
  101. ): void {
  102. const outputSourceMapPath: string = CLIUtils.getOutputSourceMapPath(
  103. outputCodePath,
  104. options.sourceMapFileName || ''
  105. );
  106. options = {
  107. ...options,
  108. sourceMapFileName: path.basename(outputSourceMapPath)
  109. };
  110. const obfuscationResult: IObfuscationResult = JavaScriptObfuscator.obfuscate(sourceCode, options);
  111. CLIUtils.writeFile(outputCodePath, obfuscationResult.getObfuscatedCode());
  112. if (options.sourceMapMode === 'separate' && obfuscationResult.getSourceMap()) {
  113. CLIUtils.writeFile(outputSourceMapPath, obfuscationResult.getSourceMap());
  114. }
  115. }
  116. public initialize (): void {
  117. this.inputPath = path.normalize(this.arguments[0] || '');
  118. this.commands = <commander.CommanderStatic>(new commander.Command());
  119. this.configureCommands();
  120. this.configureHelp();
  121. this.inputCLIOptions = this.commands.opts();
  122. }
  123. public run (): void {
  124. const canShowHelp: boolean = !this.arguments.length || this.arguments.includes('--help');
  125. if (canShowHelp) {
  126. this.commands.outputHelp();
  127. return;
  128. }
  129. const sourceCodeData: TSourceCodeData = new SourceCodeReader(this.inputCLIOptions)
  130. .readSourceCode(this.inputPath);
  131. this.processSourceCodeData(sourceCodeData);
  132. }
  133. /**
  134. * @returns {TInputOptions}
  135. */
  136. private buildOptions (): TInputOptions {
  137. const inputCLIOptions: TInputOptions = JavaScriptObfuscatorCLI.filterOptions(this.inputCLIOptions);
  138. const configFilePath: string | undefined = this.inputCLIOptions.config;
  139. const configFileLocation: string = configFilePath ? path.resolve(configFilePath, '.') : '';
  140. const configFileOptions: TInputOptions = configFileLocation ? CLIUtils.getUserConfig(configFileLocation) : {};
  141. const inputFileName: string = path.basename(this.inputPath);
  142. return {
  143. ...DEFAULT_PRESET,
  144. ...configFileOptions,
  145. ...inputCLIOptions,
  146. inputFileName
  147. };
  148. }
  149. private configureCommands (): void {
  150. this.commands
  151. .usage('<inputPath> [options]')
  152. .version(
  153. process.env.VERSION || 'unknown',
  154. '-v, --version'
  155. )
  156. .option(
  157. '-o, --output <path>',
  158. 'Output path for obfuscated code'
  159. )
  160. .option(
  161. '--compact <boolean>',
  162. 'Disable one line output code compacting',
  163. BooleanSanitizer
  164. )
  165. .option(
  166. '--config <boolean>',
  167. 'Name of js / json config file'
  168. )
  169. .option(
  170. '--control-flow-flattening <boolean>',
  171. 'Enables control flow flattening',
  172. BooleanSanitizer
  173. )
  174. .option(
  175. '--control-flow-flattening-threshold <number>',
  176. 'The probability that the control flow flattening transformation will be applied to the node',
  177. parseFloat
  178. )
  179. .option(
  180. '--dead-code-injection <boolean>',
  181. 'Enables dead code injection',
  182. BooleanSanitizer
  183. )
  184. .option(
  185. '--dead-code-injection-threshold <number>',
  186. 'The probability that the dead code injection transformation will be applied to the node',
  187. parseFloat
  188. )
  189. .option(
  190. '--debug-protection <boolean>',
  191. 'Disable browser Debug panel (can cause DevTools enabled browser freeze)',
  192. BooleanSanitizer
  193. )
  194. .option(
  195. '--debug-protection-interval <boolean>',
  196. 'Disable browser Debug panel even after page was loaded (can cause DevTools enabled browser freeze)',
  197. BooleanSanitizer
  198. )
  199. .option(
  200. '--disable-console-output <boolean>',
  201. 'Allow console.log, console.info, console.error and console.warn messages output into browser console',
  202. BooleanSanitizer
  203. )
  204. .option(
  205. '--domain-lock <list> (comma separated, without whitespaces)',
  206. 'Blocks the execution of the code in domains that do not match the passed RegExp patterns (comma separated)',
  207. ArraySanitizer
  208. )
  209. .option(
  210. '--exclude <list> (comma separated, without whitespaces)',
  211. 'A filename or glob which indicates files to exclude from obfuscation',
  212. ArraySanitizer
  213. )
  214. .option(
  215. '--identifier-names-generator <string>',
  216. 'Sets identifier names generator. ' +
  217. 'Values: hexadecimal, mangled. ' +
  218. 'Default: hexadecimal',
  219. IdentifierNamesGeneratorSanitizer
  220. )
  221. .option(
  222. '--identifiers-prefix <string>',
  223. 'Sets prefix for all global identifiers.'
  224. )
  225. .option(
  226. '--log <boolean>', 'Enables logging of the information to the console',
  227. BooleanSanitizer
  228. )
  229. .option(
  230. '--reserved-names <list> (comma separated, without whitespaces)',
  231. 'Disables obfuscation and generation of identifiers, which being matched by passed RegExp patterns (comma separated)',
  232. ArraySanitizer
  233. )
  234. .option(
  235. '--reserved-strings <list> (comma separated, without whitespaces)',
  236. 'Disables transformation of string literals, which being matched by passed RegExp patterns (comma separated)',
  237. ArraySanitizer
  238. )
  239. .option(
  240. '--rename-globals <boolean>', 'Allows to enable obfuscation of global variable and function names with declaration.',
  241. BooleanSanitizer
  242. )
  243. .option(
  244. '--rotate-string-array <boolean>', 'Disable rotation of unicode array values during obfuscation',
  245. BooleanSanitizer
  246. )
  247. .option(
  248. '--seed <number>',
  249. 'Sets seed for random generator. This is useful for creating repeatable results.',
  250. parseFloat
  251. )
  252. .option(
  253. '--self-defending <boolean>',
  254. 'Disables self-defending for obfuscated code',
  255. BooleanSanitizer
  256. )
  257. .option(
  258. '--source-map <boolean>',
  259. 'Enables source map generation',
  260. BooleanSanitizer
  261. )
  262. .option(
  263. '--source-map-base-url <string>',
  264. 'Sets base url to the source map import url when `--source-map-mode=separate`'
  265. )
  266. .option(
  267. '--source-map-file-name <string>',
  268. 'Sets file name for output source map when `--source-map-mode=separate`'
  269. )
  270. .option(
  271. '--source-map-mode <string>',
  272. 'Specify source map output mode. ' +
  273. 'Values: inline, separate. ' +
  274. 'Default: separate',
  275. SourceMapModeSanitizer
  276. )
  277. .option(
  278. '--string-array <boolean>',
  279. 'Disables gathering of all literal strings into an array and replacing every literal string with an array call',
  280. BooleanSanitizer
  281. )
  282. .option(
  283. '--string-array-encoding <string|boolean>',
  284. 'Encodes all strings in strings array using base64 or rc4 (this option can slow down your code speed. ' +
  285. 'Values: true, false, base64, rc4. ' +
  286. 'Default: false',
  287. StringArrayEncodingSanitizer
  288. )
  289. .option(
  290. '--string-array-threshold <number>',
  291. 'The probability that the literal string will be inserted into stringArray (Default: 0.8, Min: 0, Max: 1)',
  292. parseFloat
  293. )
  294. .option(
  295. '--target <string>',
  296. 'Allows to set target environment for obfuscated code. ' +
  297. 'Values: browser, browser-no-eval, node. ' +
  298. 'Default: browser',
  299. ObfuscationTargetSanitizer
  300. )
  301. .option(
  302. '--transform-object-keys <boolean>',
  303. 'Enables transformation of object keys',
  304. BooleanSanitizer
  305. )
  306. .option(
  307. '--unicode-escape-sequence <boolean>',
  308. 'Allows to enable/disable string conversion to unicode escape sequence',
  309. BooleanSanitizer
  310. )
  311. .parse(this.rawArguments);
  312. }
  313. private configureHelp (): void {
  314. this.commands.on('--help', () => {
  315. console.log(' Examples:\n');
  316. console.log(' %> javascript-obfuscator input_file_name.js --compact true --self-defending false');
  317. console.log(' %> javascript-obfuscator input_file_name.js --output output_file_name.js --compact true --self-defending false');
  318. console.log(' %> javascript-obfuscator input_directory_name --compact true --self-defending false');
  319. console.log('');
  320. });
  321. }
  322. /**
  323. * @param {TSourceCodeData} sourceCodeData
  324. */
  325. private processSourceCodeData (sourceCodeData: TSourceCodeData): void {
  326. const outputPath: string = this.inputCLIOptions.output
  327. ? path.normalize(this.inputCLIOptions.output)
  328. : '';
  329. if (!Array.isArray(sourceCodeData)) {
  330. const outputCodePath: string = outputPath || CLIUtils.getOutputCodePath(this.inputPath);
  331. this.processSourceCode(sourceCodeData, outputCodePath, null);
  332. } else {
  333. sourceCodeData.forEach(({ filePath, content }: IFileData, index: number) => {
  334. const outputCodePath: string = outputPath
  335. ? path.join(outputPath, filePath)
  336. : CLIUtils.getOutputCodePath(filePath);
  337. this.processSourceCode(content, outputCodePath, index);
  338. });
  339. }
  340. }
  341. /**
  342. * @param {string} sourceCode
  343. * @param {string} outputCodePath
  344. * @param {number | null} sourceCodeIndex
  345. */
  346. private processSourceCode (
  347. sourceCode: string,
  348. outputCodePath: string,
  349. sourceCodeIndex: number | null
  350. ): void {
  351. let options: TInputOptions = this.buildOptions();
  352. if (sourceCodeIndex !== null) {
  353. const baseIdentifiersPrefix: string = this.inputCLIOptions.identifiersPrefix
  354. || JavaScriptObfuscatorCLI.baseIdentifiersPrefix;
  355. const identifiersPrefix: string = `${baseIdentifiersPrefix}${sourceCodeIndex}`;
  356. options = {
  357. ...options,
  358. identifiersPrefix
  359. };
  360. }
  361. if (options.sourceMap) {
  362. JavaScriptObfuscatorCLI.processSourceCodeWithSourceMap(sourceCode, outputCodePath, options);
  363. } else {
  364. JavaScriptObfuscatorCLI.processSourceCodeWithoutSourceMap(sourceCode, outputCodePath, options);
  365. }
  366. }
  367. }