JavaScriptObfuscatorCLI.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  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. return {
  142. ...DEFAULT_PRESET,
  143. ...configFileOptions,
  144. ...inputCLIOptions
  145. };
  146. }
  147. private configureCommands (): void {
  148. this.commands
  149. .usage('<inputPath> [options]')
  150. .version(
  151. process.env.VERSION || 'unknown',
  152. '-v, --version'
  153. )
  154. .option(
  155. '-o, --output <path>',
  156. 'Output path for obfuscated code'
  157. )
  158. .option(
  159. '--compact <boolean>',
  160. 'Disable one line output code compacting',
  161. BooleanSanitizer
  162. )
  163. .option(
  164. '--config <boolean>',
  165. 'Name of js / json config file'
  166. )
  167. .option(
  168. '--control-flow-flattening <boolean>',
  169. 'Enables control flow flattening',
  170. BooleanSanitizer
  171. )
  172. .option(
  173. '--control-flow-flattening-threshold <number>',
  174. 'The probability that the control flow flattening transformation will be applied to the node',
  175. parseFloat
  176. )
  177. .option(
  178. '--dead-code-injection <boolean>',
  179. 'Enables dead code injection',
  180. BooleanSanitizer
  181. )
  182. .option(
  183. '--dead-code-injection-threshold <number>',
  184. 'The probability that the dead code injection transformation will be applied to the node',
  185. parseFloat
  186. )
  187. .option(
  188. '--debug-protection <boolean>',
  189. 'Disable browser Debug panel (can cause DevTools enabled browser freeze)',
  190. BooleanSanitizer
  191. )
  192. .option(
  193. '--debug-protection-interval <boolean>',
  194. 'Disable browser Debug panel even after page was loaded (can cause DevTools enabled browser freeze)',
  195. BooleanSanitizer
  196. )
  197. .option(
  198. '--disable-console-output <boolean>',
  199. 'Allow console.log, console.info, console.error and console.warn messages output into browser console',
  200. BooleanSanitizer
  201. )
  202. .option(
  203. '--domain-lock <list> (comma separated, without whitespaces)',
  204. 'Blocks the execution of the code in domains that do not match the passed RegExp patterns (comma separated)',
  205. ArraySanitizer
  206. )
  207. .option(
  208. '--exclude <list> (comma separated, without whitespaces)',
  209. 'A filename or glob which indicates files to exclude from obfuscation',
  210. ArraySanitizer
  211. )
  212. .option(
  213. '--identifier-names-generator <string>',
  214. 'Sets identifier names generator. ' +
  215. 'Values: hexadecimal, mangled. ' +
  216. 'Default: hexadecimal',
  217. IdentifierNamesGeneratorSanitizer
  218. )
  219. .option(
  220. '--identifiers-prefix <string>',
  221. 'Sets prefix for all global identifiers.'
  222. )
  223. .option(
  224. '--log <boolean>', 'Enables logging of the information to the console',
  225. BooleanSanitizer
  226. )
  227. .option(
  228. '--reserved-names <list> (comma separated, without whitespaces)',
  229. 'Disables obfuscation and generation of identifiers, which being matched by passed RegExp patterns (comma separated)',
  230. ArraySanitizer
  231. )
  232. .option(
  233. '--rename-globals <boolean>', 'Allows to enable obfuscation of global variable and function names with declaration.',
  234. BooleanSanitizer
  235. )
  236. .option(
  237. '--rotate-string-array <boolean>', 'Disable rotation of unicode array values during obfuscation',
  238. BooleanSanitizer
  239. )
  240. .option(
  241. '--seed <number>',
  242. 'Sets seed for random generator. This is useful for creating repeatable results.',
  243. parseFloat
  244. )
  245. .option(
  246. '--self-defending <boolean>',
  247. 'Disables self-defending for obfuscated code',
  248. BooleanSanitizer
  249. )
  250. .option(
  251. '--source-map <boolean>',
  252. 'Enables source map generation',
  253. BooleanSanitizer
  254. )
  255. .option(
  256. '--source-map-base-url <string>',
  257. 'Sets base url to the source map import url when `--source-map-mode=separate`'
  258. )
  259. .option(
  260. '--source-map-file-name <string>',
  261. 'Sets file name for output source map when `--source-map-mode=separate`'
  262. )
  263. .option(
  264. '--source-map-mode <string>',
  265. 'Specify source map output mode. ' +
  266. 'Values: inline, separate. ' +
  267. 'Default: separate',
  268. SourceMapModeSanitizer
  269. )
  270. .option(
  271. '--string-array <boolean>',
  272. 'Disables gathering of all literal strings into an array and replacing every literal string with an array call',
  273. BooleanSanitizer
  274. )
  275. .option(
  276. '--string-array-encoding <string|boolean>',
  277. 'Encodes all strings in strings array using base64 or rc4 (this option can slow down your code speed. ' +
  278. 'Values: true, false, base64, rc4. ' +
  279. 'Default: false',
  280. StringArrayEncodingSanitizer
  281. )
  282. .option(
  283. '--string-array-threshold <number>',
  284. 'The probability that the literal string will be inserted into stringArray (Default: 0.8, Min: 0, Max: 1)',
  285. parseFloat
  286. )
  287. .option(
  288. '--target <string>',
  289. 'Allows to set target environment for obfuscated code. ' +
  290. 'Values: browser, browser-no-eval, node. ' +
  291. 'Default: browser',
  292. ObfuscationTargetSanitizer
  293. )
  294. .option(
  295. '--transform-object-keys <boolean>',
  296. 'Enables transformation of object keys',
  297. BooleanSanitizer
  298. )
  299. .option(
  300. '--unicode-escape-sequence <boolean>',
  301. 'Allows to enable/disable string conversion to unicode escape sequence',
  302. BooleanSanitizer
  303. )
  304. .parse(this.rawArguments);
  305. }
  306. private configureHelp (): void {
  307. this.commands.on('--help', () => {
  308. console.log(' Examples:\n');
  309. console.log(' %> javascript-obfuscator input_file_name.js --compact true --self-defending false');
  310. console.log(' %> javascript-obfuscator input_file_name.js --output output_file_name.js --compact true --self-defending false');
  311. console.log(' %> javascript-obfuscator input_directory_name --compact true --self-defending false');
  312. console.log('');
  313. });
  314. }
  315. /**
  316. * @param {TSourceCodeData} sourceCodeData
  317. */
  318. private processSourceCodeData (sourceCodeData: TSourceCodeData): void {
  319. const outputPath: string = this.inputCLIOptions.output
  320. ? path.normalize(this.inputCLIOptions.output)
  321. : '';
  322. if (!Array.isArray(sourceCodeData)) {
  323. const outputCodePath: string = outputPath || CLIUtils.getOutputCodePath(this.inputPath);
  324. this.processSourceCode(sourceCodeData, outputCodePath, null);
  325. } else {
  326. sourceCodeData.forEach(({ filePath, content }: IFileData, index: number) => {
  327. const outputCodePath: string = outputPath
  328. ? path.join(outputPath, filePath)
  329. : CLIUtils.getOutputCodePath(filePath);
  330. this.processSourceCode(content, outputCodePath, index);
  331. });
  332. }
  333. }
  334. /**
  335. * @param {string} sourceCode
  336. * @param {string} outputCodePath
  337. * @param {number | null} sourceCodeIndex
  338. */
  339. private processSourceCode (
  340. sourceCode: string,
  341. outputCodePath: string,
  342. sourceCodeIndex: number | null
  343. ): void {
  344. let options: TInputOptions = this.buildOptions();
  345. if (sourceCodeIndex !== null) {
  346. const baseIdentifiersPrefix: string = this.inputCLIOptions.identifiersPrefix
  347. || JavaScriptObfuscatorCLI.baseIdentifiersPrefix;
  348. const identifiersPrefix: string = `${baseIdentifiersPrefix}${sourceCodeIndex}`;
  349. options = {
  350. ...options,
  351. identifiersPrefix
  352. };
  353. }
  354. if (options.sourceMap) {
  355. JavaScriptObfuscatorCLI.processSourceCodeWithSourceMap(sourceCode, outputCodePath, options);
  356. } else {
  357. JavaScriptObfuscatorCLI.processSourceCodeWithoutSourceMap(sourceCode, outputCodePath, options);
  358. }
  359. }
  360. }