diff --git a/.eslintrc.js b/.eslintrc.js index 2e2f5f3bd..4f327033a 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -1,336 +1,292 @@ module.exports = { - "env": { - "browser": true, - "es6": true, - "node": true + env: { + browser: true, + es6: true, + node: true }, - "parser": "@typescript-eslint/parser", - "parserOptions": { - "project": "src/tsconfig.node.json", - "sourceType": "module" + parser: '@typescript-eslint/parser', + parserOptions: { + project: 'src/tsconfig.node.json', + sourceType: 'module' }, - "plugins": [ - "@typescript-eslint", - "import", - "jsdoc", - "prefer-arrow", - "unicorn" - ], - "rules": { - "@typescript-eslint/adjacent-overload-signatures": "error", - "@typescript-eslint/array-type": [ - "error", + plugins: ['@typescript-eslint', 'import', 'jsdoc', 'prefer-arrow', 'unicorn', 'prettier'], + extends: ['prettier'], + rules: { + '@typescript-eslint/adjacent-overload-signatures': 'error', + '@typescript-eslint/array-type': [ + 'error', { - "default": "array" + default: 'array' } ], - "@typescript-eslint/await-thenable": "error", - "@typescript-eslint/ban-ts-comment": "error", - "@typescript-eslint/ban-types": "off", - "@typescript-eslint/brace-style": [ - "error", - "1tbs", + '@typescript-eslint/await-thenable': 'error', + '@typescript-eslint/ban-ts-comment': 'error', + '@typescript-eslint/ban-types': 'off', + '@typescript-eslint/brace-style': 'off', + '@typescript-eslint/camelcase': 'off', + '@typescript-eslint/comma-spacing': 'error', + '@typescript-eslint/consistent-type-assertions': [ + 'error', { - "allowSingleLine": true + assertionStyle: 'angle-bracket' } ], - "@typescript-eslint/camelcase": "off", - "@typescript-eslint/comma-spacing": "error", - "@typescript-eslint/consistent-type-assertions": [ - "error", + '@typescript-eslint/consistent-type-definitions': 'error', + '@typescript-eslint/default-param-last': 'error', + '@typescript-eslint/explicit-function-return-type': 'error', + '@typescript-eslint/explicit-member-accessibility': [ + 'error', { - "assertionStyle": "angle-bracket" + accessibility: 'explicit' } ], - "@typescript-eslint/consistent-type-definitions": "error", - "@typescript-eslint/default-param-last": "error", - "@typescript-eslint/explicit-function-return-type": "error", - "@typescript-eslint/explicit-member-accessibility": [ - "error", + '@typescript-eslint/explicit-module-boundary-types': 'error', + '@typescript-eslint/func-call-spacing': 'error', + '@typescript-eslint/indent': ['off', 4], + '@typescript-eslint/member-delimiter-style': [ + 'error', { - "accessibility": "explicit" - } - ], - "@typescript-eslint/explicit-module-boundary-types": "error", - "@typescript-eslint/func-call-spacing": "error", - "@typescript-eslint/indent": [ - "off", - 4 - ], - "@typescript-eslint/member-delimiter-style": [ - "error", - { - "multiline": { - "delimiter": "semi", - "requireLast": true + multiline: { + delimiter: 'semi', + requireLast: true }, - "singleline": { - "delimiter": "semi", - "requireLast": false + singleline: { + delimiter: 'semi', + requireLast: false } } ], - "@typescript-eslint/member-ordering": "error", - "@typescript-eslint/naming-convention": [ - "error", + '@typescript-eslint/member-ordering': 'error', + '@typescript-eslint/naming-convention': [ + 'error', { - "selector": "default", - "format": ["camelCase", "PascalCase"] + selector: 'default', + format: ['camelCase', 'PascalCase'] }, { - "selector": "variable", - "format": ["camelCase", "PascalCase", "UPPER_CASE"] + selector: 'variable', + format: ['camelCase', 'PascalCase', 'UPPER_CASE'] }, { - "selector": "function", - "format": ["camelCase", "PascalCase"] + selector: 'function', + format: ['camelCase', 'PascalCase'] }, { - "selector": "class", - "format": ["PascalCase"] + selector: 'class', + format: ['PascalCase'] }, { - "selector": "interface", - "format": ["PascalCase"], - "prefix": ["I"] + selector: 'interface', + format: ['PascalCase'], + prefix: ['I'] }, { - "selector": "typeAlias", - "format": ["PascalCase"], - "prefix": ["T"] + selector: 'typeAlias', + format: ['PascalCase'], + prefix: ['T'] }, { - "selector": "typeParameter", - "format": ["PascalCase"] + selector: 'typeParameter', + format: ['PascalCase'] }, { - "selector": "enum", - "format": ["PascalCase"] + selector: 'enum', + format: ['PascalCase'] }, { - "selector": "enumMember", - "format": null + selector: 'enumMember', + format: null }, { - "selector": "property", - "format": ["camelCase", "PascalCase", "snake_case"] + selector: 'property', + format: ['camelCase', 'PascalCase', 'snake_case'] } ], - "@typescript-eslint/no-empty-function": "off", - "@typescript-eslint/no-empty-interface": "error", - "@typescript-eslint/no-explicit-any": "off", - "@typescript-eslint/no-extra-parens": "off", - "@typescript-eslint/no-floating-promises": "error", - "@typescript-eslint/no-for-in-array": "error", - "@typescript-eslint/no-inferrable-types": "off", - "@typescript-eslint/no-magic-numbers": "off", - "@typescript-eslint/no-misused-new": "error", - "@typescript-eslint/no-namespace": "error", - "@typescript-eslint/no-non-null-asserted-optional-chain": "error", - "@typescript-eslint/no-non-null-assertion": "error", - "@typescript-eslint/no-param-reassign": "off", - "@typescript-eslint/no-parameter-properties": "error", - "@typescript-eslint/no-require-imports": "off", - "@typescript-eslint/no-shadow": "error", - "@typescript-eslint/no-this-alias": "error", - "@typescript-eslint/no-unnecessary-qualifier": "error", - "@typescript-eslint/no-unnecessary-type-arguments": "error", - "@typescript-eslint/no-unnecessary-type-assertion": "error", - "@typescript-eslint/no-unused-expressions": "error", - "@typescript-eslint/no-use-before-define": "off", - "@typescript-eslint/no-var-requires": "error", - "@typescript-eslint/prefer-for-of": "error", - "@typescript-eslint/prefer-function-type": "error", - "@typescript-eslint/prefer-namespace-keyword": "error", - "@typescript-eslint/prefer-nullish-coalescing": "error", - "@typescript-eslint/prefer-optional-chain": "error", - "@typescript-eslint/prefer-readonly": "error", - "@typescript-eslint/promise-function-async": "error", - "@typescript-eslint/quotes": [ - "error", - "single" - ], - "@typescript-eslint/require-array-sort-compare": "error", - "@typescript-eslint/restrict-plus-operands": "error", - "@typescript-eslint/semi": [ - "error", - "always" - ], - "@typescript-eslint/space-before-function-paren": "error", - "@typescript-eslint/strict-boolean-expressions": "off", - "@typescript-eslint/triple-slash-reference": "error", - "@typescript-eslint/type-annotation-spacing": "error", - "@typescript-eslint/typedef": "error", - "@typescript-eslint/unified-signatures": "error", - "arrow-body-style": "off", - "arrow-parens": [ - "off", - "as-needed" - ], - "brace-style": "off", - "capitalized-comments": "off", - "comma-dangle": "off", - "comma-spacing": "off", - "complexity": [ - "error", + '@typescript-eslint/no-empty-function': 'off', + '@typescript-eslint/no-empty-interface': 'error', + '@typescript-eslint/no-explicit-any': 'off', + '@typescript-eslint/no-extra-parens': 'off', + '@typescript-eslint/no-floating-promises': 'error', + '@typescript-eslint/no-for-in-array': 'error', + '@typescript-eslint/no-inferrable-types': 'off', + '@typescript-eslint/no-magic-numbers': 'off', + '@typescript-eslint/no-misused-new': 'error', + '@typescript-eslint/no-namespace': 'error', + '@typescript-eslint/no-non-null-asserted-optional-chain': 'error', + '@typescript-eslint/no-non-null-assertion': 'off', + '@typescript-eslint/no-param-reassign': 'off', + '@typescript-eslint/parameter-properties': 'error', + '@typescript-eslint/no-require-imports': 'off', + '@typescript-eslint/no-shadow': 'error', + '@typescript-eslint/no-this-alias': 'error', + '@typescript-eslint/no-unnecessary-qualifier': 'error', + '@typescript-eslint/no-unnecessary-type-arguments': 'error', + '@typescript-eslint/no-unnecessary-type-assertion': 'error', + '@typescript-eslint/no-unused-expressions': 'error', + '@typescript-eslint/no-use-before-define': 'off', + '@typescript-eslint/no-var-requires': 'error', + '@typescript-eslint/prefer-for-of': 'error', + '@typescript-eslint/prefer-function-type': 'error', + '@typescript-eslint/prefer-namespace-keyword': 'error', + '@typescript-eslint/prefer-nullish-coalescing': 'error', + '@typescript-eslint/prefer-optional-chain': 'error', + '@typescript-eslint/prefer-readonly': 'error', + '@typescript-eslint/promise-function-async': 'error', + '@typescript-eslint/quotes': ['error', 'single', { avoidEscape: true }], + '@typescript-eslint/require-array-sort-compare': 'error', + '@typescript-eslint/restrict-plus-operands': 'error', + '@typescript-eslint/semi': ['error', 'always'], + '@typescript-eslint/space-before-function-paren': 'off', + '@typescript-eslint/strict-boolean-expressions': 'off', + '@typescript-eslint/triple-slash-reference': 'error', + '@typescript-eslint/type-annotation-spacing': 'error', + '@typescript-eslint/typedef': 'error', + '@typescript-eslint/unified-signatures': 'error', + 'arrow-body-style': 'off', + 'arrow-parens': ['off', 'as-needed'], + 'brace-style': 'off', + 'capitalized-comments': 'off', + 'comma-dangle': 'off', + 'comma-spacing': 'off', + 'complexity': [ + 'error', { - "max": 10 + max: 10 } ], - "constructor-super": "error", - "curly": "error", - "default-case": "off", - "dot-notation": "error", - "eol-last": "error", - "eqeqeq": [ - "error", - "smart" - ], - "func-call-spacing": "off", - "guard-for-in": "error", - "id-blacklist": "off", - "id-match": "off", - "import/export": "error", - "import/first": "error", - "import/newline-after-import": "error", - "import/no-absolute-path": "error", - "import/no-cycle": "error", - "import/no-default-export": "error", - "import/no-deprecated": "error", - "import/no-extraneous-dependencies": "error", - "import/no-internal-modules": "error", - "import/no-mutable-exports": "error", - "import/no-unassigned-import": "off", - "import/no-useless-path-segments": "error", - "import/order": "off", - "indent": "off", - "jsdoc/no-types": "off", - "linebreak-style": "off", - "max-classes-per-file": [ - "error", - 1 - ], - "max-len": "off", - "max-lines": [ - "error", - 500 - ], - "new-parens": "error", - "newline-per-chained-call": "off", - "no-bitwise": "off", - "no-caller": "error", - "no-cond-assign": "error", - "no-console": [ - "error", + 'constructor-super': 'error', + 'curly': 'error', + 'default-case': 'off', + 'dot-notation': 'error', + 'eol-last': 'error', + 'eqeqeq': ['error', 'smart'], + 'func-call-spacing': 'off', + 'guard-for-in': 'error', + 'id-blacklist': 'off', + 'id-match': 'off', + 'import/export': 'error', + 'import/first': 'error', + 'import/newline-after-import': 'error', + 'import/no-absolute-path': 'error', + 'import/no-cycle': 'error', + 'import/no-default-export': 'error', + 'import/no-deprecated': 'error', + 'import/no-extraneous-dependencies': 'error', + 'import/no-internal-modules': 'error', + 'import/no-mutable-exports': 'error', + 'import/no-unassigned-import': 'off', + 'import/no-useless-path-segments': 'error', + 'import/order': 'off', + 'indent': 'off', + 'jsdoc/no-types': 'off', + 'linebreak-style': 'off', + 'max-classes-per-file': ['error', 1], + 'max-len': 'off', + 'max-lines': ['error', { max: 500, skipComments: true }], + 'new-parens': 'error', + 'newline-per-chained-call': 'off', + 'no-bitwise': 'off', + 'no-caller': 'error', + 'no-cond-assign': 'error', + 'no-console': [ + 'error', { - "allow": [ - "log", - "warn", - "dir", - "timeLog", - "assert", - "clear", - "count", - "countReset", - "group", - "groupEnd", - "table", - "dirxml", - "error", - "groupCollapsed", - "Console", - "profile", - "profileEnd", - "timeStamp", - "context" + allow: [ + 'log', + 'warn', + 'dir', + 'timeLog', + 'assert', + 'clear', + 'count', + 'countReset', + 'group', + 'groupEnd', + 'table', + 'dirxml', + 'error', + 'groupCollapsed', + 'Console', + 'profile', + 'profileEnd', + 'timeStamp', + 'context' ] } ], - "no-constant-condition": "error", - "no-control-regex": "off", - "no-debugger": "error", - "no-duplicate-case": "error", - "no-duplicate-imports": "error", - "no-empty": "off", - "no-eval": "off", - "no-extra-bind": "error", - "no-extra-parens": "off", - "no-extra-semi": "error", - "no-fallthrough": "error", - "no-invalid-regexp": "error", - "no-invalid-this": "off", - "no-irregular-whitespace": "error", - "no-magic-numbers": "off", - "no-multi-str": "error", - "no-multiple-empty-lines": "error", - "no-new-wrappers": "error", - "no-null/no-null": "off", - "no-octal": "error", - "no-octal-escape": "error", - "no-redeclare": "error", - "no-regex-spaces": "error", - "no-restricted-syntax": [ - "error", - "ForInStatement" - ], - "no-return-await": "error", - "no-sequences": "error", - "no-shadow": "off", - "no-sparse-arrays": "error", - "no-template-curly-in-string": "error", - "no-throw-literal": "error", - "no-trailing-spaces": [ - "error", + 'no-constant-condition': 'error', + 'no-control-regex': 'off', + 'no-debugger': 'error', + 'no-duplicate-case': 'error', + 'no-duplicate-imports': 'error', + 'no-empty': 'off', + 'no-eval': 'off', + 'no-extra-bind': 'error', + 'no-extra-parens': 'off', + 'no-extra-semi': 'error', + 'no-fallthrough': 'error', + 'no-invalid-regexp': 'error', + 'no-invalid-this': 'off', + 'no-irregular-whitespace': 'error', + 'no-magic-numbers': 'off', + 'no-multi-str': 'error', + 'no-multiple-empty-lines': 'error', + 'no-new-wrappers': 'error', + 'no-null/no-null': 'off', + 'no-octal': 'error', + 'no-octal-escape': 'error', + 'no-redeclare': 'error', + 'no-regex-spaces': 'error', + 'no-restricted-syntax': ['error', 'ForInStatement'], + 'no-return-await': 'error', + 'no-sequences': 'error', + 'no-shadow': 'off', + 'no-sparse-arrays': 'error', + 'no-template-curly-in-string': 'error', + 'no-throw-literal': 'error', + 'no-trailing-spaces': [ + 'error', { - "skipBlankLines": true + skipBlankLines: true } ], - "no-undef-init": "error", - "no-underscore-dangle": "off", - "no-unsafe-finally": "error", - "no-unused-expressions": "off", - "no-unused-labels": "error", - "no-var": "error", - "no-void": "error", - "object-shorthand": "off", - "one-var": [ - "error", - "never" - ], - "padding-line-between-statements": [ - "error", + 'no-undef-init': 'error', + 'no-underscore-dangle': 'off', + 'no-unsafe-finally': 'error', + 'no-unused-expressions': 'off', + 'no-unused-labels': 'error', + 'no-var': 'error', + 'no-void': 'error', + 'object-shorthand': 'off', + 'one-var': ['error', 'never'], + 'padding-line-between-statements': [ + 'error', { - "blankLine": "always", - "prev": "*", - "next": "return" + blankLine: 'always', + prev: '*', + next: 'return' } ], - "prefer-arrow/prefer-arrow-functions": "off", - "prefer-const": "error", - "prefer-object-spread": "error", - "prefer-template": "error", - "quote-props": [ - "error", - "as-needed" - ], - "quotes": "off", - "radix": "error", - "space-before-function-paren": "off", - "spaced-comment": "error", - "space-in-parens": [ - "error", - "never" - ], - "unicorn/catch-error-name": [ - "error", + 'prefer-arrow/prefer-arrow-functions': 'off', + 'prefer-const': 'error', + 'prefer-object-spread': 'error', + 'prefer-template': 'error', + 'quote-props': ['off', 'as-needed'], + 'quotes': 'off', + 'radix': 'error', + 'space-before-function-paren': 'off', + 'spaced-comment': 'error', + 'space-in-parens': ['error', 'never'], + 'unicorn/catch-error-name': [ + 'error', { - "name": "error" + name: 'error' } ], - "unicorn/no-nested-ternary": "error", - "unicorn/no-unreadable-array-destructuring": "error", - "unicorn/numeric-separators-style": [ - "error", + 'unicorn/no-nested-ternary': 'off', + 'unicorn/no-unreadable-array-destructuring': 'error', + 'unicorn/numeric-separators-style': [ + 'error', { number: { minimumDigits: 7, @@ -338,15 +294,15 @@ module.exports = { } } ], - "unicorn/prefer-array-find": "error", - "unicorn/prefer-includes": "error", - "unicorn/prefer-optional-catch-binding": "error", - "unicorn/prefer-starts-ends-with": "error", - "unicorn/prefer-set-has": "error", - "unicorn/prefer-string-slice": "error", - "unicorn/prefer-string-trim-start-end": "error", - "use-isnan": "error", - "valid-typeof": "error", - "yoda": "error" + 'unicorn/prefer-array-find': 'error', + 'unicorn/prefer-includes': 'error', + 'unicorn/prefer-optional-catch-binding': 'error', + 'unicorn/prefer-starts-ends-with': 'error', + 'unicorn/prefer-set-has': 'error', + 'unicorn/prefer-string-slice': 'error', + 'unicorn/prefer-string-trim-start-end': 'error', + 'use-isnan': 'error', + 'valid-typeof': 'error', + 'yoda': 'error' } }; diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md index b5c3667ec..6566c0260 100644 --- a/.github/ISSUE_TEMPLATE.md +++ b/.github/ISSUE_TEMPLATE.md @@ -17,7 +17,10 @@ 1. 2. 3. -4. + +## JavaScript Obfuscator Edition +- JavaScript Obfuscator Open Source +- JavaScript Obfuscator Pro via API or [http://obfuscator.io](http://obfuscator.io]) ## Your Environment diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index dbedc7c35..e422999f9 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -24,7 +24,10 @@ assignees: '' 1. 2. 3. -4. + +## JavaScript Obfuscator Edition +- JavaScript Obfuscator Open Source +- JavaScript Obfuscator Pro via API or [http://obfuscator.io](http://obfuscator.io]) ## Your Environment diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e45571de4..9f85a9b02 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2,9 +2,9 @@ name: JavaScript Obfuscator CI on: push: - branches: [master] + branches: [master, release-**] pull_request: - branches: [master] + branches: [master, release-**] schedule: - cron: '0 1 * * *' @@ -17,34 +17,50 @@ jobs: matrix: include: - os: ubuntu-latest, - node-version: 14.x + node-version: 20.x - os: ubuntu-latest, - node-version: 16.x + node-version: 22.x - os: ubuntu-latest, - node-version: 18.x + node-version: 24.x - os: windows-latest, - node-version: 16.x + node-version: 20.x - os: windows-latest, - node-version: 18.x + node-version: 22.x + - os: windows-latest, + node-version: 24.x steps: - - uses: actions/checkout@v2 - - uses: styfle/cancel-workflow-action@0.6.0 + - uses: actions/checkout@v4 + - uses: styfle/cancel-workflow-action@0.12.1 with: access_token: ${{ github.token }} - name: Use Node.js ${{ matrix.node-version }} - uses: actions/setup-node@v1 + uses: actions/setup-node@v4 with: node-version: ${{ matrix.node-version }} - - uses: actions/cache@v2 + - uses: actions/cache@v4 with: path: '**/node_modules' key: ${{ runner.os }}-modules-${{ hashFiles('**/yarn.lock') }} - run: yarn install - run: yarn run build + - run: yarn run test:mocha-coverage - run: yarn run test:mocha-coverage:report - name: Coveralls - uses: coverallsapp/github-action@master + uses: coverallsapp/github-action@v2 + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + path-to-lcov: './coverage/lcov.info' + parallel: true + flag-name: node-${{ matrix.node-version }}-${{ matrix.os }} + + coveralls-finish: + needs: build + if: always() + runs-on: ubuntu-latest + steps: + - name: Coveralls Finished + uses: coverallsapp/github-action@v2 with: github-token: ${{ secrets.GITHUB_TOKEN }} - path-to-lcov: './coverage/lcov.info' \ No newline at end of file + parallel-finished: true \ No newline at end of file diff --git a/.gitignore b/.gitignore index b79ba16a5..ac8242982 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ +.claude .DS_Store .idea .nyc_output @@ -13,3 +14,4 @@ npm-debug.log /test/benchmark/**/** *dockerfile /test*.js +/reproductions diff --git a/.mocharc.json b/.mocharc.json index 0ca796a9e..a854da57e 100644 --- a/.mocharc.json +++ b/.mocharc.json @@ -1,3 +1,3 @@ { - "node-option": ["experimental-specifier-resolution=node", "loader=ts-node/esm"] + "node-option": [] } \ No newline at end of file diff --git a/.npmignore b/.npmignore index 217c06850..2157c5a98 100644 --- a/.npmignore +++ b/.npmignore @@ -1,4 +1,5 @@ .awcache +.claude .github .idea .nyc_output @@ -9,3 +10,6 @@ /src/ /test/ /test*.js +index.ts +index.cli.ts +/reproductions \ No newline at end of file diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 000000000..859bd06b4 --- /dev/null +++ b/.prettierignore @@ -0,0 +1,34 @@ +# Dependencies +node_modules + +# Build output +dist +*.browser.js + +# Coverage +coverage +.nyc_output + +# Type definitions +typings + +# Webpack bundles +webpack + +# Lock files +package-lock.json +yarn.lock + +# Logs +*.log + +# Temporary files +*.tmp +.DS_Store + +# Test fixtures and expected output +test/**/*.expected.js +test/**/*.fixture.js + +# Templates (custom code helpers - these are code templates, not regular code) +src/custom-code-helpers/**/templates/*.ts diff --git a/.prettierrc.js b/.prettierrc.js new file mode 100644 index 000000000..09aeed300 --- /dev/null +++ b/.prettierrc.js @@ -0,0 +1,50 @@ +module.exports = { + // Basic formatting + printWidth: 120, + tabWidth: 4, + useTabs: false, + semi: true, + singleQuote: true, + quoteProps: 'consistent', + trailingComma: 'none', + + // Spacing + bracketSpacing: true, + arrowParens: 'always', + + // Line breaks + endOfLine: 'lf', + + // TypeScript + parser: 'typescript', + + // Override for specific file types + overrides: [ + { + files: '*.ts', + options: { + parser: 'typescript' + } + }, + { + files: '*.js', + options: { + parser: 'babel' + } + }, + { + files: '*.json', + options: { + parser: 'json', + tabWidth: 2 + } + }, + { + files: '*.md', + options: { + parser: 'markdown', + proseWrap: 'preserve' + } + } + ] +}; diff --git a/CHANGELOG.md b/CHANGELOG.md index 279789018..b173fb420 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,124 @@ Change Log +v5.5.0 +--- +* Pro API: reworked large file uploads — fixed `413 Content Too Large` for ~4.4–4.6MB request bodies, and Blob uploads now send the raw source (`blobFormat: 'raw'`) instead of the JSON request body, so uploads always fit the plan's file size cap + +v5.4.7 +--- +* Fixed directory obfuscation with a set `sourceMapFileName` making all files share and overwrite one `.map`. Fixes https://github.com/javascript-obfuscator/javascript-obfuscator/issues/817 +* Fixed CLI `--config` failures hiding the real cause behind a generic `Cannot open config file` message. Fixes https://github.com/javascript-obfuscator/javascript-obfuscator/issues/1101 +* Fixed `sourceMapFileName` ending in `.js.map` (e.g. `foo.min.js.map`) being mangled in the emitted `//# sourceMappingURL=` comment. Fixes https://github.com/javascript-obfuscator/javascript-obfuscator/issues/1312 +* Fixed `URIError: URI malformed` crash when `stringArray` with `base64`/`rc4` encoding processed a string literal containing lone surrogate code units (e.g. `"[^\uD800-\uDFFF]"`). Fixes https://github.com/javascript-obfuscator/javascript-obfuscator/issues/1431 +* Bumped the production `brace-expansion` transitive dependency to a patched version, resolving `CVE-2026-25547`. Fixes https://github.com/javascript-obfuscator/javascript-obfuscator/issues/1405 + +v5.4.6 +--- +* Fixed unicode (`\uXXXX`, `\u{XXXX}`) and hex (`\xXX`) escape sequences of string literals being un-escaped into their literal characters during obfuscation. Fixes https://github.com/javascript-obfuscator/javascript-obfuscator/issues/345 + +v5.4.5 +--- +* Fixed `controlFlowFlattening` intermittently dropping arguments of a spread call (e.g. `foo(...args)`) when it reused a control flow wrapper of a same-arity plain call. Fixes https://github.com/javascript-obfuscator/javascript-obfuscator/issues/1423 +* Fixed `selfDefending` making obfuscated code run several times slower on Bun/JavaScriptCore. Fixes https://github.com/javascript-obfuscator/javascript-obfuscator/issues/1421 +* Fixed dropped parentheses around an `in` operator inside an arrow body in a `for`-init, producing unparsable output. Fixes https://github.com/javascript-obfuscator/javascript-obfuscator/issues/1419 + +v5.4.4 +--- +* Optimized scope identifiers transformer performance +* Optimized identifier renaming performance by reusing scope analysis between transformers +* Fixed `Invalid regular expression` error when obfuscating code that uses ES2025 RegExp pattern modifiers (e.g. `/(?i:abc)/`). Fixes https://github.com/javascript-obfuscator/javascript-obfuscator/issues/1410 +* Fixed `SyntaxError` when obfuscating a class that extends a boolean literal (e.g. `class C extends true {}`). Fixes https://github.com/javascript-obfuscator/javascript-obfuscator/issues/1131 + +v5.4.3 +--- +* Fixed `controlFlowFlattening` occasionally dropping the `?.` short-circuit on `foo?.(arg)` calls, causing `TypeError: is not a function`. Fixes https://github.com/javascript-obfuscator/javascript-obfuscator/issues/1408 + +v5.4.2 +--- +* Fixed obfuscated code hanging in Bun when `selfDefending` is enabled. Fixes https://github.com/javascript-obfuscator/javascript-obfuscator/issues/1404 + +v5.4.1 +--- +* Fixed `Utils.nodeRequire` causing `ReferenceError: require is not defined` in browser build by making it lazy-evaluated +* Fixed missing space between keywords (`return`, `throw`, `typeof`) and Unicode surrogate pair identifiers in compact mode. Fixes https://github.com/javascript-obfuscator/javascript-obfuscator/issues/1112 +* Fixed `domainLock` being case-sensitive — domain values are now normalized to lowercase. Fixes https://github.com/javascript-obfuscator/javascript-obfuscator/issues/1182 +* Removed `source-map-support` runtime dependency. Use `node --enable-source-maps` instead. Fixes https://github.com/javascript-obfuscator/javascript-obfuscator/issues/1149 + +v5.4.0 +--- +* Add support for `import attributes`. Fixes https://github.com/javascript-obfuscator/javascript-obfuscator/issues/1256 +* Add `renameProperties` support for private class fields and methods (`#foo`, `#bar()`). Fixes https://github.com/javascript-obfuscator/javascript-obfuscator/issues/1220 +* Fixed `reservedNames` not preserving class method and property names when `stringArray` or `deadCodeInjection` is enabled. Fixes https://github.com/javascript-obfuscator/javascript-obfuscator/issues/1279 +* Fixed infinite loop / stack overflow when `reservedNames` patterns match all generated identifier names. Now throws a descriptive error instead. Fixes https://github.com/javascript-obfuscator/javascript-obfuscator/issues/1382 +* Fixed `transformObjectKeys` changing evaluation order when object expression is inside a sequence expression with preceding side effects (e.g. `return aux(ys), { min }`). Fixes https://github.com/javascript-obfuscator/javascript-obfuscator/issues/1246 +* Fixed destructuring patterns inside class static blocks not being renamed when `renameGlobals` is disabled. Fixes https://github.com/javascript-obfuscator/javascript-obfuscator/issues/1141 +* Fixed CLI `--options-preset` not applying preset values for options not explicitly set via command line (e.g. `splitStrings` from `high-obfuscation` preset was ignored). Fixes https://github.com/javascript-obfuscator/javascript-obfuscator/issues/1236 +* Replaced `mkdirp` dependency with native `fs.mkdirSync({ recursive: true })`. Fixes https://github.com/javascript-obfuscator/javascript-obfuscator/issues/1275. Thank you https://github.com/roli-lpci! +* Updated reserved DOM properties list, fixing `renameProperties` breaking modern built-in methods like `Array.prototype.at()`. Fixes https://github.com/javascript-obfuscator/javascript-obfuscator/issues/1066 +* Replaced `conf` dependency with custom implementation using `env-paths` and native `fs` + +v5.3.1 +--- +* Fixed class expression name references inside class body being incorrectly resolved to an import binding with the same name, causing broken code at runtime. Fixes https://github.com/javascript-obfuscator/javascript-obfuscator/issues/1386 + +v5.3.0 +--- +* Add Pro API support to CLI +* Add large files upload support to Pro API + +v5.2.1 +--- +* Fixed `transformObjectKeys` incorrectly hoisting object literal outside of loop when loop body is a single statement without braces, causing all iterations to share the same object reference. Fixes https://github.com/javascript-obfuscator/javascript-obfuscator/issues/1300 +* Fixed parsing error when `await` is used as an identifier in non-async context. Fixes https://github.com/javascript-obfuscator/javascript-obfuscator/issues/1127 +* Fixed `deadCodeInjection` causing SyntaxError when `arguments` from collected block statements was injected into class field initializers or static initialization blocks. Fixes https://github.com/javascript-obfuscator/javascript-obfuscator/issues/1166 +* Fixed `transformObjectKeys` with `mangled` identifier generator causing variable shadowing when extracted object variable name matched an existing inner scope variable. Fixes https://github.com/javascript-obfuscator/javascript-obfuscator/issues/1232 + +v5.2.0 +--- +* Skip obfuscation of `process.env.*` +* Fixed `controlFlowFlattening` breaking short-circuit evaluation with spread operator and conditional objects. Fixes https://github.com/javascript-obfuscator/javascript-obfuscator/issues/1372 +* Fix Annex B function hoisting: block-scoped function declarations are now correctly linked to references outside the block in non-strict mode +* Fixed `NodeUtils.cloneRecursive` corrupting `range` property when cloning AST nodes, causing scope analysis to incorrectly resolve destructuring default parameter references + +v5.1.0 +--- +* Add `version` parameter to the `apiConfig` to use different versions JavaScript Obfuscator Pro via API + +v5.0.1 +--- +* Add JavaScript Obfuscator PRO advertisement message + +v5.0.0 +--- +* Add JavaScript Obfuscator PRO support via calling its API + +v4.2.1 +--- +* Downgrade `multimatch` version to avoid esm errors + +v4.2.0 +--- +* Dropped support of Node versions 17 and below +* Fix `transformObjectKeys` performance in some edge-cases +* Fix `controlFlowFlattening` + optional chaining compatibility. Fixes https://github.com/javascript-obfuscator/javascript-obfuscator/issues/1325 +* Don't obfuscate import.meta.*. Fixes https://github.com/javascript-obfuscator/javascript-obfuscator/issues/1267 +* Revert `Improved stringArray calls wrapper templates` commit. Fixes https://github.com/javascript-obfuscator/javascript-obfuscator/issues/1330 +* Fix error when ClassExpression is the CallExpression callee. Fixes https://github.com/javascript-obfuscator/javascript-obfuscator/issues/1132 +* Don't publish root index.ts files to NPM. Fixes https://github.com/javascript-obfuscator/javascript-obfuscator/issues/1252 +* Update `class-validator` version. Fixes https://github.com/javascript-obfuscator/javascript-obfuscator/issues/1324 +* Update other dependencies +* CLI: support `.mjs` and `.cjs` extensions. Kudos to https://github.com/javascript-obfuscator/javascript-obfuscator/pull/1301 + +v4.1.1 +--- +* Update supported Node.js versions up to `node@22`. Fixes https://github.com/javascript-obfuscator/javascript-obfuscator/pull/1100 +* Update `class-validator` version. Fixes https://github.com/javascript-obfuscator/javascript-obfuscator/issues/1247 +* Fixed CI + +v4.1.0 +--- +* Add target `service-worker` + v4.0.2 --- * Add support for `node@18` @@ -934,4 +1053,4 @@ v0.7.0-dev.1 * **Breaking API change:** now `obfuscate(sourceCode, options)` returns `ObfuscationResult` object instead `string`. `ObfuscationResult` object contains two public methods: `getObfuscatedCode()` and `getSourceMap()`. * CLI. Now any code can be obfuscated through CLI `javascript-obfuscator` command. See `README.md` for available options. * New option `sourceMap` enables source map generation for obfuscated code. -* New option `sourceMapMode` specifies source map generation mode. \ No newline at end of file +* New option `sourceMapMode` specifies source map generation mode. diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 000000000..b22d6d98c --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,1503 @@ +# JavaScript Obfuscator - Project Documentation + +## Project Overview + +**JavaScript Obfuscator** is a powerful, enterprise-grade code obfuscation tool for JavaScript and Node.js applications. It transforms readable JavaScript code into a protected, difficult-to-understand format while maintaining full functionality. The project is widely used for protecting intellectual property and preventing reverse engineering. + +- **Version**: 5.0.0 +- **Author**: Timofei Kachalov (@sanex3339) +- **License**: BSD-2-Clause +- **Repository**: https://github.com/javascript-obfuscator/javascript-obfuscator +- **Homepage**: https://obfuscator.io/ +- **Node Requirement**: >=18.0.0 + +## Key Features + +### Core Obfuscation Techniques + +1. **Variable & Function Renaming**: Replaces identifiable names with cryptic hexadecimal or mangled identifiers +2. **String Extraction & Encryption**: Moves string literals to an encoded array with base64/rc4 encryption +3. **Dead Code Injection**: Inserts non-functional code blocks to confuse static analysis +4. **Control Flow Flattening**: Restructures code flow using switch statements to obscure logic +5. **Code Transformations**: Multiple AST-level transformations including: + - Boolean literal obfuscation + - Number to expression conversion + - Object key transformation + - Template literal transformation + - Property renaming (safe/unsafe modes) + +### Advanced Protection Features + +- **Self-Defending Code**: Code that breaks when beautified or modified +- **Debug Protection**: Anti-debugging mechanisms to prevent DevTools usage +- **Domain Lock**: Restricts code execution to specific domains/subdomains +- **Console Output Disabling**: Removes console.* functionality +- **Unicode Escape Sequences**: Additional string obfuscation layer + +## Architecture Overview + +### Technology Stack + +- **Language**: TypeScript 4.9.5 +- **Parser**: Acorn 8.8.2 (ES3-ES2020 support) +- **Code Generator**: @javascript-obfuscator/escodegen 2.3.0 +- **AST Traversal**: @javascript-obfuscator/estraverse 5.4.0 +- **DI Framework**: InversifyJS 7.10.8 +- **Testing**: Mocha 10.4.0 + Chai 4.3.7 +- **Build System**: Webpack 5.75.0 + +### Project Structure + +``` +javascript-obfuscator/ +├── src/ # Source code +│ ├── JavaScriptObfuscator.ts # Main obfuscator class +│ ├── JavaScriptObfuscatorFacade.ts # Public API facade +│ ├── JavaScriptObfuscatorCLIFacade.ts # CLI interface +│ ├── ASTParserFacade.ts # AST parsing wrapper +│ │ +│ ├── analyzers/ # Code analysis components +│ │ ├── calls-graph-analyzer/ # Function call graph analysis +│ │ ├── scope-analyzer/ # Variable scope analysis +│ │ ├── string-array-storage-analyzer/ # String array optimization +│ │ ├── number-numerical-expression-analyzer/ +│ │ └── prevailing-kind-of-variables-analyzer/ +│ │ +│ ├── node-transformers/ # AST transformation pipeline +│ │ ├── AbstractNodeTransformer.ts +│ │ ├── NodeTransformersRunner.ts +│ │ ├── converting-transformers/ # Node type conversions +│ │ ├── control-flow-transformers/ # Control flow flattening +│ │ ├── dead-code-injection-transformers/ # Dead code generation +│ │ ├── finalizing-transformers/ # Post-processing transforms +│ │ ├── initializing-transformers/ # Pre-processing transforms +│ │ ├── preparing-transformers/ # Preparation phase +│ │ ├── rename-identifiers-transformers/ # Variable renaming +│ │ ├── rename-properties-transformers/ # Property renaming +│ │ ├── simplifying-transformers/ # Code simplification +│ │ └── string-array-transformers/ # String array handling +│ │ +│ ├── code-transformers/ # Code-level (not AST) transformers +│ │ ├── AbstractCodeTransformer.ts +│ │ ├── CodeTransformersRunner.ts +│ │ └── CodeTransformerNamesGroupsBuilder.ts +│ │ +│ ├── custom-code-helpers/ # Injectable code helpers +│ │ ├── common/ # Global variable templates +│ │ ├── console-output/ # Console disabling templates +│ │ ├── debug-protection/ # Anti-debugging templates +│ │ ├── domain-lock/ # Domain restriction templates +│ │ ├── self-defending/ # Self-defense templates +│ │ └── string-array/ # String array wrapper templates +│ │ +│ ├── custom-nodes/ # Custom AST node generators +│ │ ├── control-flow-flattening-nodes/ +│ │ ├── dead-code-injection-nodes/ +│ │ ├── object-expression-keys-transformer-nodes/ +│ │ └── string-array-nodes/ +│ │ +│ ├── container/ # Dependency injection +│ │ ├── InversifyContainerFacade.ts +│ │ ├── ServiceIdentifiers.ts +│ │ └── modules/ # DI module definitions +│ │ +│ ├── options/ # Configuration system +│ │ ├── Options.ts +│ │ ├── OptionsNormalizer.ts +│ │ ├── validators/ # Option validation +│ │ ├── normalizer-rules/ # Option normalization +│ │ └── presets/ # Obfuscation presets +│ │ +│ ├── storages/ # Data storage components +│ │ ├── string-array-transformers/ +│ │ ├── control-flow-transformers/ +│ │ ├── custom-code-helpers/ +│ │ └── identifier-names-cache/ +│ │ +│ ├── node/ # AST node utilities +│ │ ├── NodeGuards.ts # Type guards +│ │ ├── NodeFactory.ts # Node creation +│ │ ├── NodeAppender.ts # Node insertion +│ │ ├── NodeStatementUtils.ts +│ │ └── NodeUtils.ts +│ │ +│ ├── generators/ # Name/value generators +│ │ ├── identifier-names-generators/ +│ │ └── string-array-index-nodes-generators/ +│ │ +│ ├── utils/ # Utility functions +│ │ ├── RandomGenerator.ts +│ │ ├── ArrayUtils.ts +│ │ ├── CryptUtils.ts +│ │ ├── LevelledTopologicalSorter.ts +│ │ └── Utils.ts +│ │ +│ ├── cli/ # CLI utilities +│ │ ├── sanitizers/ # Input sanitizers +│ │ └── utils/ # File handling +│ │ +│ ├── enums/ # Enumerations +│ ├── interfaces/ # TypeScript interfaces +│ ├── types/ # Type definitions +│ ├── constants/ # Constants +│ ├── decorators/ # Decorators +│ └── logger/ # Logging system +│ +├── test/ # Test suite +│ ├── functional-tests/ # Feature tests +│ ├── unit-tests/ # Unit tests +│ ├── performance-tests/ # Performance benchmarks +│ └── index.spec.ts +│ +├── webpack/ # Build configurations +│ ├── webpack.node.config.js +│ └── webpack.browser.config.js +│ +├── dist/ # Compiled output +│ ├── index.js # Node.js bundle +│ └── index.browser.js # Browser bundle +│ +├── bin/ # CLI executable +│ └── javascript-obfuscator +│ +└── typings/ # TypeScript declarations +``` + +## Core Workflow + +### Obfuscation Pipeline + +The obfuscation process follows a multi-stage pipeline defined in `JavaScriptObfuscator.ts`: + +``` +1. Code Transformation Stage: PreparingTransformers + └─> Raw code preprocessing (e.g., hashbang handling) + +2. AST Parsing + └─> Parse source code into ESTree-compliant AST using Acorn + +3. Node Transformation Stages (sequential): + ├─> Initializing + │ └─> Initial AST setup, parentification, metadata + ├─> Preparing + │ └─> Scope analysis, obfuscating guards, identifier collection + ├─> DeadCodeInjection (optional) + │ └─> Insert dead code blocks + ├─> ControlFlowFlattening (optional) + │ └─> Flatten control flow with switch statements + ├─> RenameProperties (optional) + │ └─> Rename object properties + ├─> Converting + │ └─> Transform nodes (literals, expressions, etc.) + ├─> RenameIdentifiers + │ └─> Rename variables and functions + ├─> StringArray + │ └─> Extract strings to array, add wrappers + ├─> Simplifying (optional) + │ └─> Simplify and merge statements + └─> Finalizing + └─> Final cleanup, directive placement + +4. Code Generation + └─> Generate obfuscated code using escodegen + +5. Code Transformation Stage: FinalizingTransformers + └─> Post-processing on generated code + +6. Source Map Generation (optional) + └─> Create source maps for debugging +``` + +### Dependency Injection Architecture + +The project uses **InversifyJS v7** for dependency injection, providing: + +- **Modularity**: Clean separation of concerns +- **Testability**: Easy mocking and testing +- **Flexibility**: Runtime configuration of transformers +- **Scalability**: Easy addition of new transformers + +All components are registered in container modules located in `src/container/modules/`. + +**Key Changes in InversifyJS v7:** +- Container modules now use `ContainerModuleLoadOptions` instead of separate `bind`, `unbind`, etc. parameters +- `getNamed`, `getTagged`, etc. are replaced by `get(serviceId, { name: ... })` or `get(serviceId, { tag: ... })` +- `load()` and `unload()` are now async, with `loadSync()` and `unloadSync()` alternatives for synchronous operations +- Types like `Context`, `Newable`, `Factory` are now directly exported instead of through `interfaces` namespace +- Custom metadata and middleware features have been removed + +## Key Components Deep Dive + +### 1. JavaScriptObfuscator (Main Engine) + +**Location**: `src/JavaScriptObfuscator.ts` + +The core orchestrator that: +- Manages the complete obfuscation pipeline +- Coordinates code and node transformers +- Handles AST parsing and code generation +- Integrates with logger and random generator + +**Key Methods**: +- `obfuscate(sourceCode: string): IObfuscationResult` - Main entry point +- `parseCode()` - AST parsing with Acorn +- `transformAstTree()` - Applies transformation stages +- `generateCode()` - Code generation with escodegen + +### 2. Node Transformers + +**Location**: `src/node-transformers/` + +Each transformer implements `INodeTransformer` interface with: +- `getVisitor(stage): IVisitor | null` - Returns visitor for specific stage +- `transformNode(node, parent): Node` - Transforms individual AST node + +**Key Transformers**: + +- **StringArrayTransformer**: Extracts string literals to centralized array +- **BooleanLiteralTransformer**: Converts true/false to `!![]` and `![]` +- **NumberToNumericalExpressionTransformer**: Converts numbers to expressions +- **BlockStatementControlFlowTransformer**: Implements control flow flattening +- **DeadCodeInjectionTransformer**: Injects dead code blocks +- **RenamePropertiesTransformer**: Renames object properties +- **ScopeIdentifiersTransformer**: Renames variables based on scope + +### 3. Analyzers + +**Location**: `src/analyzers/` + +- **CallsGraphAnalyzer**: Builds function call dependency graph +- **ScopeAnalyzer**: Analyzes variable scopes using eslint-scope +- **StringArrayStorageAnalyzer**: Optimizes string array storage +- **PrevailingKindOfVariablesAnalyzer**: Determines var/let/const usage +- **NumberNumericalExpressionAnalyzer**: Analyzes numeric expressions + +### 4. Custom Code Helpers + +**Location**: `src/custom-code-helpers/` + +Injectable runtime helpers that provide: +- **String Array Decoders**: Base64/RC4 decoding functions +- **Debug Protection**: Anti-debugging wrapper code +- **Domain Lock**: Domain validation code +- **Self-Defending**: Code integrity checks +- **Console Output Disable**: Console method replacements + +### 5. Options System + +**Location**: `src/options/` + +Sophisticated configuration system with: +- **Validation**: Using class-validator decorators +- **Normalization**: Automatic option interdependency handling +- **Presets**: Default, low, medium, and high obfuscation presets +- **Type Safety**: Full TypeScript support + +**Key Option Categories**: +- Code output (compact, target) +- String transformations (stringArray*, splitStrings) +- Control flow (controlFlowFlattening, deadCodeInjection) +- Naming (identifierNamesGenerator, renameGlobals, renameProperties) +- Protection (selfDefending, debugProtection, domainLock) +- Advanced (numbersToExpressions, simplify, transformObjectKeys) + +## Important Patterns and Conventions + +### 1. Visitor Pattern + +Transformers use the visitor pattern for AST traversal: + +```typescript +interface IVisitor { + enter?: (node: Node, parent: Node) => Node | VisitorOption; + leave?: (node: Node, parent: Node) => Node | VisitorOption; +} +``` + +### 2. Initializable Pattern + +Many components implement `IInitializable` for lazy initialization: + +```typescript +interface IInitializable { + initialize(...args: any[]): void; +} +``` + +Managed via `@Initializable()` decorator. + +### 3. Stage-Based Processing + +Both code and node transformers operate in stages: + +**Code Transformation Stages**: +- PreparingTransformers +- FinalizingTransformers + +**Node Transformation Stages**: +- Initializing +- Preparing +- DeadCodeInjection +- ControlFlowFlattening +- RenameProperties +- Converting +- RenameIdentifiers +- StringArray +- Simplifying +- Finalizing + +### 4. Factory Pattern + +Extensive use of factories for object creation: +- `TObfuscationResultFactory` +- Custom node factories +- Identifier name generators + +### 5. Storage Pattern + +Centralized storages for shared data: +- String array storage +- Custom code helpers storage +- Identifier names cache storage +- Control flow transformers storage + +## CLI Usage + +**Location**: `bin/javascript-obfuscator`, `src/JavaScriptObfuscatorCLIFacade.ts` + +### Basic Commands + +```bash +# Obfuscate single file +javascript-obfuscator input.js --output output.js + +# Obfuscate directory +javascript-obfuscator ./src --output ./dist + +# Use configuration file +javascript-obfuscator input.js --config config.json + +# High obfuscation preset +javascript-obfuscator input.js --options-preset high-obfuscation +``` + +### CLI Features + +- Automatic identifier prefix for multiple files +- Glob pattern exclusions +- Source map support +- Identifier names cache (cross-file consistency) +- Progress logging + +## API Usage + +### Basic Obfuscation + +```javascript +const JavaScriptObfuscator = require('javascript-obfuscator'); + +const obfuscationResult = JavaScriptObfuscator.obfuscate( + ` + var foo = 'Hello World'; + console.log(foo); + `, + { + compact: true, + controlFlowFlattening: true + } +); + +console.log(obfuscationResult.getObfuscatedCode()); +console.log(obfuscationResult.getSourceMap()); +console.log(obfuscationResult.getIdentifierNamesCache()); +``` + +### Multiple Files + +```javascript +const sourceCodesObject = { + 'file1.js': 'var foo = 1;', + 'file2.js': 'var bar = 2;' +}; + +const obfuscationResults = JavaScriptObfuscator.obfuscateMultiple( + sourceCodesObject, + options +); +``` + +### Identifier Names Cache (Cross-File Consistency) + +```javascript +// First file +const result1 = JavaScriptObfuscator.obfuscate(code1, { + identifierNamesCache: {}, + renameGlobals: true +}); +const cache = result1.getIdentifierNamesCache(); + +// Second file using same cache +const result2 = JavaScriptObfuscator.obfuscate(code2, { + identifierNamesCache: cache, + renameGlobals: true +}); +``` + +## Browser Support + +The project includes a browser build at `dist/index.browser.js` that can be used in web environments: + +```html + + +``` + +**Note**: No eval() in `browser-no-eval` target. + +## Build System + +### Webpack Configuration + +- **Node.js build**: `webpack/webpack.node.config.js` + - Target: CommonJS module + - External dependencies: node_modules + - Output: `dist/index.js` + +- **Browser build**: `webpack/webpack.browser.config.js` + - Target: UMD module + - Bundled dependencies + - Output: `dist/index.browser.js` + +### Build Scripts + +```bash +# Production build +npm run build +# or +yarn run build + +# Development watch mode +npm run watch +# or +yarn run watch + +# Build TypeScript typings +npm run build:typings +# or +yarn run build:typings + +# Linting +npm run eslint +# or +yarn run eslint +``` + +## Testing + +### Test Structure + +**Location**: `test/` + +- **Functional tests**: Feature-level tests for transformers and options +- **Unit tests**: Component-level tests +- **Performance tests**: Memory and speed benchmarks + +### Running Tests + +#### Quick Start + +```bash +# Install dependencies first +npm install +# or +yarn install + +# Run all tests (includes dev test, coverage, and memory performance) +npm test +# or +yarn test +``` + +#### Individual Test Commands + +```bash +# Run full test suite (test:dev + test:mocha-coverage + test:mocha-memory-performance). This is slow. +npm run test:full +yarn run test:full + +# Run Mocha tests only (no coverage) +npm run test:mocha +yarn run test:mocha + +# Run tests with coverage report +npm run test:mocha-coverage +yarn run test:mocha-coverage + +# Generate detailed coverage report (after running test:mocha-coverage) +npm run test:mocha-coverage:report +yarn run test:mocha-coverage:report + +# Run memory performance tests (tests memory constraints) +npm run test:mocha-memory-performance +yarn run test:mocha-memory-performance + +# Run development test (custom dev test file) +npm run test:dev +yarn run test:dev + +# Run compile performance test +npm run test:devCompilePerformance +yarn run test:devCompilePerformance + +# Run runtime performance test +npm run test:devRuntimePerformance +yarn run test:devRuntimePerformance +``` + +#### Test Details + +**test:full** +- Runs the complete test suite +- Includes: development tests, coverage tests, and memory performance tests +- This is what runs when you execute `npm test` + +**test:mocha** +- Runs all Mocha tests from `test/index.spec.ts` +- Uses ts-node for TypeScript execution +- No code coverage reporting + +**test:mocha-coverage** +- Runs Mocha tests with NYC (Istanbul) code coverage +- Allocates up to 4GB memory (`--max-old-space-size=4096`) +- Generates coverage reports (text-summary by default) +- Use `test:mocha-coverage:report` to generate detailed lcov report + +**test:mocha-memory-performance** +- Tests obfuscator memory usage under constraints +- Allocates only 280MB memory to test memory efficiency +- Located at: `test/performance-tests/JavaScriptObfuscatorMemory.spec.ts` + +**test:dev** +- Custom development test script +- Located at: `test/dev/dev.ts` +- Useful for quick testing during development + +### Test Configuration Files + +- **`.mocharc.json`**: Mocha test runner configuration +- **`.nycrc.json`**: NYC (Istanbul) coverage tool configuration +- **TypeScript**: Uses ts-node for direct TS execution without compilation + +### Running Specific Test Files + +You can run individual test files or groups of tests for faster iteration during development. + +#### Basic Command Format + +```bash +npx mocha --require ts-node/register --require source-map-support/register +``` + +#### Common Examples + +```bash +# Run a specific test file by exact path +npx mocha --require ts-node/register --require source-map-support/register test/functional-tests/options/Options.spec.ts + +# Run CLI tests +npx mocha --require ts-node/register --require source-map-support/register test/functional-tests/cli/JavaScriptObfuscatorCLI.spec.ts + +# Run a specific analyzer test +npx mocha --require ts-node/register --require source-map-support/register test/functional-tests/analyzers/calls-graph-analyzer/CallsGraphAnalyzer.spec.ts + +# Run scope analyzer tests +npx mocha --require ts-node/register --require source-map-support/register test/functional-tests/analyzers/scope-analyzer/ScopeAnalyzer.spec.ts + +# Run string array tests +npx mocha --require ts-node/register --require source-map-support/register test/functional-tests/custom-code-helpers/string-array/StringArrayCodeHelper.spec.ts + +# Run self-defending code tests +npx mocha --require ts-node/register --require source-map-support/register test/functional-tests/custom-code-helpers/self-defending/SelfDefendingCodeHelper.spec.ts +``` + +#### Pattern Matching + +Use glob patterns to run multiple related test files: + +```bash +# Run all options-related tests +npx mocha --require ts-node/register --require source-map-support/register "test/functional-tests/options/**/*.spec.ts" + +# Run all analyzer tests +npx mocha --require ts-node/register --require source-map-support/register "test/functional-tests/analyzers/**/*.spec.ts" + +# Run all string array related tests +npx mocha --require ts-node/register --require source-map-support/register "test/functional-tests/**/*StringArray*.spec.ts" + +# Run all control flow tests +npx mocha --require ts-node/register --require source-map-support/register "test/functional-tests/**/*ControlFlow*.spec.ts" + +# Run all node transformer tests +npx mocha --require ts-node/register --require source-map-support/register "test/functional-tests/node-transformers/**/*.spec.ts" + +# Run all unit tests only +npx mocha --require ts-node/register --require source-map-support/register "test/unit-tests/**/*.spec.ts" + +# Run all functional tests only +npx mocha --require ts-node/register --require source-map-support/register "test/functional-tests/**/*.spec.ts" +``` + +#### Running Tests by Category + +The test suite is organized into these main categories: + +**Functional Tests** (`test/functional-tests/`): +```bash +# Options tests +npx mocha --require ts-node/register --require source-map-support/register "test/functional-tests/options/**/*.spec.ts" + +# Analyzers tests +npx mocha --require ts-node/register --require source-map-support/register "test/functional-tests/analyzers/**/*.spec.ts" + +# Node transformers tests +npx mocha --require ts-node/register --require source-map-support/register "test/functional-tests/node-transformers/**/*.spec.ts" + +# Code transformers tests +npx mocha --require ts-node/register --require source-map-support/register "test/functional-tests/code-transformers/**/*.spec.ts" + +# Custom code helpers tests +npx mocha --require ts-node/register --require source-map-support/register "test/functional-tests/custom-code-helpers/**/*.spec.ts" + +# Storage tests +npx mocha --require ts-node/register --require source-map-support/register "test/functional-tests/storages/**/*.spec.ts" + +# CLI tests +npx mocha --require ts-node/register --require source-map-support/register "test/functional-tests/cli/**/*.spec.ts" + +# Generator tests +npx mocha --require ts-node/register --require source-map-support/register "test/functional-tests/generators/**/*.spec.ts" + +# Main obfuscator tests +npx mocha --require ts-node/register --require source-map-support/register "test/functional-tests/javascript-obfuscator/**/*.spec.ts" + +# Issue regression tests +npx mocha --require ts-node/register --require source-map-support/register "test/functional-tests/issues/**/*.spec.ts" +``` + +**Unit Tests** (`test/unit-tests/`): +```bash +# All unit tests +npx mocha --require ts-node/register --require source-map-support/register "test/unit-tests/**/*.spec.ts" + +# Options unit tests +npx mocha --require ts-node/register --require source-map-support/register "test/unit-tests/options/**/*.spec.ts" + +# Utils unit tests +npx mocha --require ts-node/register --require source-map-support/register "test/unit-tests/utils/**/*.spec.ts" + +# Node utilities unit tests +npx mocha --require ts-node/register --require source-map-support/register "test/unit-tests/node/**/*.spec.ts" +``` + +**Performance Tests** (`test/performance-tests/`): +```bash +# Memory performance tests +npx mocha --require ts-node/register --require source-map-support/register test/performance-tests/JavaScriptObfuscatorMemory.spec.ts +``` + +#### Using Mocha Options with Individual Tests + +```bash +# Run with grep to filter by test description +npx mocha --require ts-node/register --require source-map-support/register test/functional-tests/options/Options.spec.ts --grep "compact" + +# Run and show slow tests +npx mocha --require ts-node/register --require source-map-support/register test/functional-tests/options/Options.spec.ts --reporter spec + +# Run with timeout override (default is 10000ms) +npx mocha --require ts-node/register --require source-map-support/register test/functional-tests/options/Options.spec.ts --timeout 20000 + +# Run with bail (stop on first failure) +npx mocha --require ts-node/register --require source-map-support/register "test/functional-tests/**/*.spec.ts" --bail + +# Run and watch for changes +npx mocha --require ts-node/register --require source-map-support/register test/functional-tests/options/Options.spec.ts --watch + +# Run with specific reporter +npx mocha --require ts-node/register --require source-map-support/register test/functional-tests/options/Options.spec.ts --reporter json +``` + +#### Creating Test Aliases (Optional) + +For convenience, you can add these aliases to your `package.json` scripts: + +```json +{ + "scripts": { + "test:options": "mocha --require ts-node/register --require source-map-support/register 'test/functional-tests/options/**/*.spec.ts'", + "test:analyzers": "mocha --require ts-node/register --require source-map-support/register 'test/functional-tests/analyzers/**/*.spec.ts'", + "test:transformers": "mocha --require ts-node/register --require source-map-support/register 'test/functional-tests/node-transformers/**/*.spec.ts'", + "test:unit": "mocha --require ts-node/register --require source-map-support/register 'test/unit-tests/**/*.spec.ts'", + "test:functional": "mocha --require ts-node/register --require source-map-support/register 'test/functional-tests/**/*.spec.ts'" + } +} +``` + +Then run with: +```bash +npm run test:options +npm run test:analyzers +npm run test:transformers +``` + +#### Tips for Running Individual Tests + +1. **Use quotes around glob patterns** to prevent shell expansion: + ```bash + # Good + npx mocha "test/**/*.spec.ts" + + # Bad (shell will expand the pattern) + npx mocha test/**/*.spec.ts + ``` + +2. **Use --grep to run specific test cases** within a file: + ```bash + npx mocha --require ts-node/register test/functional-tests/options/Options.spec.ts --grep "should enable compact" + ``` + +3. **Use --bail to stop on first failure** when debugging: + ```bash + npx mocha --require ts-node/register "test/**/*.spec.ts" --bail + ``` + +4. **Check the exit code** to verify test success in scripts: + ```bash + npx mocha --require ts-node/register test/functional-tests/options/Options.spec.ts && echo "Tests passed!" + ``` + +5. **Combine with watch mode** for TDD workflow: + ```bash + npx mocha --require ts-node/register test/functional-tests/options/Options.spec.ts --watch --reporter min + ``` + +## Linting + +### Running ESLint + +#### Quick Start + +```bash +# Lint all TypeScript files in src/ +npm run eslint +yarn run eslint +``` + +This runs: `eslint src/**/*.ts` + +#### Linting Individual Files + +You can lint specific files or directories for faster feedback during development. + +**Basic Command Format:** +```bash +npx eslint +``` + +**Common Examples:** + +```bash +# Lint a specific file +npx eslint src/JavaScriptObfuscator.ts + +# Lint the main facade file +npx eslint src/JavaScriptObfuscatorFacade.ts + +# Lint a specific transformer +npx eslint src/node-transformers/converting-transformers/StringArrayTransformer.ts + +# Lint a specific analyzer +npx eslint src/analyzers/calls-graph-analyzer/CallsGraphAnalyzer.ts + +# Lint options file +npx eslint src/options/Options.ts + +# Lint a custom code helper +npx eslint src/custom-code-helpers/string-array/StringArrayCodeHelper.ts + +# Lint container files +npx eslint src/container/InversifyContainerFacade.ts +``` + +#### Linting Multiple Files or Directories + +```bash +# Lint entire src directory +npx eslint src/ + +# Lint all files in a specific subdirectory +npx eslint src/node-transformers/ + +# Lint all analyzers +npx eslint src/analyzers/ + +# Lint all transformers +npx eslint src/node-transformers/**/*.ts + +# Lint all options-related files +npx eslint src/options/ + +# Lint all custom code helpers +npx eslint src/custom-code-helpers/ + +# Lint all utils +npx eslint src/utils/ + +# Lint CLI files +npx eslint src/cli/ + +# Lint container modules +npx eslint src/container/ + +# Lint storage files +npx eslint src/storages/ +``` + +#### Using Glob Patterns + +```bash +# Lint all TypeScript files in src (same as npm run eslint) +npx eslint "src/**/*.ts" + +# Lint all transformer files +npx eslint "src/**/*Transformer.ts" + +# Lint all analyzer files +npx eslint "src/**/*Analyzer.ts" + +# Lint all storage files +npx eslint "src/**/*Storage.ts" + +# Lint all helper files +npx eslint "src/**/*Helper.ts" + +# Lint all files containing "String" in the name +npx eslint "src/**/*String*.ts" + +# Lint all files in node-transformers subdirectories +npx eslint "src/node-transformers/**/*.ts" +``` + +#### Auto-fixing Issues + +ESLint can automatically fix many issues: + +```bash +# Auto-fix all files in src/ +npx eslint src/**/*.ts --fix + +# Auto-fix a specific file +npx eslint src/JavaScriptObfuscator.ts --fix + +# Auto-fix specific directory +npx eslint src/node-transformers/ --fix + +# Auto-fix with glob pattern +npx eslint "src/analyzers/**/*.ts" --fix + +# Auto-fix only safe fixes (no potentially breaking changes) +npx eslint src/JavaScriptObfuscator.ts --fix --fix-type suggestion,layout +``` + +#### Checking Specific Rules + +```bash +# Show only errors (no warnings) +npx eslint src/JavaScriptObfuscator.ts --quiet + +# Check specific rule only +npx eslint src/JavaScriptObfuscator.ts --rule 'no-console: error' + +# Disable specific rules for a file check +npx eslint src/JavaScriptObfuscator.ts --rule 'no-console: off' + +# Output format options +npx eslint src/JavaScriptObfuscator.ts --format stylish # Default +npx eslint src/JavaScriptObfuscator.ts --format json # JSON output +npx eslint src/JavaScriptObfuscator.ts --format compact # Compact output +npx eslint src/JavaScriptObfuscator.ts --format unix # Unix style +``` + +#### Getting Detailed Information + +```bash +# Show more details about errors +npx eslint src/JavaScriptObfuscator.ts --format stylish + +# List all files that would be linted (dry-run) +npx eslint src/ --debug 2>&1 | grep "Processing" + +# Show timing information for rules +npx eslint src/JavaScriptObfuscator.ts --debug + +# Get statistics about linting +npx eslint src/ --format json | jq '.[] | {file: .filePath, errors: .errorCount, warnings: .warningCount}' +``` + +#### Linting by Component + +Organized by project structure: + +**Core Files:** +```bash +npx eslint src/JavaScriptObfuscator.ts +npx eslint src/JavaScriptObfuscatorFacade.ts +npx eslint src/ASTParserFacade.ts +``` + +**Node Transformers:** +```bash +# All node transformers +npx eslint src/node-transformers/ + +# Converting transformers +npx eslint src/node-transformers/converting-transformers/ + +# Control flow transformers +npx eslint src/node-transformers/control-flow-transformers/ + +# String array transformers +npx eslint src/node-transformers/string-array-transformers/ + +# Rename transformers +npx eslint src/node-transformers/rename-identifiers-transformers/ +npx eslint src/node-transformers/rename-properties-transformers/ +``` + +**Analyzers:** +```bash +# All analyzers +npx eslint src/analyzers/ + +# Specific analyzers +npx eslint src/analyzers/calls-graph-analyzer/ +npx eslint src/analyzers/scope-analyzer/ +npx eslint src/analyzers/string-array-storage-analyzer/ +``` + +**Options System:** +```bash +# All options files +npx eslint src/options/ + +# Core options +npx eslint src/options/Options.ts +npx eslint src/options/OptionsNormalizer.ts + +# Validators +npx eslint src/options/validators/ + +# Presets +npx eslint src/options/presets/ +``` + +**Custom Code Helpers:** +```bash +# All helpers +npx eslint src/custom-code-helpers/ + +# String array helpers +npx eslint src/custom-code-helpers/string-array/ + +# Debug protection helpers +npx eslint src/custom-code-helpers/debug-protection/ + +# Self-defending helpers +npx eslint src/custom-code-helpers/self-defending/ +``` + +**Utilities:** +```bash +# All utils +npx eslint src/utils/ + +# Specific utils +npx eslint src/utils/RandomGenerator.ts +npx eslint src/utils/ArrayUtils.ts +npx eslint src/utils/CryptUtils.ts +``` + +#### Integrating with Git + +```bash +# Lint only staged files (useful for pre-commit) +git diff --cached --name-only --diff-filter=ACM | grep '\.ts$' | xargs npx eslint + +# Lint files changed in current branch +git diff --name-only master | grep '\.ts$' | xargs npx eslint + +# Lint files changed in last commit +git diff HEAD~1 --name-only | grep '\.ts$' | xargs npx eslint +``` + +#### Creating Lint Aliases (Optional) + +Add these to your `package.json` scripts for convenience: + +```json +{ + "scripts": { + "lint": "eslint src/**/*.ts", + "lint:fix": "eslint src/**/*.ts --fix", + "lint:transformers": "eslint src/node-transformers/**/*.ts", + "lint:analyzers": "eslint src/analyzers/**/*.ts", + "lint:options": "eslint src/options/**/*.ts", + "lint:utils": "eslint src/utils/**/*.ts", + "lint:quiet": "eslint src/**/*.ts --quiet", + "lint:staged": "git diff --cached --name-only --diff-filter=ACM | grep '\\.ts$' | xargs eslint" + } +} +``` + +Then run with: +```bash +npm run lint:transformers +npm run lint:analyzers +npm run lint:fix +``` + +### ESLint Configuration + +**Location**: `.eslintrc.js` + +The project uses: +- **@typescript-eslint**: TypeScript-specific linting rules +- **eslint-plugin-import**: Import/export validation +- **eslint-plugin-jsdoc**: JSDoc comment validation +- **eslint-plugin-no-null**: Prevents null usage (prefer undefined) +- **eslint-plugin-prefer-arrow**: Enforces arrow functions +- **eslint-plugin-unicorn**: Additional code quality rules + +**Ignored files**: `.eslintignore` + +#### Viewing Current ESLint Config + +```bash +# Print effective configuration for a file +npx eslint --print-config src/JavaScriptObfuscator.ts + +# List all rules being applied +npx eslint --print-config src/JavaScriptObfuscator.ts | grep rules -A 1000 +``` + +### Code Quality Checks + +```bash +# Run full build (includes webpack, eslint, and tests) +npm run build +yarn run build + +# The build script runs: +# 1. webpack:prod (production build) +# 2. eslint (linting) +# 3. test (full test suite) +``` + +### Tips for Effective Linting + +1. **Lint before committing**: Always run linting before creating commits + ```bash + npx eslint src/ && git commit -m "Your message" + ``` + +2. **Use --fix cautiously**: Review changes before committing auto-fixes + ```bash + npx eslint src/MyFile.ts --fix + git diff # Review changes + ``` + +3. **Focus on errors first**: Use `--quiet` to see only errors + ```bash + npx eslint src/ --quiet + ``` + +4. **Lint specific files during development**: Don't lint everything when working on one file + ```bash + npx eslint src/node-transformers/MyNewTransformer.ts + ``` + +5. **Check exit code**: Useful in scripts and CI/CD + ```bash + npx eslint src/ || echo "Linting failed!" + ``` + +## Development Workflow + +### Setting Up Development Environment + +```bash +# 1. Clone the repository +git clone https://github.com/javascript-obfuscator/javascript-obfuscator.git +cd javascript-obfuscator + +# 2. Install dependencies +npm install +# or +yarn install + +# 3. Install Husky hooks (for pre-commit checks) +npm run prepare +# or +yarn run prepare +``` + +### Development Commands + +```bash +# Start development mode with watch (auto-recompile on changes) +npm start +# or +npm run watch +# or +yarn run watch + +# Build for production +npm run webpack:prod +yarn run webpack:prod + +# Build TypeScript type definitions +npm run build:typings +yarn run build:typings + +# Full build (webpack + eslint + tests) +npm run build +yarn run build +``` + +### Pre-commit Hooks + +The project uses **Husky** for git hooks: + +- **pre-commit**: Automatically runs `npm run build` before each commit + - Ensures code compiles + - Ensures linting passes + - Ensures all tests pass + +**Configuration**: `.husky/` directory + +### Development Tips + +1. **Use watch mode during development**: + ```bash + npm run watch + # or + yarn run watch + ``` + This rebuilds automatically when you save files. + +2. **Run specific tests during development**: + ```bash + npm run test:dev + # or + yarn run test:dev + ``` + Faster than full test suite. + +3. **Check linting before committing**: + ```bash + npm run eslint + # or + yarn run eslint + ``` + Fix issues before the pre-commit hook runs. + +4. **Test memory usage**: + ```bash + npm run test:mocha-memory-performance + # or + yarn run test:mocha-memory-performance + ``` + Ensure your changes don't cause memory issues. + +5. **Generate coverage reports**: + ```bash + npm run test:mocha-coverage + npm run test:mocha-coverage:report + # or + yarn run test:mocha-coverage + yarn run test:mocha-coverage:report + ``` + Check test coverage in the generated `coverage/` directory. + +## Performance Considerations + +### Impact on Code Size + +- **Default**: ~15-30% increase +- **Dead Code Injection**: Up to 200% increase +- **String Array**: 20-50% increase +- **Control Flow Flattening**: 30-80% increase + +### Runtime Performance + +- **No obfuscation**: Baseline +- **Low preset**: ~10-20% slower +- **Medium preset**: ~30-50% slower +- **High preset**: ~50-80% slower + +### Optimization Tips + +1. Use **thresholds** to apply transformations selectively: + - `controlFlowFlatteningThreshold` + - `deadCodeInjectionThreshold` + - `stringArrayThreshold` + +2. Avoid obfuscating: + - Third-party libraries + - Polyfills + - Large vendor bundles + +3. Use **seed** option for reproducible builds + +4. Enable **simplify** for better performance (enabled by default) + +## Security Considerations + +### What It Protects + +- Makes reverse engineering harder +- Prevents casual code inspection +- Protects string literals and algorithms +- Adds anti-debugging measures +- Can lock code to specific domains + +### What It Doesn't Protect + +- Determined attackers with time and tools +- Network traffic and API endpoints +- Runtime behavior analysis +- Secrets embedded in code (use environment variables!) + +### Best Practices + +1. **Never obfuscate secrets**: Use environment variables or secure vaults +2. **Combine with other protections**: Minification, HTTPS, CSP headers +3. **Test thoroughly**: Obfuscation can introduce subtle bugs +4. **Monitor performance**: High obfuscation impacts runtime speed +5. **Use source maps carefully**: Keep them private for debugging + +## Conditional Comments + +Control obfuscation for specific code sections: + +```javascript +var foo = 1; +// javascript-obfuscator:disable +var bar = 2; // This won't be obfuscated +// javascript-obfuscator:enable +var baz = 3; +``` + +## Integration with Build Tools + +### Webpack + +Use [webpack-obfuscator](https://github.com/javascript-obfuscator/webpack-obfuscator) plugin + +### Gulp + +Use [gulp-javascript-obfuscator](https://github.com/javascript-obfuscator/gulp-javascript-obfuscator) + +### Rollup + +Use [rollup-plugin-javascript-obfuscator](https://github.com/javascript-obfuscator/rollup-plugin-javascript-obfuscator) + +### Grunt + +Use [grunt-contrib-obfuscator](https://github.com/javascript-obfuscator/grunt-contrib-obfuscator) + +## Common Issues and Solutions + +### Issue: Code breaks after obfuscation + +**Solutions**: +- Add function/variable names to `reservedNames` +- Add strings to `reservedStrings` +- Use `renamePropertiesMode: 'safe'` instead of 'unsafe' +- Disable `renameProperties` if safe mode doesn't work +- Check for dynamic property access like `obj[dynamicKey]` + +### Issue: Performance is too slow + +**Solutions**: +- Use lower obfuscation preset +- Reduce threshold values +- Disable `controlFlowFlattening` and `deadCodeInjection` +- Use `target: 'browser-no-eval'` if applicable + +### Issue: Code size is too large + +**Solutions**: +- Disable `deadCodeInjection` +- Reduce `stringArrayWrappersCount` +- Use lower `stringArrayThreshold` +- Disable `unicodeEscapeSequence` + +### Issue: Source maps not working + +**Solutions**: +- Ensure `sourceMap: true` in options +- Set correct `sourceMapMode` ('inline' or 'separate') +- Specify `inputFileName` when using NodeJS API +- Use `sourceMapSourcesMode: 'sources-content'` for embedded source + +### Issue: Domain lock not working + +**Solutions**: +- Don't use with `target: 'node'` +- Test in actual browser environment +- Check domain format (`.example.com` for all subdomains) +- Ensure `domainLockRedirectUrl` is set + +## Extension Points + +### Adding Custom Transformers + +1. Create transformer class extending `AbstractNodeTransformer` +2. Implement `getVisitor()` and `transformNode()` methods +3. Register in appropriate module (`src/container/modules/node-transformers/`) +4. Add to transformer list in `JavaScriptObfuscator.ts` +5. Add to `NodeTransformer` enum + +### Adding Custom Options + +1. Add property to `IOptions` interface +2. Add validation decorator in `Options.ts` +3. Add normalizer rule if needed in `options/normalizer-rules/` +4. Add preset values if applicable + +### Adding Custom Code Helpers + +1. Create helper group extending `AbstractCustomCodeHelperGroup` +2. Create template files in `custom-code-helpers/[group]/templates/` +3. Register in `CustomCodeHelpersModule` +4. Add to `CustomCodeHelper` enum + +## TypeScript Configuration + +### Main Config + +**Location**: `tsconfig.json` + +- **Target**: ES2018 +- **Module**: CommonJS +- **Strict mode**: Enabled +- **Decorators**: Enabled (experimental) +- **Emit decorator metadata**: Enabled + +### Special Configs + +- `tsconfig.browser.json`: Browser-specific settings +- `tsconfig.node.json`: Node.js-specific settings +- `tsconfig.typings.json`: Type declarations generation + +## Dependencies Overview + +### Production Dependencies + +- **@javascript-obfuscator/escodegen**: Modified escodegen for code generation +- **@javascript-obfuscator/estraverse**: Modified estraverse for AST traversal +- **acorn**: JavaScript parser (ES3-ES2020) +- **inversify**: Dependency injection container +- **eslint-scope**: Scope analysis (from ESLint) +- **class-validator**: Options validation +- **chance**: Random data generation +- **commander**: CLI argument parsing +- **chalk**: Terminal colors +- **md5**: Hashing for identifiers + +### Development Dependencies + +- **TypeScript**: Type system and compiler +- **Webpack**: Module bundler +- **Mocha + Chai**: Testing framework +- **NYC**: Code coverage +- **ESLint**: Code linting +- **Sinon**: Test mocking + +## Contributing + +**Location**: `CONTRIBUTING.md`, `CODE_OF_CONDUCT.md` + +1. Fork the repository +2. Create feature branch +3. Write tests for new features +4. Ensure all tests pass +5. Follow existing code style (ESLint) +6. Submit pull request + +## Versioning and Releases + +- Follows semantic versioning (SemVer) +- Changelog maintained in `CHANGELOG.md` +- Precommit hooks run build and tests (Husky) +- Automated CI/CD via GitHub Actions + +## Support and Community + +- **GitHub Issues**: Bug reports and feature requests +- **GitHub Discussions**: Questions and general discussion +- **GitHub Sponsors**: Direct sponsorship + +## License + +**BSD-2-Clause License** + +Copyright (C) 2016-2026 Timofei Kachalov + +See `LICENSE.BSD` for full license text. + +## Project Statistics + +- **First Release**: 2016 +- **Language**: TypeScript (~90% of codebase) +- **Test Coverage**: Extensive functional and unit test suite +- **Supported JavaScript Versions**: ES3, ES5, ES2015-ES2019, partial ES2020 +- **Downloads**: Widely used in production applications +- **Maintenance**: Actively maintained + +## Resources + +- **Main Repository**: https://github.com/javascript-obfuscator/javascript-obfuscator +- **Online Tool**: https://obfuscator.io +- **NPM Package**: https://www.npmjs.com/package/javascript-obfuscator +- **Documentation**: In README.md and inline code comments + +--- + +## Quick Reference: File Locations + +| Component | Primary Location | +|-----------|------------------| +| Main Obfuscator | `src/JavaScriptObfuscator.ts` | +| Public API | `src/JavaScriptObfuscatorFacade.ts` | +| CLI | `bin/javascript-obfuscator`, `src/JavaScriptObfuscatorCLIFacade.ts` | +| Options | `src/options/Options.ts` | +| Transformers | `src/node-transformers/` | +| Analyzers | `src/analyzers/` | +| DI Container | `src/container/InversifyContainerFacade.ts` | +| Tests | `test/` | +| Build Config | `webpack/` | +| Distribution | `dist/` | + +## Quick Reference: Key Enums + +- **CodeTransformationStage**: PreparingTransformers, FinalizingTransformers +- **NodeTransformationStage**: Initializing, Preparing, DeadCodeInjection, ControlFlowFlattening, RenameProperties, Converting, RenameIdentifiers, StringArray, Simplifying, Finalizing +- **OptionsPreset**: default, low-obfuscation, medium-obfuscation, high-obfuscation +- **StringArrayEncoding**: none, base64, rc4 +- **IdentifierNamesGenerator**: hexadecimal, mangled, mangled-shuffled, dictionary +- **RenamePropertiesMode**: safe, unsafe +- **Target**: browser, browser-no-eval, node diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md index c2a51b853..14aa477fa 100644 --- a/CODE_OF_CONDUCT.md +++ b/CODE_OF_CONDUCT.md @@ -34,7 +34,7 @@ This Code of Conduct applies both within project spaces and in public spaces whe ## Enforcement -Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at sanex3339@yandex.ru. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. +Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at support@obfuscator.io. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. diff --git a/README.md b/README.md index c850f60f1..6658a333a 100644 --- a/README.md +++ b/README.md @@ -1,22 +1,63 @@ -#### You can support this project by donating: -* (Github) https://github.com/sponsors/sanex3339 -* (OpenCollective) https://opencollective.com/javascript-obfuscator - -Huge thanks to all supporters! - # JavaScript obfuscator ![logo](https://raw.githubusercontent.com/javascript-obfuscator/javascript-obfuscator/master/images/logo.png) +--- + +### Do you use JavaScript Obfuscator at your company? + +JavaScript Obfuscator has reached over **1 million npm downloads per week**. I am currently preparing an **EB-1 immigration case** and collecting independent evidence of the project’s real-world professional usage and impact. + +If you use JavaScript Obfuscator in a company project — especially at a well-known company, large organization, or widely used product — I would be very grateful if you could contact me. + +Helpful evidence may include a brief confirmation or, ideally, a 1–2 page reference letter describing: + +- how your team or company used JavaScript Obfuscator; +- why you chose it; +- what problem it helped solve; +- whether it was used in production or an important internal workflow; +- your role and how you are familiar with the usage. + +I can provide a simple draft/template to make this easy. + +Please contact me at: **referenceletter@obfuscator.io** + +Thank you for supporting the project. + +--- + +### :rocket: Obfuscator.io with VM Obfuscation + +**Obfuscator.io** adds **VM-based bytecode obfuscation** to this package - your JavaScript functions are compiled to custom bytecode that runs on an embedded virtual machine. Each build produces unique opcodes and VM structure, making reverse engineering and automated deobfuscation dramatically harder. + +| Protection goal | Free (this package) | [obfuscator.io](https://obfuscator.io) | +| --- |-----------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| Rename identifiers | ✅ variable/function renaming | ✅ + VM-local symbols never exposed as JavaScript | +| Obscure strings | ✅ string array + base64/rc4 | ✅ + strings embedded in bytecode constants | +| Obscure control flow | ✅ control flow flattening | ✅ full bytecode virtualization, [`vmJumpsEncoding`](#vmjumpsencoding) (runtime-computed jump targets), [`vmDeadCodeInjection`](#vmdeadcodeinjection) (fake bytecode sequences) | +| Resist decompilation | ⚠️ output is still JavaScript | ✅ custom opcodes, [`vmStatefulOpcodes`](#vmstatefulopcodes) (position-dependent opcode mapping), [`vmMacroOps`](#vmmacroops) (fused instructions), [`vmDecoyOpcodes`](#vmdecoyopcodes) (fake opcode handlers) | +| Resist automated LLM-based analysis | ❌ fully vulnerable (no LLM-specific defenses) | ✅ bytecode encryption + anti-LLM defenses in [`vmSelfDefending`](#vmselfdefending) and [`vmDebugProtection`](#vmdebugProtection) | +| Encryption | ✅ [`stringArrayEncoding`](#stringarrayencoding) (base64/rc4 on extracted strings) | ✅ [`vmBytecodeEncoding`](#vmbytecodeencoding) (per-instruction encoding), [`vmBytecodeArrayEncoding`](#vmbytecodeArrayEncoding) (whole bytecode array as single block) | +| Anti-debugging | ✅ `debugProtection` (freezes browser DevTools) | ✅ [`vmDebugProtection`](#vmdebugProtection) (multi-layered anti-debugging and anti-analysis defenses) | +| Tamper detection | ✅ `selfDefending` (breaks if beautified) | ✅ [`vmSelfDefending`](#vmselfdefending) (multi-layered tamper detection, anti-hooking, anti-reverse-engineering protection) | +| Runs offline, no network | ✅ | ❌ uses obfuscator.io API (requires token) | + +[Visit Obfuscator.io](https://obfuscator.io) · [Pro API methods](#shield-pro-api-methods-vm-obfuscation) + +This package provides access to Obfuscator.io API via CLI and Node.js API. + +--- + JavaScript Obfuscator is a powerful free obfuscator for JavaScript, containing a variety of features which provide protection for your source code. **Key features:** +- VM bytecode obfuscation (via [Obfuscator.io](https://obfuscator.io/)) - variables renaming - strings extraction and encryption - dead code injection @@ -32,12 +73,15 @@ The example of obfuscated code: [github.com](https://github.com/javascript-obfus #### Plugins: * Webpack plugin: [webpack-obfuscator](https://github.com/javascript-obfuscator/webpack-obfuscator) * Webpack loader: [obfuscator-loader](https://github.com/javascript-obfuscator/obfuscator-loader) +* Esbuild plugin: [esbuild-javascript-obfuscator](https://www.npmjs.com/package/esbuild-javascript-obfuscator) * Gulp: [gulp-javascript-obfuscator](https://github.com/javascript-obfuscator/gulp-javascript-obfuscator) * Grunt: [grunt-contrib-obfuscator](https://github.com/javascript-obfuscator/grunt-contrib-obfuscator) * Rollup: [rollup-plugin-javascript-obfuscator](https://github.com/javascript-obfuscator/rollup-plugin-javascript-obfuscator) * Weex: [weex-devtool](https://www.npmjs.com/package/weex-devtool) * Malta: [malta-js-obfuscator](https://github.com/fedeghe/malta-js-obfuscator) * Netlify plugin: [netlify-plugin-js-obfuscator](https://www.npmjs.com/package/netlify-plugin-js-obfuscator) +* Snowpack plugin: [snowpack-javascript-obfuscator](https://www.npmjs.com/package/snowpack-javascript-obfuscator) +* Vite plugin: [vite-plugin-bundle-obfuscator](https://github.com/z0ffy/vite-plugin-bundle-obfuscator) [![npm version](https://badge.fury.io/js/javascript-obfuscator.svg)](https://badge.fury.io/js/javascript-obfuscator) [![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fjavascript-obfuscator%2Fjavascript-obfuscator.svg?type=shield)](https://app.fossa.io/projects/git%2Bgithub.com%2Fjavascript-obfuscator%2Fjavascript-obfuscator?ref=badge_shield) @@ -258,6 +302,171 @@ Returns a map object which keys are identifiers of source codes and values are ` Returns an options object for the passed options preset name. +--- + +## :shield: Pro API Methods (VM Obfuscation) + +The Pro API methods provide access to **VM-based bytecode obfuscation** through the [obfuscator.io](https://obfuscator.io) cloud service. VM obfuscation is the most advanced and secure form of code protection available, transforming your JavaScript functions into custom bytecode that runs on an embedded virtual machine. + +**Why VM Obfuscation?** +- **Strongest protection**: Code is converted to bytecode that cannot be directly understood +- **Anti-decompilation**: No standard JavaScript to reverse engineer +- **Customizable VM**: Each obfuscation generates unique opcodes and VM structure +- **Layered security**: Combine with other obfuscation options for defense in depth + +### Getting an API Token + +To use Pro API methods, you need a valid API token from [obfuscator.io](https://obfuscator.io): + +1. Create an account at [obfuscator.io](https://obfuscator.io) +2. Subscribe to a Pro, Team, or Business plan that includes API access +3. Generate your API token at [obfuscator.io/dashboard](https://obfuscator.io/dashboard) + +### `obfuscatePro(sourceCode, options, proApiConfig, onProgress?)` :new: + +**Async method** that obfuscates code using the Pro API with VM-based bytecode obfuscation. + +```javascript +const JavaScriptObfuscator = require('javascript-obfuscator'); + +const result = await JavaScriptObfuscator.obfuscatePro( + `function hello() { console.log("Hello World"); }`, + { + vmObfuscation: true, // Required! + compact: true + }, + { + apiToken: 'your_javascript_obfuscator_pro_api_token' + } +); + +console.log(result.getObfuscatedCode()); +``` + +**Parameters:** + +* `sourceCode` (`string`) – source code to obfuscate +* `options` (`Object`) – obfuscation options. **Must include at least one Pro feature: `vmObfuscation: true` or `parseHtml: true`** +* `apiConfig` (`Object`) – Pro API configuration: + * `apiToken` (`string`, required) – your API token from obfuscator.io + * `timeout` (`number`, optional) – request timeout in ms (default: `300000` - 5 minutes) + * `version` (`string`, optional) – Obfuscator.io version to use (e.g., `'5.0.3'`). Defaults to latest version if not specified. +* `onProgress` (`function`, optional) – callback for progress updates during obfuscation + +**Returns:** `Promise` + +**Throws:** `ApiError` if: +- No Pro features (`vmObfuscation` or `parseHtml`) are enabled in options +- API token is invalid or expired +- API request fails + +### Pro API with Specific Version + +You can specify which obfuscator version to use via the `version` option: + +```javascript +const result = await JavaScriptObfuscator.obfuscatePro( + sourceCode, + { + vmObfuscation: true + }, + { + apiToken: 'your_javascript_obfuscator_pro_api_token', + version: '5.0.3' // Use specific version + } +); +``` + +### Pro API with Progress Updates + +The API uses streaming mode to provide real-time progress updates during obfuscation: + +```javascript +const result = await JavaScriptObfuscator.obfuscatePro( + sourceCode, + { + vmObfuscation: true + }, + { + apiToken: 'your_javascript_obfuscator_pro_api_token' + }, + (message) => { + console.log('Progress:', message); + // Output: "Validating request...", "Authenticating...", "Obfuscating...", etc. + } +); +``` + +### Checking for Pro Features + +Use `ProApiClient.hasProFeatures()` to check if options require the Pro API: + +```javascript +const { ProApiClient } = require('javascript-obfuscator'); + +const options = { vmObfuscation: true, compact: true }; + +if (ProApiClient.hasProFeatures(options)) { + // Use obfuscatePro() - requires API token + const result = await JavaScriptObfuscator.obfuscatePro(sourceCode, options, { apiToken }); +} else { + // Use regular obfuscate() - no API token needed + const result = JavaScriptObfuscator.obfuscate(sourceCode, options); +} +``` + +Pro features include: +- `vmObfuscation: true` – VM-based bytecode obfuscation +- `parseHtml: true` – HTML parsing with inline JavaScript obfuscation + +### Error Handling + +```javascript +const { ApiError } = require('javascript-obfuscator'); + +try { + const result = await JavaScriptObfuscator.obfuscatePro(sourceCode, options, config); +} catch (error) { + if (error instanceof ApiError) { + console.error(`API Error (${error.statusCode}): ${error.message}`); + } else { + throw error; + } +} +``` + +### CLI Usage with Pro API + +You can also use Pro API features directly from the CLI by providing your API token: + +```sh +javascript-obfuscator input.js --pro-api-token YOUR_API_TOKEN --vm-obfuscation true -o output.js +``` + +With a specific obfuscator version: + +```sh +javascript-obfuscator input.js --pro-api-token YOUR_API_TOKEN --pro-api-version 5.0.3 --vm-obfuscation true -o output.js +``` + +**CLI Options:** +- `--pro-api-token ` – Your API token from [obfuscator.io](https://obfuscator.io) +- `--pro-api-version ` – Obfuscator.io version to use (optional, defaults to latest) + +The CLI automatically detects when Pro features (`vmObfuscation` or `parseHtml`) are enabled and routes the request through the Pro API. + +### Large File Uploads + +For files larger than ~4MB, the Pro API uses client-side uploads to Vercel Blob storage. To enable this feature, install the optional `@vercel/blob` package: + +```sh +npm install @vercel/blob +``` + +Without this package, large file obfuscation will fail with an error message prompting you to install it. + +--- + ## CLI usage See [CLI options](#cli-options). @@ -335,6 +544,8 @@ When using CLI this prefix will be added automatically. ## JavaScript Obfuscator Options +> :shield: **Looking for VM obfuscation?** Options like `vmObfuscation`, `parseHtml`, and every `vm*` option are Pro-only and require an API token from [obfuscator.io](https://obfuscator.io). Use them via the [`obfuscatePro()`](#shield-pro-api-methods-vm-obfuscation) method, or the `--pro-api-token` CLI flag — see [Pro API Methods](#shield-pro-api-methods-vm-obfuscation). + Following options are available for the JS Obfuscator: #### options: @@ -456,6 +667,37 @@ Following options are available for the JS Obfuscator: --target [browser, browser-no-eval, node] --transform-object-keys --unicode-escape-sequence + --pro-api-token + --pro-api-version + --vm-obfuscation + --vm-obfuscation-threshold + --vm-preprocess-identifiers + --vm-dynamic-opcodes + --vm-target-functions '' (comma separated) + --vm-exclude-functions '' (comma separated) + --vm-target-functions-mode [root, comment] + --vm-wrap-top-level-initializers + --vm-opcode-shuffle + --vm-bytecode-encoding + --vm-bytecode-array-encoding + --vm-bytecode-array-encoding-key + --vm-bytecode-array-encoding-key-getter + --vm-instruction-shuffle + --vm-jumps-encoding + --vm-decoy-opcodes + --vm-dead-code-injection + --vm-split-dispatcher + --vm-macro-ops + --vm-debug-protection + --vm-runtime-opcode-derivation + --vm-stateful-opcodes + --vm-stack-encoding + --vm-randomize-keys + --vm-indirect-dispatch + --vm-compact-dispatcher + --vm-bytecode-format [binary, json] + --parse-html + --strict-mode ``` @@ -1187,7 +1429,7 @@ Each `stringArray` value will be encoded by the randomly picked encoding from th Available values: * `'none'` (`boolean`): doesn't encode `stringArray` value * `'base64'` (`string`): encodes `stringArray` value using `base64` -* `'rc4'` (`string`): encodes `stringArray` value using `rc4`. **About 30-50% slower than `base64`, but more harder to get initial values.** It's recommended to disable [`unicodeEscapeSequence`](#unicodeescapesequence) option when using `rc4` encoding to prevent very large size of obfuscated code. +* `'rc4'` (`string`): encodes `stringArray` value using `rc4`. **About 30-50% slower than `base64`, but harder to get initial values.** It's recommended to disable [`unicodeEscapeSequence`](#unicodeescapesequence) option when using `rc4` encoding to prevent very large size of obfuscated code. For example with the following option values some `stringArray` value won't be encoded, and some values will be encoded with `base64` and `rc4` encoding: @@ -1639,6 +1881,320 @@ The performance will be at a relatively normal level +## Obfuscator.io Pro Options + +> :warning: **The following VM obfuscation/Pro options are available only via the [Obfuscator.io Pro API](https://obfuscator.io/).** +> +> To use these options, you need a Pro API token from [obfuscator.io](https://obfuscator.io) and must call the `obfuscatePro()` method instead of `obfuscate()`. See the [Pro API Methods](#shield-pro-api-methods-vm-obfuscation) section for details. + +### `vmObfuscation` +Type: `boolean` Default: `false` + +Enables VM-based bytecode obfuscation. When enabled, JavaScript functions are compiled into custom bytecode that runs on an embedded virtual machine. This provides the highest level of protection as the original code logic is completely transformed. + +**Example:** +Your readable code like `return qty * price` becomes a list of numbers like `[0x15,0x03,0x17,...]` that only the embedded VM interpreter can execute. The original logic is no longer visible as JavaScript. + +### `vmTargetFunctions` +Type: `string[]` Default: `[]` + +Specify exactly which root-level functions should get VM protection by name. + +**Example:** +```javascript +{ + vmObfuscation: true, + vmTargetFunctions: ['someFunctionName'] +} +``` + +**Result:** Only these three functions get VM-protected. Everything else stays as regular (but still obfuscated) JavaScript. Perfect for protecting sensitive license checks or authentication logic while keeping the rest of your code lean. + +### `vmExcludeFunctions` +Type: `string[]` Default: `[]` + +Specify root-level functions that should never get VM protection. Takes precedence over other settings. + +**Example:** +```javascript +{ + vmObfuscation: true, + vmExcludeFunctions: ['someFunctionName'] +} +``` + +**When to use:** Performance-critical root-level functions (animation loops, real-time data processing) can be excluded to avoid VM overhead while still protecting everything else. + +### `vmTargetFunctionsMode` +Type: `string` Default: `root` + +Controls how functions/methods are selected for VM obfuscation. + +| Mode | Description | +|------|------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `root` | Default behavior. Only root-level functions are considered for VM obfuscation. Uses `vmTargetFunctions` allow-list and `vmExcludeFunctions` deny-list to filter. | +| `comment` | Only functions/methods decorated with `/* javascript-obfuscator:vm */` comment are VM-obfuscated. Works with functions/methods at **any nesting level**. | + +**Example - Comment mode:** +```javascript +// Source code +function regularFunction() { + return 'not virtualized'; +} + +/* javascript-obfuscator:vm */ +function sensitiveFunction() { + return 'this will be VM-protected'; +} + +function outer() { + /* javascript-obfuscator:vm */ + function nestedSensitive() { + return 'nested but still VM-protected'; + } + return nestedSensitive(); +} +``` + +```javascript +// Obfuscator options +{ + vmObfuscation: true, + vmTargetFunctionsMode: 'comment' +} +``` + +**When to use:** When you need surgical control over exactly which functions get VM protection, especially nested functions that contain sensitive logic. Unlike `vmTargetFunctions` which only works with root-level named functions, comment mode lets you protect any function anywhere in your code. + +### `vmWrapTopLevelInitializers` +Type: `boolean` Default: `false` + +Wraps some top-level variable initializers in IIFEs (Immediately Invoked Function Expressions) so they can be VM-obfuscated. + +**What it does:** +Without this option, top-level constants and variables remain visible in the output: +```javascript +// Input +const MY_STRING = "my-string"; + +// Output (without vmWrapTopLevelInitializers) +const MY_STRING = "my-string"; // String is visible! +``` + +With this option enabled, the initializer is wrapped in an IIFE that gets VM-obfuscated: +```javascript +// Input +const MY_STRING = "my-string"; + +// Output (with vmWrapTopLevelInitializers: true) +const MY_STRING = (() => { return /* VM bytecode call */ })(); // String hidden in bytecode +``` + +**Note:** This option only works when `vmTargetFunctionsMode` is `'root'` (the default). + +### `vmDynamicOpcodes` +Type: `boolean` Default: `false` + +Makes the VM interpreter smaller and unique for each build. + +**What it does:** +1. **Filters unused instructions** - If your code doesn't use classes, class-related instructions are removed entirely +2. **Randomizes structure** - The order of instruction handlers is shuffled each build + +As the result - smaller output and each build looks different. + +### `vmBytecodeEncoding` +Type: `boolean` Default: `false` + +Encodes each bytecode instruction. Instructions are decoded one at a time during execution. + +### `vmBytecodeArrayEncoding` +Type: `boolean` Default: `false` + +Encodes the entire bytecode array as a single block. The array is decoded once at startup before execution begins. Use together with `vmBytecodeEncoding` for two layers of protection. + +### `vmBytecodeArrayEncodingKey` +Type: `string` Default: `''` + +Custom encryption key for bytecode array encoding. When set, this key is used instead of the default environment-derived key. The key must be provided at runtime via `vmBytecodeArrayEncodingKeyGetter`. + +This option externalizes the encryption key - it's not embedded in the obfuscated code itself. While the key is still accessible at runtime (and thus not truly secret), this separation prevents static analysis tools from finding the key by examining the code alone. + +**Important:** The key must be available **synchronously** when the obfuscated code loads. Use synchronous storage like cookies, localStorage, sessionStorage, global variables, or DOM elements (e.g., server-injected meta tags). Async methods like `fetch()` cannot be used directly in the key getter expression. + +### `vmBytecodeArrayEncodingKeyGetter` +Type: `string` Default: `''` + +**Synchronous** JavaScript expression that **returns** the encryption key at runtime. This expression is evaluated when the obfuscated code loads, and must return the same key that was provided in `vmBytecodeArrayEncodingKey`. + +**The obfuscated code will only work when the key getter returns exactly the same key that was used during obfuscation.** If the keys don't match, decryption will fail and the code will produce garbage or errors. If the key getter returns `undefined`, `null`, or an empty string, the code will throw an error: "VM decryption key not available". + +**Important:** The key should NOT be defined in the same JavaScript file/script as the obfuscated code. Doing so defeats the purpose of key externalization, as static analysis could still find the key. Store the key in a separate source: server-set cookies, localStorage populated by another script, server-injected HTML meta tags, or a global variable set by a different script that loads before the obfuscated code. + +Examples: +```ts +// From cookie +vmBytecodeArrayEncodingKeyGetter: "document.cookie.match(/vmKey=([^;]+)/)?.[1]" + +// From localStorage +vmBytecodeArrayEncodingKeyGetter: "localStorage.getItem('vmKey')" + +// From global variable +vmBytecodeArrayEncodingKeyGetter: "window.__VM_KEY__" + +// From meta tag (server-injected) +vmBytecodeArrayEncodingKeyGetter: "document.querySelector('meta[name=\"vm-key\"]').content" + +// From nested object +vmBytecodeArrayEncodingKeyGetter: "window.config.encryption.key" +``` + +**Usage example:** +```ts +// Build time +JavaScriptObfuscator.obfuscate(code, { + vmObfuscation: true, + vmBytecodeArrayEncoding: true, + vmBytecodeArrayEncodingKey: 'mySecretKey123', + vmBytecodeArrayEncodingKeyGetter: 'window.__VM_KEY__' +}); + +// Runtime - key must be set before obfuscated code runs +window.__VM_KEY__ = 'mySecretKey123'; +``` + +### `vmJumpsEncoding` +Type: `boolean` Default: `false` + +Encodes jump targets in the bytecode. Jump offsets are calculated at runtime, hiding the control flow structure (`if`/`else`, loops, etc.) from static analysis. + +### `vmDecoyOpcodes` +Type: `boolean` Default: `false` + +Adds fake opcode handlers to the VM dispatcher that are never called. For example, if the VM uses 20 real opcodes, this might add 30 fake handlers, making the interpreter appear more complex than it really is. + +### `vmDeadCodeInjection` +Type: `boolean` Default: `false` + +Injects fake bytecode sequences that are never executed. These look like real instructions but are skipped during runtime, confusing analysis tools that process them. + +### `vmMacroOps` +Type: `boolean` Default: `false` + +Combines common instruction sequences into single "macro" opcodes. For example, `LOAD + ADD + STORE` might become a single `MACRO_ADD_TO_VAR` instruction. This breaks pattern recognition and can improve performance. + +### `vmDebugProtection` +Type: `boolean` Default: `false` + +Adds multi-layered anti-debugging, anti-analysis, and anti-LLM defenses to the VM runtime. For best results, allow `unsafe-eval` in your Content Security Policy. Works best with `browser`/`browser-no-eval` targets. + +### `vmSelfDefending` +Type: `boolean` Default: `false` + +Adds multi-layered tamper detection, anti-hooking, and anti-reverse-engineering protection to the VM runtime. + +> :warning: This option force-enables [`vmBytecodeArrayEncoding`](#vmbytecodeArrayEncoding). + +Strongly recommended to use together with [`vmDebugProtection`](#vmDebugProtection), [`vmBytecodeArrayEncodingKey`](#vmbytecodeArrayEncodingKey), and [`vmBytecodeArrayEncodingKeyGetter`](#vmbytecodeArrayEncodingKeyGetter). + +### `vmStatefulOpcodes` +Type: `boolean` Default: `false` + +Makes opcode meanings depend on position in the bytecode. Each position has a different opcode-to-handler mapping derived from a seed, so the same opcode number performs different operations at different positions. + +### `vmStackEncoding` +Type: `boolean` Default: `false` + +Encrypts values on the VM stack during execution. Values are encoded when pushed and decoded when popped, so memory inspection shows encrypted data instead of actual values. + +This option heavily affects performance. + +### `vmCompactDispatcher` +Type: `boolean` Default: `false` + +Uses a single VM executor instead of dual executors (sync + generator). Reduces obfuscated code size but adds ~20% performance overhead on recursion-heavy code. + +- `false` (default): dual executors — optimal performance, larger output +- `true`: single executor — smaller output, slightly slower + +### `vmStringArrayBytecodeOnly` +Type: `boolean` Default: `false` + +When enabled, the string array will **only** extract strings from bytecode data — no other strings in the code are transformed. This force-enables `stringArray` even if it's not explicitly set. + +**Why use this:** Extracting all VM runtime strings to a string array is slow. This option targets only bytecode content for string array extraction, improving performance while still protecting bytecode constants. + +- When `vmBytecodeArrayEncoding: false` — strings inside bytecode constant pools (`c` arrays) are extracted +- When `vmBytecodeArrayEncoding: true` — top-level base64 encoded bytecode strings are extracted +- `stringArrayThreshold` still controls what percentage of those bytecode strings are extracted + + +### `strictMode` +Type: `boolean | null` Default: `null` + +Allows to specify how the obfuscator should treat code regarding JavaScript strict mode. + +Available values: +* `null` (default) - auto-detect strict mode from the code. If the code has explicit `'use strict'` directive, ES module syntax, or class methods, it's treated as strict mode. Otherwise, sloppy mode is assumed. +* `true` - force strict mode treatment for all code, even without explicit `'use strict'` directive. Use this when your code will run in strict mode context (e.g., in ES modules, bundlers, or modern frameworks). +* `false` - only explicit strict mode indicators (`'use strict'`, ES modules, class methods) are treated as strict. Parent scope inheritance still applies per JS spec. + +### `parseHtml` +Type: `boolean` Default: `false` + +Enables obfuscation of JavaScript within HTML ` + + + + +`; + +JavaScriptObfuscator.obfuscate(html, { + parseHtml: true, + stringArray: true +}); + +// output: HTML with only the marked script obfuscated +``` + ## Frequently Asked Questions ### What javascript versions are supported? @@ -1673,6 +2229,10 @@ See: [`Kind of variables`](#kind-of-variables) Try `renamePropertiesMode: 'safe'` option, if it still doesn't work, just disable this option. +## GitHub Sponsors + + + ## Backers Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/javascript-obfuscator#backer)] @@ -1709,7 +2269,7 @@ Support us with a monthly donation and help us continue our activities. [[Become -## Sponsors +## Open Collective Sponsors Become a sponsor and get your logo on our README on Github with a link to your site. @@ -1728,7 +2288,7 @@ Become a sponsor and get your logo on our README on Github with a link to your s ## License [![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fjavascript-obfuscator%2Fjavascript-obfuscator.svg?type=large)](https://app.fossa.io/projects/git%2Bgithub.com%2Fjavascript-obfuscator%2Fjavascript-obfuscator?ref=badge_large) -Copyright (C) 2016-2022 [Timofey Kachalov](http://github.com/sanex3339). +Copyright (C) 2016-2026 [Timofei Kachalov](http://github.com/sanex3339). Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: diff --git a/bin/javascript-obfuscator b/bin/javascript-obfuscator index 0946b4521..144f7b8ad 100755 --- a/bin/javascript-obfuscator +++ b/bin/javascript-obfuscator @@ -1,3 +1,6 @@ #!/usr/bin/env node -require('../dist/index.cli').obfuscate(process.argv); \ No newline at end of file +require('../dist/index.cli').obfuscate(process.argv).catch((error) => { + console.error(error.message); + process.exit(1); +}); \ No newline at end of file diff --git a/index.ts b/index.ts index 5fad2f096..30b327761 100644 --- a/index.ts +++ b/index.ts @@ -6,13 +6,18 @@ import { TObfuscationResultsObject } from './src/types/TObfuscationResultsObject import { TOptionsPreset } from './src/types/options/TOptionsPreset'; import { IObfuscationResult } from './src/interfaces/source-code/IObfuscationResult'; - -import { JavaScriptObfuscator } from './src/JavaScriptObfuscatorFacade'; +import { IProApiConfig, IProObfuscationResult, TProApiProgressCallback } from './src/interfaces/pro-api/IProApiClient'; +import { JavaScriptObfuscator, ApiError } from './src/JavaScriptObfuscatorFacade'; export type ObfuscatorOptions = TInputOptions; export interface ObfuscationResult extends IObfuscationResult {} +export interface ProObfuscationResult extends IProObfuscationResult {} + +export type { IProApiConfig, TProApiProgressCallback }; +export { ApiError }; + /** * @param {string} sourceCode * @param {ObfuscatorOptions} inputOptions @@ -30,6 +35,23 @@ export declare function obfuscateMultiple ; +/** + * Obfuscate code using the Pro API (obfuscator.io) + * Requires a valid API token and vmObfuscation: true + * + * @param {string} sourceCode - Source code to obfuscate + * @param {ObfuscatorOptions} inputOptions - Obfuscation options (must include vmObfuscation: true) + * @param {IProApiConfig} proApiConfig - Pro API configuration including API token + * @param {TProApiProgressCallback} onProgress - Optional callback for progress updates + * @returns {Promise} - Promise resolving to obfuscation result + */ +export declare function obfuscatePro ( + sourceCode: string, + inputOptions: ObfuscatorOptions, + proApiConfig: IProApiConfig, + onProgress?: TProApiProgressCallback +): Promise; + /** * @param {TOptionsPreset} optionsPreset * @returns {TInputOptions} diff --git a/package.json b/package.json index 35a30c2a4..c6c70fff4 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "javascript-obfuscator", - "version": "4.0.2", + "version": "5.5.0", "description": "JavaScript obfuscator", "keywords": [ "obfuscator", @@ -12,7 +12,7 @@ "js obfuscator" ], "engines": { - "node": "^12.22.0 || ^14.0.0 || ^16.0.0 || ^17.0.0 || >=18.0.0" + "node": ">=18.0.0" }, "main": "dist/index.js", "browser": "dist/index.browser.js", @@ -21,81 +21,88 @@ }, "types": "typings/index.d.ts", "dependencies": { - "@javascript-obfuscator/escodegen": "2.3.0", + "@javascript-obfuscator/escodegen": "2.4.2", "@javascript-obfuscator/estraverse": "5.4.0", - "acorn": "8.8.2", - "assert": "2.0.0", + "@vercel/blob": ">=0.23.0", + "acorn": "8.15.0", + "acorn-import-attributes": "^1.9.5", + "assert": "2.1.0", "chalk": "4.1.2", - "chance": "1.1.9", - "class-validator": "0.14.0", - "commander": "10.0.0", - "eslint-scope": "7.1.1", - "eslint-visitor-keys": "3.3.0", + "chance": "1.1.13", + "class-validator": "0.14.3", + "commander": "12.1.0", + "env-paths": "4.0.0", + "eslint-scope": "8.4.0", + "eslint-visitor-keys": "4.2.1", "fast-deep-equal": "3.1.3", - "inversify": "6.0.1", + "inversify": "7.11.0", "js-string-escape": "1.0.1", "md5": "2.3.0", - "mkdirp": "2.1.3", "multimatch": "5.0.0", - "opencollective-postinstall": "2.0.3", "process": "0.11.10", - "reflect-metadata": "0.1.13", - "source-map-support": "0.5.21", + "reflect-metadata": "0.2.2", "string-template": "1.0.0", "stringz": "2.1.0", - "tslib": "2.5.0" + "tslib": "2.8.1" }, "devDependencies": { "@istanbuljs/nyc-config-typescript": "1.0.2", - "@types/chai": "4.3.4", - "@types/chance": "1.1.3", - "@types/escodegen": "0.0.7", - "@types/eslint-scope": "3.7.4", + "@types/chai": "4.3.20", + "@types/chance": "1.1.7", + "@types/escodegen": "0.0.10", + "@types/eslint-scope": "3.7.7", "@types/eslint-visitor-keys": "1.0.0", - "@types/estraverse": "5.1.2", + "@types/estraverse": "5.1.7", "@types/estree": "0.0.51", - "@types/js-beautify": "1.13.3", - "@types/js-string-escape": "1.0.1", - "@types/md5": "2.3.2", - "@types/mkdirp": "1.0.2", - "@types/mocha": "10.0.1", + "@types/js-beautify": "1.14.3", + "@types/js-string-escape": "1.0.3", + "@types/md5": "2.3.6", + "@types/mocha": "10.0.10", "@types/multimatch": "4.0.0", - "@types/node": "18.13.0", + "@types/node": "22.10.2", "@types/rimraf": "3.0.2", - "@types/sinon": "10.0.13", - "@types/string-template": "1.0.2", - "@types/webpack-env": "1.18.0", - "@typescript-eslint/eslint-plugin": "5.51.0", - "@typescript-eslint/parser": "5.51.0", - "chai": "4.3.7", - "chai-exclude": "2.1.0", - "cross-env": "7.0.3", - "eslint": "8.34.0", - "eslint-plugin-import": "2.27.5", - "eslint-plugin-jsdoc": "40.0.0", + "@types/sinon": "17.0.4", + "@types/string-template": "1.0.7", + "@types/webpack-env": "1.18.8", + "@typescript-eslint/eslint-plugin": "7.18.0", + "@typescript-eslint/parser": "7.18.0", + "chai": "4.5.0", + "chai-exclude": "3.0.1", + "cross-env": "10.1.0", + "eslint": "8.57.1", + "eslint-config-prettier": "10.1.8", + "eslint-plugin-import": "2.32.0", + "eslint-plugin-jsdoc": "50.6.3", "eslint-plugin-no-null": "1.0.2", "eslint-plugin-prefer-arrow": "1.2.3", - "eslint-plugin-unicorn": "45.0.2", - "eslint-webpack-plugin": "4.0.0", - "fork-ts-checker-notifier-webpack-plugin": "6.0.0", - "fork-ts-checker-webpack-plugin": "7.3.0", - "husky": "8.0.3", - "js-beautify": "1.14.7", - "mocha": "10.2.0", - "nyc": "15.1.0", + "eslint-plugin-prettier": "5.5.4", + "eslint-plugin-unicorn": "56.0.1", + "eslint-webpack-plugin": "4.2.0", + "fork-ts-checker-notifier-webpack-plugin": "9.0.0", + "fork-ts-checker-webpack-plugin": "9.1.0", + "husky": "9.1.7", + "js-beautify": "1.15.4", + "mocha": "11.7.4", + "nyc": "17.1.0", + "parse5": "^8.0.0", "pjson": "1.0.9", - "rimraf": "4.1.2", - "sinon": "15.0.1", + "prettier": "3.6.2", + "rimraf": "6.0.1", + "sinon": "19.0.2", "source-map-resolve": "0.6.0", - "terser": "5.16.3", + "source-map-support": "0.5.21", + "terser": "5.44.0", "threads": "1.7.0", - "ts-loader": "9.4.2", - "ts-node": "10.9.1", - "typescript": "4.9.5", - "webpack": "5.75.0", - "webpack-cli": "5.0.1", + "ts-loader": "9.5.4", + "ts-node": "10.9.2", + "typescript": "5.9.3", + "webpack": "5.102.1", + "webpack-cli": "6.0.1", "webpack-node-externals": "3.0.0" }, + "resolutions": { + "multimatch/minimatch/brace-expansion": "^1.1.12" + }, "repository": { "type": "git", "url": "git+https://github.com/javascript-obfuscator/javascript-obfuscator.git" @@ -104,38 +111,31 @@ "scripts": { "start": "yarn run watch", "webpack:prod": "webpack --config ./webpack/webpack.node.config.js --config ./webpack/webpack.browser.config.js --mode production", - "build": "yarn run webpack:prod && yarn run eslint && yarn test", + "build": "yarn run webpack:prod && yarn run eslint", "build:typings": "rm -rf ./typings && tsc --project src/tsconfig.typings.json", "watch": "webpack --config ./webpack/webpack.node.config.js --mode development --watch", "test:dev": "ts-node --type-check test/dev/dev.ts", "test:devCompilePerformance": "ts-node test/dev/dev-compile-performance.ts", "test:devRuntimePerformance": "ts-node test/dev/dev-runtime-performance.ts", "test:full": "yarn run test:dev && yarn run test:mocha-coverage && yarn run test:mocha-memory-performance", - "test:mocha": "mocha --require source-map-support/register test/index.spec.ts --exit", - "test:mocha-coverage": "NODE_OPTIONS=--max-old-space-size=4096 nyc --reporter text-summary --no-clean yarn run test:mocha", + "test:mocha": "mocha --require ts-node/register --require source-map-support/register test/index.spec.ts --exit", + "test:mocha-coverage": "cross-env NODE_OPTIONS=--max-old-space-size=4096 nyc --reporter text-summary --no-clean yarn run test:mocha", "test:mocha-coverage:report": "nyc report --reporter=lcov", - "test:mocha-memory-performance": "cross-env NODE_OPTIONS=--max-old-space-size=280 mocha test/performance-tests/JavaScriptObfuscatorMemory.spec.ts", + "test:mocha-memory-performance": "cross-env NODE_OPTIONS=--max-old-space-size=280 mocha --require ts-node/register test/performance-tests/JavaScriptObfuscatorMemory.spec.ts", "test": "yarn run test:full", "eslint": "eslint src/**/*.ts", + "prettier": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"", + "prettier:check": "prettier --check \"src/**/*.ts\" \"test/**/*.ts\"", + "format": "yarn run prettier && yarn run eslint --fix", "git:addFiles": "git add .", - "postinstall": "opencollective-postinstall", - "precommit": "npm run build", - "prepublishOnly": "npm run build && npm run build:typings", + "precommit": "yarn run eslint", + "prepublishOnly": "yarn run build && yarn run build:typings", "prepare": "husky install" }, "author": { - "name": "Timofey Kachalov" + "name": "Timofei Kachalov" }, - "contributors": [ - "Timofey Kachalov (https://github.com/sanex3339)", - "Dmitry Zamotkin (https://github.com/zamotkin)" - ], + "contributors": ["Timofei Kachalov (https://github.com/sanex3339)", "Dmitry Zamotkin (https://github.com/zamotkin)"], "license": "BSD-2-Clause", - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/javascript-obfuscator" - }, - "collective": { - "url": "https://opencollective.com/javascript-obfuscator" - } + "packageManager": "yarn@1.22.21+sha512.ca75da26c00327d26267ce33536e5790f18ebd53266796fbb664d2a4a5116308042dd8ee7003b276a20eace7d3c5561c3577bdd71bcb67071187af124779620a" } diff --git a/src/ASTParserFacade.ts b/src/ASTParserFacade.ts index 565a3df97..ade6007c4 100644 --- a/src/ASTParserFacade.ts +++ b/src/ASTParserFacade.ts @@ -1,6 +1,9 @@ import * as acorn from 'acorn'; import * as ESTree from 'estree'; import chalk, { Chalk } from 'chalk'; +import { importAttributesOrAssertions } from 'acorn-import-attributes'; + +const AcornParser = acorn.Parser.extend(importAttributesOrAssertions); /** * Facade over AST parser `acorn` @@ -19,17 +22,14 @@ export class ASTParserFacade { /** * @type {acorn.Options['sourceType'][]} */ - private static readonly sourceTypes: acorn.Options['sourceType'][] = [ - 'script', - 'module' - ]; + private static readonly sourceTypes: acorn.Options['sourceType'][] = ['script', 'module']; /** * @param {string} sourceCode * @param {Options} config * @returns {Program} */ - public static parse (sourceCode: string, config: acorn.Options): ESTree.Program | never { + public static parse(sourceCode: string, config: acorn.Options): ESTree.Program | never { const sourceTypeLength: number = ASTParserFacade.sourceTypes.length; for (let i: number = 0; i < sourceTypeLength; i++) { @@ -40,11 +40,7 @@ export class ASTParserFacade { continue; } - throw new Error(ASTParserFacade.processParsingError( - sourceCode, - error.message, - error.loc - )); + throw new Error(ASTParserFacade.processParsingError(sourceCode, error.message, error.loc)); } } @@ -57,7 +53,7 @@ export class ASTParserFacade { * @param {acorn.Options["sourceType"]} sourceType * @returns {Program} */ - private static parseType ( + private static parseType( sourceCode: string, inputConfig: acorn.Options, sourceType: acorn.Options['sourceType'] @@ -65,13 +61,16 @@ export class ASTParserFacade { const comments: ESTree.Comment[] = []; const config: acorn.Options = { ...inputConfig, - allowAwaitOutsideFunction: true, + allowAwaitOutsideFunction: false, + allowReserved: true, + allowImportExportEverywhere: true, + allowReturnOutsideFunction: true, + allowSuperOutsideMethod: true, onComment: comments, sourceType }; - const program: acorn.Node & ESTree.Program = acorn - .parse(sourceCode, config); + const program: acorn.Node & ESTree.Program = AcornParser.parse(sourceCode, config); if (comments.length) { program.comments = comments; @@ -86,7 +85,7 @@ export class ASTParserFacade { * @param {Position | null} position * @returns {never} */ - private static processParsingError ( + private static processParsingError( sourceCode: string, errorMessage: string, position: ESTree.Position | null @@ -108,12 +107,10 @@ export class ASTParserFacade { const endErrorIndex: number = Math.min(errorLine.length, position.column + ASTParserFacade.nearestSymbolsCount); const formattedPointer: string = ASTParserFacade.colorError('>'); - const formattedCodeSlice: string = `...${ - errorLine.slice(startErrorIndex, endErrorIndex).replace(/^\s+/, '') - }...`; + const formattedCodeSlice: string = `...${errorLine + .slice(startErrorIndex, endErrorIndex) + .replace(/^\s+/, '')}...`; - throw new Error( - `ERROR at line ${position.line}: ${errorMessage}\n${formattedPointer} ${formattedCodeSlice}` - ); + throw new Error(`ERROR at line ${position.line}: ${errorMessage}\n${formattedPointer} ${formattedCodeSlice}`); } } diff --git a/src/JavaScriptObfuscator.ts b/src/JavaScriptObfuscator.ts index 4728c05a3..53381b977 100644 --- a/src/JavaScriptObfuscator.ts +++ b/src/JavaScriptObfuscator.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from './container/ServiceIdentifiers'; import * as acorn from 'acorn'; @@ -28,6 +28,7 @@ import { ecmaVersion } from './constants/EcmaVersion'; import { ASTParserFacade } from './ASTParserFacade'; import { NodeGuards } from './node/NodeGuards'; import { Utils } from './utils/Utils'; +import { AdvertisementUtils } from './utils/AdvertisementUtils'; @injectable() export class JavaScriptObfuscator implements IJavaScriptObfuscator { @@ -55,9 +56,7 @@ export class JavaScriptObfuscator implements IJavaScriptObfuscator { /** * @type {CodeTransformer[]} */ - private static readonly codeTransformersList: CodeTransformer[] = [ - CodeTransformer.HashbangOperatorTransformer - ]; + private static readonly codeTransformersList: CodeTransformer[] = [CodeTransformer.HashbangOperatorTransformer]; /** * @type {NodeTransformer[]} @@ -138,7 +137,7 @@ export class JavaScriptObfuscator implements IJavaScriptObfuscator { * @param {ILogger} logger * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.ICodeTransformersRunner) codeTransformersRunner: ICodeTransformersRunner, @inject(ServiceIdentifiers.INodeTransformersRunner) nodeTransformersRunner: INodeTransformersRunner, @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @@ -158,13 +157,21 @@ export class JavaScriptObfuscator implements IJavaScriptObfuscator { * @param {string} sourceCode * @returns {IObfuscationResult} */ - public obfuscate (sourceCode: string): IObfuscationResult { + public obfuscate(sourceCode: string): IObfuscationResult { + if (AdvertisementUtils.shouldShowAdvertisement()) { + this.logger.advertise(LoggingMessage.JavaScriptObfuscatorProAdFirstPart); + this.logger.advertise(LoggingMessage.JavaScriptObfuscatorProAdSecondPart); + } + if (typeof sourceCode !== 'string') { sourceCode = ''; } const timeStart: number = Date.now(); - this.logger.info(LoggingMessage.Version, Utils.buildVersionMessage(process.env.VERSION, process.env.BUILD_TIMESTAMP)); + this.logger.info( + LoggingMessage.Version, + Utils.buildVersionMessage(process.env.VERSION, process.env.BUILD_TIMESTAMP) + ); this.logger.info(LoggingMessage.ObfuscationStarted); this.logger.info(LoggingMessage.RandomGeneratorSeed, this.randomGenerator.getInputSeed()); @@ -181,7 +188,10 @@ export class JavaScriptObfuscator implements IJavaScriptObfuscator { const generatorOutput: IGeneratorOutput = this.generateCode(sourceCode, obfuscatedAstTree); // finalizing code transformations - generatorOutput.code = this.runCodeTransformationStage(generatorOutput.code, CodeTransformationStage.FinalizingTransformers); + generatorOutput.code = this.runCodeTransformationStage( + generatorOutput.code, + CodeTransformationStage.FinalizingTransformers + ); const obfuscationTime: number = (Date.now() - timeStart) / 1000; this.logger.success(LoggingMessage.ObfuscationCompleted, obfuscationTime); @@ -193,7 +203,7 @@ export class JavaScriptObfuscator implements IJavaScriptObfuscator { * @param {string} sourceCode * @returns {Program} */ - private parseCode (sourceCode: string): ESTree.Program { + private parseCode(sourceCode: string): ESTree.Program { return ASTParserFacade.parse(sourceCode, JavaScriptObfuscator.parseOptions); } @@ -201,13 +211,14 @@ export class JavaScriptObfuscator implements IJavaScriptObfuscator { * @param {Program} astTree * @returns {Program} */ - private transformAstTree (astTree: ESTree.Program): ESTree.Program { + private transformAstTree(astTree: ESTree.Program): ESTree.Program { astTree = this.runNodeTransformationStage(astTree, NodeTransformationStage.Initializing); - const isEmptyAstTree: boolean = NodeGuards.isProgramNode(astTree) - && !astTree.body.length - && !astTree.leadingComments - && !astTree.trailingComments; + const isEmptyAstTree: boolean = + NodeGuards.isProgramNode(astTree) && + !astTree.body.length && + !astTree.leadingComments && + !astTree.trailingComments; if (isEmptyAstTree) { this.logger.warn(LoggingMessage.EmptySourceCode); @@ -245,22 +256,22 @@ export class JavaScriptObfuscator implements IJavaScriptObfuscator { * @param {Program} astTree * @returns {IGeneratorOutput} */ - private generateCode (sourceCode: string, astTree: ESTree.Program): IGeneratorOutput { + private generateCode(sourceCode: string, astTree: ESTree.Program): IGeneratorOutput { const escodegenParams: escodegen.GenerateOptions = { ...JavaScriptObfuscator.escodegenParams, format: { compact: this.options.compact }, - ...this.options.sourceMap && { - ...this.options.sourceMapSourcesMode === SourceMapSourcesMode.SourcesContent + ...(this.options.sourceMap && { + ...(this.options.sourceMapSourcesMode === SourceMapSourcesMode.SourcesContent ? { - sourceMap: 'sourceMap', - sourceContent: sourceCode - } + sourceMap: 'sourceMap', + sourceContent: sourceCode + } : { - sourceMap: this.options.inputFileName || 'sourceMap' - } - } + sourceMap: this.options.inputFileName || 'sourceMap' + }) + }) }; const generatorOutput: IGeneratorOutput = escodegen.generate(astTree, escodegenParams); @@ -274,7 +285,7 @@ export class JavaScriptObfuscator implements IJavaScriptObfuscator { * @param {IGeneratorOutput} generatorOutput * @returns {IObfuscationResult} */ - private getObfuscationResult (generatorOutput: IGeneratorOutput): IObfuscationResult { + private getObfuscationResult(generatorOutput: IGeneratorOutput): IObfuscationResult { return this.obfuscationResultFactory(generatorOutput.code, generatorOutput.map); } @@ -283,7 +294,7 @@ export class JavaScriptObfuscator implements IJavaScriptObfuscator { * @param {CodeTransformationStage} codeTransformationStage * @returns {string} */ - private runCodeTransformationStage (code: string, codeTransformationStage: CodeTransformationStage): string { + private runCodeTransformationStage(code: string, codeTransformationStage: CodeTransformationStage): string { this.logger.info(LoggingMessage.CodeTransformationStage, codeTransformationStage); return this.codeTransformersRunner.transform( @@ -298,7 +309,10 @@ export class JavaScriptObfuscator implements IJavaScriptObfuscator { * @param {NodeTransformationStage} nodeTransformationStage * @returns {Program} */ - private runNodeTransformationStage (astTree: ESTree.Program, nodeTransformationStage: NodeTransformationStage): ESTree.Program { + private runNodeTransformationStage( + astTree: ESTree.Program, + nodeTransformationStage: NodeTransformationStage + ): ESTree.Program { this.logger.info(LoggingMessage.NodeTransformationStage, nodeTransformationStage); return this.nodeTransformersRunner.transform( diff --git a/src/JavaScriptObfuscatorCLIFacade.ts b/src/JavaScriptObfuscatorCLIFacade.ts index eb3f632c8..075f21be5 100644 --- a/src/JavaScriptObfuscatorCLIFacade.ts +++ b/src/JavaScriptObfuscatorCLIFacade.ts @@ -6,11 +6,12 @@ class JavaScriptObfuscatorCLIFacade { /** * @param {string[]} argv */ - public static obfuscate (argv: string[]): void { + public static async obfuscate(argv: string[]): Promise { const javaScriptObfuscatorCLI: JavaScriptObfuscatorCLI = new JavaScriptObfuscatorCLI(argv); javaScriptObfuscatorCLI.initialize(); - javaScriptObfuscatorCLI.run(); + + return javaScriptObfuscatorCLI.run(); } } diff --git a/src/JavaScriptObfuscatorFacade.ts b/src/JavaScriptObfuscatorFacade.ts index 2489c40b2..91356e7c3 100644 --- a/src/JavaScriptObfuscatorFacade.ts +++ b/src/JavaScriptObfuscatorFacade.ts @@ -10,6 +10,7 @@ import { TOptionsPreset } from './types/options/TOptionsPreset'; import { IInversifyContainerFacade } from './interfaces/container/IInversifyContainerFacade'; import { IJavaScriptObfuscator } from './interfaces/IJavaScriptObfsucator'; import { IObfuscationResult } from './interfaces/source-code/IObfuscationResult'; +import { IProApiConfig, IProObfuscationResult, TProApiProgressCallback } from './interfaces/pro-api/IProApiClient'; import { InversifyContainerFacade } from './container/InversifyContainerFacade'; import { Options } from './options/Options'; @@ -26,13 +27,14 @@ class JavaScriptObfuscatorFacade { * @param {TInputOptions} inputOptions * @returns {IObfuscationResult} */ - public static obfuscate (sourceCode: string, inputOptions: TInputOptions = {}): IObfuscationResult { + public static obfuscate(sourceCode: string, inputOptions: TInputOptions = {}): IObfuscationResult { const inversifyContainerFacade: IInversifyContainerFacade = new InversifyContainerFacade(); inversifyContainerFacade.load(sourceCode, '', inputOptions); - const javaScriptObfuscator: IJavaScriptObfuscator = inversifyContainerFacade - .get(ServiceIdentifiers.IJavaScriptObfuscator); + const javaScriptObfuscator: IJavaScriptObfuscator = inversifyContainerFacade.get( + ServiceIdentifiers.IJavaScriptObfuscator + ); const obfuscationResult: IObfuscationResult = javaScriptObfuscator.obfuscate(sourceCode); inversifyContainerFacade.unload(); @@ -45,7 +47,7 @@ class JavaScriptObfuscatorFacade { * @param {TInputOptions} inputOptions * @returns {TObfuscationResultsObject} */ - public static obfuscateMultiple > ( + public static obfuscateMultiple>( sourceCodesObject: TSourceCodesObject, inputOptions: TInputOptions = {} ): TObfuscationResultsObject { @@ -53,41 +55,71 @@ class JavaScriptObfuscatorFacade { throw new Error('Source codes object should be a plain object'); } - return Object - .keys(sourceCodesObject) - .reduce( - ( - acc: TObfuscationResultsObject, - sourceCodeIdentifier: keyof TSourceCodesObject, - index: number - ) => { - const identifiersPrefix: string = Utils.getIdentifiersPrefixForMultipleSources( - inputOptions.identifiersPrefix, - index - ); - - const sourceCode: string = sourceCodesObject[sourceCodeIdentifier]; - const sourceCodeOptions: TInputOptions = { - ...inputOptions, - identifiersPrefix - }; - - return { - ...acc, - [sourceCodeIdentifier]: JavaScriptObfuscatorFacade.obfuscate(sourceCode, sourceCodeOptions) - }; - }, - >{} - ); + return Object.keys(sourceCodesObject).reduce( + ( + acc: TObfuscationResultsObject, + sourceCodeIdentifier: keyof TSourceCodesObject, + index: number + ) => { + const identifiersPrefix: string = Utils.getIdentifiersPrefixForMultipleSources( + inputOptions.identifiersPrefix, + index + ); + + const sourceCode: string = sourceCodesObject[sourceCodeIdentifier]; + const sourceCodeOptions: TInputOptions = { + ...inputOptions, + identifiersPrefix + }; + + return { + ...acc, + [sourceCodeIdentifier]: JavaScriptObfuscatorFacade.obfuscate(sourceCode, sourceCodeOptions) + }; + }, + >{} + ); } /** * @param {TOptionsPreset} optionsPreset * @returns {TInputOptions} */ - public static getOptionsByPreset (optionsPreset: TOptionsPreset): TInputOptions { + public static getOptionsByPreset(optionsPreset: TOptionsPreset): TInputOptions { return Options.getOptionsByPreset(optionsPreset); } + + /** + * Obfuscate code using the Pro API (obfuscator.io) + * This method requires a valid API token from obfuscator.io and only works with VM obfuscation. + * Only available in Node.js environment. + * + * @param {string} sourceCode - Source code to obfuscate + * @param {TInputOptions} inputOptions - Obfuscation options (must include vmObfuscation: true) + * @param {IProApiConfig} proApiConfig - Pro API configuration including API token + * @param {TProApiProgressCallback} onProgress - Optional callback for progress updates (streaming mode only) + * @returns {Promise} - Promise resolving to obfuscation result + * @throws {ApiError} - If API returns an error or vmObfuscation is not enabled + */ + public static async obfuscatePro( + sourceCode: string, + inputOptions: TInputOptions, + proApiConfig: IProApiConfig, + onProgress?: TProApiProgressCallback + ): Promise { + if (typeof window !== 'undefined') { + const { ApiError } = await import('./pro-api/ApiError'); + + throw new ApiError('obfuscatePro is only available in Node.js environment', 500); + } + + const { ProApiClient } = await import('./pro-api/ProApiClient'); + const client = new ProApiClient(proApiConfig); + + return client.obfuscate(sourceCode, inputOptions, onProgress); + } } export { JavaScriptObfuscatorFacade as JavaScriptObfuscator }; +export { ApiError } from './pro-api/ApiError'; +export type { IProApiConfig, IProObfuscationResult, TProApiProgressCallback } from './interfaces/pro-api/IProApiClient'; diff --git a/src/analyzers/calls-graph-analyzer/CallsGraphAnalyzer.ts b/src/analyzers/calls-graph-analyzer/CallsGraphAnalyzer.ts index 99c9b1db0..7e5d80960 100644 --- a/src/analyzers/calls-graph-analyzer/CallsGraphAnalyzer.ts +++ b/src/analyzers/calls-graph-analyzer/CallsGraphAnalyzer.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../container/ServiceIdentifiers'; import * as estraverse from '@javascript-obfuscator/estraverse'; @@ -72,8 +72,9 @@ export class CallsGraphAnalyzer implements ICallsGraphAnalyzer { */ private readonly calleeDataExtractorFactory: TCalleeDataExtractorFactory; - public constructor ( - @inject(ServiceIdentifiers.Factory__ICalleeDataExtractor) calleeDataExtractorFactory: TCalleeDataExtractorFactory + public constructor( + @inject(ServiceIdentifiers.Factory__ICalleeDataExtractor) + calleeDataExtractorFactory: TCalleeDataExtractorFactory ) { this.calleeDataExtractorFactory = calleeDataExtractorFactory; } @@ -82,16 +83,14 @@ export class CallsGraphAnalyzer implements ICallsGraphAnalyzer { * @param {number} blockScopeBodyLength * @returns {number} */ - public static getLimitIndex (blockScopeBodyLength: number): number { + public static getLimitIndex(blockScopeBodyLength: number): number { const lastIndex: number = blockScopeBodyLength - 1; const limitThresholdActivationIndex: number = CallsGraphAnalyzer.limitThresholdActivationLength - 1; let limitIndex: number = lastIndex; if (lastIndex > limitThresholdActivationIndex) { - limitIndex = Math.round( - limitThresholdActivationIndex + (lastIndex * CallsGraphAnalyzer.limitThreshold) - ); + limitIndex = Math.round(limitThresholdActivationIndex + lastIndex * CallsGraphAnalyzer.limitThreshold); if (limitIndex > lastIndex) { limitIndex = lastIndex; @@ -105,7 +104,7 @@ export class CallsGraphAnalyzer implements ICallsGraphAnalyzer { * @param {Program} astTree * @returns {ICallsGraphData[]} */ - public analyze (astTree: ESTree.Program): ICallsGraphData[] { + public analyze(astTree: ESTree.Program): ICallsGraphData[] { return this.analyzeRecursive(astTree.body); } @@ -113,7 +112,7 @@ export class CallsGraphAnalyzer implements ICallsGraphAnalyzer { * @param {NodeGuards[]} blockScopeBody * @returns {ICallsGraphData[]} */ - private analyzeRecursive (blockScopeBody: ESTree.Node[]): ICallsGraphData[] { + private analyzeRecursive(blockScopeBody: ESTree.Node[]): ICallsGraphData[] { const limitIndex: number = CallsGraphAnalyzer.getLimitIndex(blockScopeBody.length); const callsGraphData: ICallsGraphData[] = []; const blockScopeBodyLength: number = blockScopeBody.length; @@ -148,14 +147,16 @@ export class CallsGraphAnalyzer implements ICallsGraphAnalyzer { * @param {NodeGuards[]} blockScopeBody * @param {CallExpression} callExpressionNode */ - private analyzeCallExpressionNode ( + private analyzeCallExpressionNode( callsGraphData: ICallsGraphData[], blockScopeBody: ESTree.Node[], callExpressionNode: ESTree.CallExpression ): void { CallsGraphAnalyzer.calleeDataExtractorsList.forEach((calleeDataExtractorName: CalleeDataExtractor) => { - const calleeData: ICalleeData | null = this.calleeDataExtractorFactory(calleeDataExtractorName) - .extract(blockScopeBody, callExpressionNode.callee); + const calleeData: ICalleeData | null = this.calleeDataExtractorFactory(calleeDataExtractorName).extract( + blockScopeBody, + callExpressionNode.callee + ); if (!calleeData) { return; diff --git a/src/analyzers/calls-graph-analyzer/callee-data-extractors/AbstractCalleeDataExtractor.ts b/src/analyzers/calls-graph-analyzer/callee-data-extractors/AbstractCalleeDataExtractor.ts index 34381f6f1..444701c9a 100644 --- a/src/analyzers/calls-graph-analyzer/callee-data-extractors/AbstractCalleeDataExtractor.ts +++ b/src/analyzers/calls-graph-analyzer/callee-data-extractors/AbstractCalleeDataExtractor.ts @@ -12,5 +12,5 @@ export abstract class AbstractCalleeDataExtractor implements ICalleeDataExtracto * @param {Node} callee * @returns {ICalleeData} */ - public abstract extract (blockScopeBody: ESTree.Node[], callee: ESTree.Node): ICalleeData | null; + public abstract extract(blockScopeBody: ESTree.Node[], callee: ESTree.Node): ICalleeData | null; } diff --git a/src/analyzers/calls-graph-analyzer/callee-data-extractors/FunctionDeclarationCalleeDataExtractor.ts b/src/analyzers/calls-graph-analyzer/callee-data-extractors/FunctionDeclarationCalleeDataExtractor.ts index 8d7816462..ee5ce750a 100644 --- a/src/analyzers/calls-graph-analyzer/callee-data-extractors/FunctionDeclarationCalleeDataExtractor.ts +++ b/src/analyzers/calls-graph-analyzer/callee-data-extractors/FunctionDeclarationCalleeDataExtractor.ts @@ -1,4 +1,4 @@ -import { injectable } from 'inversify'; +import { injectable, injectFromBase } from 'inversify'; import * as estraverse from '@javascript-obfuscator/estraverse'; import * as ESTree from 'estree'; @@ -9,6 +9,7 @@ import { AbstractCalleeDataExtractor } from './AbstractCalleeDataExtractor'; import { NodeGuards } from '../../../node/NodeGuards'; import { NodeStatementUtils } from '../../../node/NodeStatementUtils'; +@injectFromBase() @injectable() export class FunctionDeclarationCalleeDataExtractor extends AbstractCalleeDataExtractor { /** @@ -16,7 +17,7 @@ export class FunctionDeclarationCalleeDataExtractor extends AbstractCalleeDataEx * @param {Identifier} callee * @returns {ICalleeData} */ - public extract (blockScopeBody: ESTree.Node[], callee: ESTree.Identifier): ICalleeData | null { + public extract(blockScopeBody: ESTree.Node[], callee: ESTree.Identifier): ICalleeData | null { if (!NodeGuards.isIdentifierNode(callee)) { return null; } @@ -41,7 +42,7 @@ export class FunctionDeclarationCalleeDataExtractor extends AbstractCalleeDataEx * @param {string} name * @returns {BlockStatement} */ - private getCalleeBlockStatement (targetNode: ESTree.Node, name: string): ESTree.BlockStatement | null { + private getCalleeBlockStatement(targetNode: ESTree.Node, name: string): ESTree.BlockStatement | null { let calleeBlockStatement: ESTree.BlockStatement | null = null; estraverse.traverse(targetNode, { diff --git a/src/analyzers/calls-graph-analyzer/callee-data-extractors/FunctionExpressionCalleeDataExtractor.ts b/src/analyzers/calls-graph-analyzer/callee-data-extractors/FunctionExpressionCalleeDataExtractor.ts index 606ca2384..c0b8e0c0d 100644 --- a/src/analyzers/calls-graph-analyzer/callee-data-extractors/FunctionExpressionCalleeDataExtractor.ts +++ b/src/analyzers/calls-graph-analyzer/callee-data-extractors/FunctionExpressionCalleeDataExtractor.ts @@ -1,4 +1,4 @@ -import { injectable } from 'inversify'; +import { injectable, injectFromBase } from 'inversify'; import * as estraverse from '@javascript-obfuscator/estraverse'; import * as ESTree from 'estree'; @@ -9,6 +9,7 @@ import { AbstractCalleeDataExtractor } from './AbstractCalleeDataExtractor'; import { NodeGuards } from '../../../node/NodeGuards'; import { NodeStatementUtils } from '../../../node/NodeStatementUtils'; +@injectFromBase() @injectable() export class FunctionExpressionCalleeDataExtractor extends AbstractCalleeDataExtractor { /** @@ -16,7 +17,10 @@ export class FunctionExpressionCalleeDataExtractor extends AbstractCalleeDataExt * @param {Identifier} callee * @returns {ICalleeData} */ - public extract (blockScopeBody: ESTree.Node[], callee: ESTree.Identifier | ESTree.FunctionExpression): ICalleeData | null { + public extract( + blockScopeBody: ESTree.Node[], + callee: ESTree.Identifier | ESTree.FunctionExpression + ): ICalleeData | null { let calleeName: string | null = null; let calleeBlockStatement: ESTree.BlockStatement | null = null; @@ -46,7 +50,7 @@ export class FunctionExpressionCalleeDataExtractor extends AbstractCalleeDataExt * @param {string} name * @returns {BlockStatement} */ - private getCalleeBlockStatement (targetNode: ESTree.Node, name: string): ESTree.BlockStatement | null { + private getCalleeBlockStatement(targetNode: ESTree.Node, name: string): ESTree.BlockStatement | null { let calleeBlockStatement: ESTree.BlockStatement | null = null; estraverse.traverse(targetNode, { diff --git a/src/analyzers/calls-graph-analyzer/callee-data-extractors/ObjectExpressionCalleeDataExtractor.ts b/src/analyzers/calls-graph-analyzer/callee-data-extractors/ObjectExpressionCalleeDataExtractor.ts index 1fabd1da7..8f24f7675 100644 --- a/src/analyzers/calls-graph-analyzer/callee-data-extractors/ObjectExpressionCalleeDataExtractor.ts +++ b/src/analyzers/calls-graph-analyzer/callee-data-extractors/ObjectExpressionCalleeDataExtractor.ts @@ -1,4 +1,4 @@ -import { injectable } from 'inversify'; +import { injectable, injectFromBase } from 'inversify'; import * as estraverse from '@javascript-obfuscator/estraverse'; import * as ESTree from 'estree'; @@ -11,6 +11,7 @@ import { AbstractCalleeDataExtractor } from './AbstractCalleeDataExtractor'; import { NodeGuards } from '../../../node/NodeGuards'; import { NodeStatementUtils } from '../../../node/NodeStatementUtils'; +@injectFromBase() @injectable() export class ObjectExpressionCalleeDataExtractor extends AbstractCalleeDataExtractor { /** @@ -18,7 +19,10 @@ export class ObjectExpressionCalleeDataExtractor extends AbstractCalleeDataExtra * @param {string | number} nextItemInCallsChain * @returns {boolean} */ - private static isValidTargetPropertyNode (propertyNode: ESTree.Property, nextItemInCallsChain: string | number): boolean { + private static isValidTargetPropertyNode( + propertyNode: ESTree.Property, + nextItemInCallsChain: string | number + ): boolean { if (!propertyNode.key) { return false; } @@ -38,7 +42,7 @@ export class ObjectExpressionCalleeDataExtractor extends AbstractCalleeDataExtra * @param {MemberExpression} callee * @returns {ICalleeData} */ - public extract (blockScopeBody: ESTree.Node[], callee: ESTree.MemberExpression): ICalleeData | null { + public extract(blockScopeBody: ESTree.Node[], callee: ESTree.MemberExpression): ICalleeData | null { if (!NodeGuards.isMemberExpressionNode(callee)) { return null; } @@ -49,7 +53,8 @@ export class ObjectExpressionCalleeDataExtractor extends AbstractCalleeDataExtra return null; } - const functionExpressionName: string | number | null = objectMembersCallsChain[objectMembersCallsChain.length - 1]; + const functionExpressionName: string | number | null = + objectMembersCallsChain[objectMembersCallsChain.length - 1]; const calleeBlockStatement: ESTree.BlockStatement | null = this.getCalleeBlockStatement( NodeStatementUtils.getParentNodeWithStatements(blockScopeBody[0]), objectMembersCallsChain @@ -74,7 +79,7 @@ export class ObjectExpressionCalleeDataExtractor extends AbstractCalleeDataExtra * @param {MemberExpression} memberExpression * @returns {TObjectMembersCallsChain} */ - private createObjectMembersCallsChain ( + private createObjectMembersCallsChain( currentChain: TObjectMembersCallsChain, memberExpression: ESTree.MemberExpression ): TObjectMembersCallsChain { @@ -83,10 +88,7 @@ export class ObjectExpressionCalleeDataExtractor extends AbstractCalleeDataExtra currentChain.unshift(memberExpression.property.name); } else if ( NodeGuards.isLiteralNode(memberExpression.property) && - ( - typeof memberExpression.property.value === 'string' || - typeof memberExpression.property.value === 'number' - ) + (typeof memberExpression.property.value === 'string' || typeof memberExpression.property.value === 'number') ) { currentChain.unshift(memberExpression.property.value); } else { @@ -108,7 +110,7 @@ export class ObjectExpressionCalleeDataExtractor extends AbstractCalleeDataExtra * @param {TObjectMembersCallsChain} objectMembersCallsChain * @returns {BlockStatement} */ - private getCalleeBlockStatement ( + private getCalleeBlockStatement( targetNode: ESTree.Node, objectMembersCallsChain: TObjectMembersCallsChain ): ESTree.BlockStatement | null { @@ -144,7 +146,7 @@ export class ObjectExpressionCalleeDataExtractor extends AbstractCalleeDataExtra * @param {TObjectMembersCallsChain} objectMembersCallsChain * @returns {BlockStatement} */ - private findCalleeBlockStatement ( + private findCalleeBlockStatement( objectExpressionProperties: (ESTree.Property | ESTree.SpreadElement)[], objectMembersCallsChain: TObjectMembersCallsChain ): ESTree.BlockStatement | null { diff --git a/src/analyzers/number-numerical-expression-analyzer/NumberNumericalExpressionAnalyzer.ts b/src/analyzers/number-numerical-expression-analyzer/NumberNumericalExpressionAnalyzer.ts index 79efad5c9..557e3bed5 100644 --- a/src/analyzers/number-numerical-expression-analyzer/NumberNumericalExpressionAnalyzer.ts +++ b/src/analyzers/number-numerical-expression-analyzer/NumberNumericalExpressionAnalyzer.ts @@ -37,9 +37,7 @@ export class NumberNumericalExpressionAnalyzer implements INumberNumericalExpres /** * @param {IRandomGenerator} randomGenerator */ - public constructor ( - @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator - ) { + public constructor(@inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator) { this.randomGenerator = randomGenerator; } @@ -48,10 +46,7 @@ export class NumberNumericalExpressionAnalyzer implements INumberNumericalExpres * @param {number} additionalPartsCount * @returns {TNumberNumericalExpressionData} */ - public analyze ( - number: number, - additionalPartsCount: number - ): TNumberNumericalExpressionData { + public analyze(number: number, additionalPartsCount: number): TNumberNumericalExpressionData { if (isNaN(number)) { throw new Error('Given value is NaN'); } @@ -70,7 +65,7 @@ export class NumberNumericalExpressionAnalyzer implements INumberNumericalExpres * @param {number} additionalPartsCount * @returns {number[]} */ - private generateAdditionParts (number: number, additionalPartsCount: number): number[] { + private generateAdditionParts(number: number, additionalPartsCount: number): number[] { const additionParts = []; const upperNumberLimit: number = Math.min(Math.abs(number * 2), Number.MAX_SAFE_INTEGER); @@ -115,7 +110,7 @@ export class NumberNumericalExpressionAnalyzer implements INumberNumericalExpres * @param {number} number * @returns {number | number[]} */ - private mixWithMultiplyParts (number: number): number | number[] { + private mixWithMultiplyParts(number: number): number | number[] { const shouldMixWithMultiplyParts: boolean = this.randomGenerator.getMathRandom() > 0.5; if (!shouldMixWithMultiplyParts || number === 0) { @@ -125,8 +120,8 @@ export class NumberNumericalExpressionAnalyzer implements INumberNumericalExpres let factors: number[] | null = this.numberFactorsMap.get(number) ?? null; if (!factors) { - factors = NumberUtils.getFactors(number); - this.numberFactorsMap.set(number, factors); + factors = NumberUtils.getFactors(number); + this.numberFactorsMap.set(number, factors); } if (!factors.length) { diff --git a/src/analyzers/prevailing-kind-of-variables-analyzer/PrevailingKindOfVariablesAnalyzer.ts b/src/analyzers/prevailing-kind-of-variables-analyzer/PrevailingKindOfVariablesAnalyzer.ts index c3e2fa623..cbfb43f50 100644 --- a/src/analyzers/prevailing-kind-of-variables-analyzer/PrevailingKindOfVariablesAnalyzer.ts +++ b/src/analyzers/prevailing-kind-of-variables-analyzer/PrevailingKindOfVariablesAnalyzer.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../container/ServiceIdentifiers'; import * as estraverse from '@javascript-obfuscator/estraverse'; @@ -24,18 +24,17 @@ export class PrevailingKindOfVariablesAnalyzer implements IPrevailingKindOfVaria /** * @type {ESTree.VariableDeclaration['kind']} */ - private prevailingKindOfVariables: ESTree.VariableDeclaration['kind'] = PrevailingKindOfVariablesAnalyzer.defaultKindOfVariables; + private prevailingKindOfVariables: ESTree.VariableDeclaration['kind'] = + PrevailingKindOfVariablesAnalyzer.defaultKindOfVariables; - public constructor ( - @inject(ServiceIdentifiers.IArrayUtils) arrayUtils: IArrayUtils - ) { + public constructor(@inject(ServiceIdentifiers.IArrayUtils) arrayUtils: IArrayUtils) { this.arrayUtils = arrayUtils; } /** * @param {Program} astTree */ - public analyze (astTree: ESTree.Program): void { + public analyze(astTree: ESTree.Program): void { const variableKinds: ESTree.VariableDeclaration['kind'][] = []; estraverse.traverse(astTree, { @@ -48,14 +47,15 @@ export class PrevailingKindOfVariablesAnalyzer implements IPrevailingKindOfVaria } }); - this.prevailingKindOfVariables = this.arrayUtils.findMostOccurringElement(variableKinds) - ?? PrevailingKindOfVariablesAnalyzer.defaultKindOfVariables; + this.prevailingKindOfVariables = + this.arrayUtils.findMostOccurringElement(variableKinds) ?? + PrevailingKindOfVariablesAnalyzer.defaultKindOfVariables; } /** * @returns {VariableDeclaration["kind"]} */ - public getPrevailingKind (): ESTree.VariableDeclaration['kind'] { + public getPrevailingKind(): ESTree.VariableDeclaration['kind'] { return this.prevailingKindOfVariables; } } diff --git a/src/analyzers/scope-analyzer/ScopeAnalyzer.ts b/src/analyzers/scope-analyzer/ScopeAnalyzer.ts index 2d04ae1d4..a976f5f16 100644 --- a/src/analyzers/scope-analyzer/ScopeAnalyzer.ts +++ b/src/analyzers/scope-analyzer/ScopeAnalyzer.ts @@ -1,5 +1,6 @@ -import { injectable, } from 'inversify'; +import { injectable } from 'inversify'; +import * as acorn from 'acorn'; import * as eslintScope from 'eslint-scope'; import * as estraverse from '@javascript-obfuscator/estraverse'; import { KEYS, VisitorKeys } from 'eslint-visitor-keys'; @@ -27,10 +28,7 @@ export class ScopeAnalyzer implements IScopeAnalyzer { /** * @type {acorn.Options['sourceType'][]} */ - private static readonly sourceTypes: acorn.Options['sourceType'][] = [ - 'script', - 'module' - ]; + private static readonly sourceTypes: acorn.Options['sourceType'][] = ['script', 'module']; /** * @type {number} @@ -42,13 +40,18 @@ export class ScopeAnalyzer implements IScopeAnalyzer { */ private scopeManager: eslintScope.ScopeManager | null = null; + /** + * @type {eslintScope.ScopeManager | null} + */ + private sanitizedScopeManager: eslintScope.ScopeManager | null = null; + /** * `eslint-scope` reads `ranges` property of a nodes * Should attach that property to the some custom nodes * * @param {Node} astTree */ - private static attachMissingRanges (astTree: ESTree.Node): void { + private static attachMissingRanges(astTree: ESTree.Node): void { estraverse.replace(astTree, { enter: (node: ESTree.Node, parentNode: ESTree.Node | null): ESTree.Node => { if (!node.range) { @@ -67,16 +70,19 @@ export class ScopeAnalyzer implements IScopeAnalyzer { * @param {Node} node * @returns {boolean} */ - private static isRootNode (node: ESTree.Node): boolean { + private static isRootNode(node: ESTree.Node): boolean { return NodeGuards.isProgramNode(node) || node.parentNode === node; } /** * @param {Program} astTree */ - public analyze (astTree: ESTree.Node): void { + public analyze(astTree: ESTree.Node): void { const sourceTypeLength: number = ScopeAnalyzer.sourceTypes.length; + this.scopeManager = null; + this.sanitizedScopeManager = null; + ScopeAnalyzer.attachMissingRanges(astTree); for (let i: number = 0; i < sourceTypeLength; i++) { @@ -86,6 +92,11 @@ export class ScopeAnalyzer implements IScopeAnalyzer { sourceType: ScopeAnalyzer.sourceTypes[i] }); + // Fix Annex B function hoisting references + // eslint-scope doesn't implement Annex B semantics where function declarations + // in blocks also create a var-hoisted binding in the enclosing function scope + this.fixAnnexBFunctionHoisting(); + return; } catch (error) { if (i < sourceTypeLength - 1) { @@ -103,29 +114,135 @@ export class ScopeAnalyzer implements IScopeAnalyzer { * @param {Node} node * @returns {Scope} */ - public acquireScope (node: ESTree.Node): eslintScope.Scope { + public acquireScope(node: ESTree.Node): eslintScope.Scope { if (!this.scopeManager) { throw new Error('Scope manager is not defined'); } - const scope: eslintScope.Scope | null = this.scopeManager.acquire( - node, - ScopeAnalyzer.isRootNode(node) - ); + const scope: eslintScope.Scope | null = this.scopeManager.acquire(node, ScopeAnalyzer.isRootNode(node)); if (!scope) { throw new Error('Cannot acquire scope for node'); } - this.sanitizeScopes(scope); + if (this.sanitizedScopeManager !== this.scopeManager) { + this.sanitizeScopes(scope); + this.sanitizedScopeManager = this.scopeManager; + } return scope; } + /** + * Checks whether a scope for the given node is already available in the current + * scope manager (i.e. `analyze` has been run for the tree this node belongs to). + * + * @param {Node} node + * @returns {boolean} + */ + public isAnalyzed(node: ESTree.Node): boolean { + return !!this.scopeManager?.acquire(node, ScopeAnalyzer.isRootNode(node)); + } + + /** + * Fix Annex B function hoisting references. + * + * In non-strict mode, function declarations in blocks have dual binding: + * 1. A block-scoped binding (handled by eslint-scope) + * 2. A var-hoisted binding in the enclosing function scope (NOT handled by eslint-scope) + * + * This method merges block-scoped function declarations into the enclosing + * function scope and links unresolved references. + */ + private fixAnnexBFunctionHoisting(): void { + if (!this.scopeManager) { + return; + } + + this.walkScopes(this.scopeManager.globalScope, (scope: eslintScope.Scope) => { + if (scope.type !== 'block' && scope.type !== 'switch') { + return; + } + + // Skip strict mode scopes - Annex B doesn't apply + if (scope.isStrict) { + return; + } + + const functionScope = scope.variableScope; + + if (!functionScope) { + return; + } + + for (let i = scope.variables.length - 1; i >= 0; i--) { + const variable = scope.variables[i]; + + const isFunctionDeclaration = variable.defs.some( + (def) => def.type === 'FunctionName' && def.node?.type === 'FunctionDeclaration' + ); + + if (!isFunctionDeclaration) { + continue; + } + + // Find existing variable with the same name in function scope (shadowing case) + const outerVariable = functionScope.variables.find((v) => v.name === variable.name && v !== variable); + + // Per Annex B.3.3, hoisting only applies if outer binding is var/function (not let/const) + const isOuterLetOrConst = outerVariable?.defs.some( + (def) => def.type === 'Variable' && (def.parent?.kind === 'let' || def.parent?.kind === 'const') + ); + + // Skip Annex B hoisting if there's a let/const with the same name + if (isOuterLetOrConst) { + continue; + } + + const targetVariable = outerVariable ?? variable; + + if (outerVariable) { + // Merge inner function's identifiers and references into outer + outerVariable.identifiers.push(...variable.identifiers); + outerVariable.references.push(...variable.references); + } else { + // Move variable to function scope so references can find it + functionScope.variables.push(variable); + } + + // Remove from block scope + scope.variables.splice(i, 1); + + // Link "through" references with matching name to the target variable + this.linkThroughReferences(variable.name, functionScope, targetVariable); + } + }); + } + + /** + * Link unresolved "through" references to a variable. + * + * @param {string} name - The variable name to match + * @param {Scope} scope - The scope to start searching from + * @param {Variable} targetVariable - The variable to link references to + */ + private linkThroughReferences(name: string, scope: eslintScope.Scope, targetVariable: eslintScope.Variable): void { + for (let i = scope.through.length - 1; i >= 0; i--) { + if (scope.through[i].identifier.name === name) { + targetVariable.references.push(scope.through[i]); + scope.through.splice(i, 1); + } + } + + for (const childScope of scope.childScopes) { + this.linkThroughReferences(name, childScope, targetVariable); + } + } + /** * @param {Scope} scope */ - private sanitizeScopes (scope: eslintScope.Scope): void { + private sanitizeScopes(scope: eslintScope.Scope): void { scope.childScopes.forEach((childScope: eslintScope.Scope) => { // fix of class scopes // trying to move class scope references to the parent scope @@ -137,13 +254,19 @@ export class ScopeAnalyzer implements IScopeAnalyzer { // class name variable is always first const classNameVariable: eslintScope.Variable = childScope.variables[0]; - const upperVariable: eslintScope.Variable | undefined = childScope.upper.variables - .find((variable: eslintScope.Variable) => { - const isValidClassNameVariable: boolean = classNameVariable.defs - .some((definition: eslintScope.Definition) => definition.type === 'ClassName'); + const upperVariable: eslintScope.Variable | undefined = childScope.upper.variables.find( + (variable: eslintScope.Variable) => { + const isValidClassNameVariable: boolean = classNameVariable.defs.some( + (definition: eslintScope.Definition) => definition.type === 'ClassName' + ); + + const isImportBinding: boolean = variable.defs.some( + (definition: eslintScope.Definition) => definition.type === 'ImportBinding' + ); - return isValidClassNameVariable && variable.name === classNameVariable.name; - }); + return isValidClassNameVariable && variable.name === classNameVariable.name && !isImportBinding; + } + ); upperVariable?.references.push(...childScope.variables[0].references); } @@ -153,4 +276,18 @@ export class ScopeAnalyzer implements IScopeAnalyzer { this.sanitizeScopes(childScope); } } + + /** + * Walk through all scopes in the scope tree + * + * @param {Scope} scope - Starting scope + * @param {Function} callback - Function to call for each scope + */ + private walkScopes(scope: eslintScope.Scope, callback: (scope: eslintScope.Scope) => void): void { + callback(scope); + + for (const childScope of scope.childScopes) { + this.walkScopes(childScope, callback); + } + } } diff --git a/src/analyzers/string-array-storage-analyzer/StringArrayStorageAnalyzer.ts b/src/analyzers/string-array-storage-analyzer/StringArrayStorageAnalyzer.ts index f10acb78d..3de30cd09 100644 --- a/src/analyzers/string-array-storage-analyzer/StringArrayStorageAnalyzer.ts +++ b/src/analyzers/string-array-storage-analyzer/StringArrayStorageAnalyzer.ts @@ -1,9 +1,10 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../container/ServiceIdentifiers'; import * as estraverse from '@javascript-obfuscator/estraverse'; import * as ESTree from 'estree'; +import { TStringArrayEncoding } from '../../types/options/TStringArrayEncoding'; import { TStringLiteralNode } from '../../types/node/TStringLiteralNode'; import { IOptions } from '../../interfaces/options/IOptions'; @@ -12,6 +13,8 @@ import { IStringArrayStorage } from '../../interfaces/storages/string-array-tran import { IStringArrayStorageAnalyzer } from '../../interfaces/analyzers/string-array-storage-analyzer/IStringArrayStorageAnalyzer'; import { IStringArrayStorageItemData } from '../../interfaces/storages/string-array-transformers/IStringArrayStorageItem'; +import { StringArrayEncoding } from '../../enums/node-transformers/string-array-transformers/StringArrayEncoding'; + import { NodeGuards } from '../../node/NodeGuards'; import { NodeLiteralUtils } from '../../node/NodeLiteralUtils'; import { NodeMetadata } from '../../node/NodeMetadata'; @@ -26,6 +29,14 @@ export class StringArrayStorageAnalyzer implements IStringArrayStorageAnalyzer { */ private static readonly minimumLengthForStringArray: number = 3; + /** + * Matches a lone (unpaired) surrogate code unit. Because of the `u` flag, valid surrogate pairs are + * iterated as a single code point outside the `\uD800-\uDFFF` range, so only unpaired surrogates match. + * + * @type {RegExp} + */ + private static readonly loneSurrogateRegExp: RegExp = /[\uD800-\uDFFF]/u; + /** * @type {IOptions} */ @@ -51,10 +62,10 @@ export class StringArrayStorageAnalyzer implements IStringArrayStorageAnalyzer { * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.IStringArrayStorage) stringArrayStorage: IStringArrayStorage, @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, - @inject(ServiceIdentifiers.IOptions) options: IOptions, + @inject(ServiceIdentifiers.IOptions) options: IOptions ) { this.stringArrayStorage = stringArrayStorage; this.randomGenerator = randomGenerator; @@ -64,7 +75,7 @@ export class StringArrayStorageAnalyzer implements IStringArrayStorageAnalyzer { /** * @param {Program} astTree */ - public analyze (astTree: ESTree.Program): void { + public analyze(astTree: ESTree.Program): void { if (!this.options.stringArray) { return; } @@ -92,7 +103,7 @@ export class StringArrayStorageAnalyzer implements IStringArrayStorageAnalyzer { * @param {Literal} literalNode * @param {Node} parentNode */ - public analyzeLiteralNode (literalNode: ESTree.Literal, parentNode: ESTree.Node): void { + public analyzeLiteralNode(literalNode: ESTree.Literal, parentNode: ESTree.Node): void { if (!NodeLiteralUtils.isStringLiteralNode(literalNode)) { return; } @@ -111,18 +122,15 @@ export class StringArrayStorageAnalyzer implements IStringArrayStorageAnalyzer { /** * @param {TStringLiteralNode} literalNode */ - public addItemDataForLiteralNode (literalNode: TStringLiteralNode): void { - this.stringArrayStorageData.set( - literalNode, - this.stringArrayStorage.getOrThrow(literalNode.value) - ); + public addItemDataForLiteralNode(literalNode: TStringLiteralNode): void { + this.stringArrayStorageData.set(literalNode, this.stringArrayStorage.getOrThrow(literalNode.value)); } /** * @param {Literal} literalNode * @returns {IStringArrayStorageItemData | undefined} */ - public getItemDataForLiteralNode (literalNode: ESTree.Literal): IStringArrayStorageItemData | undefined { + public getItemDataForLiteralNode(literalNode: ESTree.Literal): IStringArrayStorageItemData | undefined { return this.stringArrayStorageData.get(literalNode); } @@ -130,15 +138,38 @@ export class StringArrayStorageAnalyzer implements IStringArrayStorageAnalyzer { * @param {TStringLiteralNode} literalNode * @returns {boolean} */ - private shouldAddValueToStringArray (literalNode: TStringLiteralNode): boolean { + private shouldAddValueToStringArray(literalNode: TStringLiteralNode): boolean { + // `base64` and `rc4` encodings rely on `encodeURIComponent`/`decodeURIComponent`, which cannot + // represent lone (unpaired) surrogate code units. Keeping such values inline avoids a + // `URIError: URI malformed` crash while still producing valid obfuscated code. + // Fixes https://github.com/javascript-obfuscator/javascript-obfuscator/issues/1431 + if (this.isProhibitedStringArrayValue(literalNode.value)) { + return false; + } + const isForceTransformNode: boolean = NodeMetadata.isForceTransformNode(literalNode); if (isForceTransformNode) { return true; } - return literalNode.value.length >= StringArrayStorageAnalyzer.minimumLengthForStringArray - && !!this.options.stringArrayThreshold - && this.randomGenerator.getMathRandom() <= this.options.stringArrayThreshold; + return ( + literalNode.value.length >= StringArrayStorageAnalyzer.minimumLengthForStringArray && + !!this.options.stringArrayThreshold && + this.randomGenerator.getMathRandom() <= this.options.stringArrayThreshold + ); + } + + /** + * @param {string} value + * @returns {boolean} + */ + private isProhibitedStringArrayValue(value: string): boolean { + const hasUnicodeEncoding: boolean = this.options.stringArrayEncoding.some( + (encoding: TStringArrayEncoding): boolean => + encoding === StringArrayEncoding.Base64 || encoding === StringArrayEncoding.Rc4 + ); + + return hasUnicodeEncoding && StringArrayStorageAnalyzer.loneSurrogateRegExp.test(value); } } diff --git a/src/cli/JavaScriptObfuscatorCLI.ts b/src/cli/JavaScriptObfuscatorCLI.ts index 2a10bd115..95eb5b78d 100644 --- a/src/cli/JavaScriptObfuscatorCLI.ts +++ b/src/cli/JavaScriptObfuscatorCLI.ts @@ -4,10 +4,13 @@ import * as path from 'path'; import { TInputCLIOptions } from '../types/options/TInputCLIOptions'; import { TInputOptions } from '../types/options/TInputOptions'; +import { TOptionsPreset } from '../types/options/TOptionsPreset'; import { IFileData } from '../interfaces/cli/IFileData'; import { IInitializable } from '../interfaces/IInitializable'; import { IObfuscationResult } from '../interfaces/source-code/IObfuscationResult'; +import { ProApiClient } from '../pro-api/ProApiClient'; +import { IProObfuscationResult } from '../interfaces/pro-api/IProApiClient'; import { initializable } from '../decorators/Initializable'; @@ -22,11 +25,10 @@ import { StringArrayEncoding } from '../enums/node-transformers/string-array-tra import { StringArrayIndexesType } from '../enums/node-transformers/string-array-transformers/StringArrayIndexesType'; import { StringArrayWrappersType } from '../enums/node-transformers/string-array-transformers/StringArrayWrappersType'; -import { DEFAULT_PRESET } from '../options/presets/Default'; - import { ArraySanitizer } from './sanitizers/ArraySanitizer'; import { BooleanSanitizer } from './sanitizers/BooleanSanitizer'; +import { Options } from '../options/Options'; import { CLIUtils } from './utils/CLIUtils'; import { IdentifierNamesCacheFileUtils } from './utils/IdentifierNamesCacheFileUtils'; import { JavaScriptObfuscator } from '../JavaScriptObfuscatorFacade'; @@ -34,14 +36,15 @@ import { Logger } from '../logger/Logger'; import { ObfuscatedCodeFileUtils } from './utils/ObfuscatedCodeFileUtils'; import { SourceCodeFileUtils } from './utils/SourceCodeFileUtils'; import { Utils } from '../utils/Utils'; +import { VMTargetFunctionsMode } from '../pro-api/enums/VMTargetFunctionsMode'; +import { VMBytecodeFormat } from '../pro-api/enums/VMBytecodeFormat'; +import { StrictModeSanitizer } from './sanitizers/StrictModeSanitizer'; export class JavaScriptObfuscatorCLI implements IInitializable { /** * @type {string[]} */ - public static readonly availableInputExtensions: string[] = [ - '.js' - ]; + public static readonly availableInputExtensions: string[] = ['.js', '.mjs', '.cjs']; /** * @type {BufferEncoding} @@ -102,68 +105,76 @@ export class JavaScriptObfuscatorCLI implements IInitializable { /** * @param {string[]} argv */ - public constructor (argv: string[]) { + public constructor(argv: string[]) { this.rawArguments = argv; this.arguments = argv.slice(2); } /** * @param {TInputCLIOptions} inputOptions + * @param {commander.Command} command * @returns {TInputOptions} */ - private static buildOptions (inputOptions: TInputCLIOptions): TInputOptions { - const inputCLIOptions: TInputOptions = JavaScriptObfuscatorCLI.filterOptions(inputOptions); + private static buildOptions(inputOptions: TInputCLIOptions, command: commander.Command): TInputOptions { + const inputCLIOptions: TInputOptions = JavaScriptObfuscatorCLI.filterOptions(inputOptions, command); const configFilePath: string | undefined = inputOptions.config; const configFileLocation: string = configFilePath ? path.resolve(configFilePath, '.') : ''; const configFileOptions: TInputOptions = configFileLocation ? CLIUtils.getUserConfig(configFileLocation) : {}; + const presetName: TOptionsPreset = + inputCLIOptions.optionsPreset ?? configFileOptions.optionsPreset ?? OptionsPreset.Default; + const presetOptions: TInputOptions = Options.getOptionsByPreset(presetName); + return { - ...DEFAULT_PRESET, + ...presetOptions, ...configFileOptions, ...inputCLIOptions }; } /** + * Filters out options that were not explicitly set by the user. + * Commander.js sets default values for all options, which would + * override preset values. Only user-provided options should be kept. + * * @param {TObject} options + * @param {commander.Command} command * @returns {TInputOptions} */ - private static filterOptions (options: TInputCLIOptions): TInputOptions { + private static filterOptions(options: TInputCLIOptions, command: commander.Command): TInputOptions { const filteredOptions: TInputOptions = {}; - Object - .keys(options) - .forEach((option: keyof TInputCLIOptions) => { - if (options[option] === undefined) { - return; - } + Object.keys(options).forEach((option: keyof TInputCLIOptions) => { + if (options[option] === undefined) { + return; + } + + if (command.getOptionValueSource(String(option)) === 'default') { + return; + } - filteredOptions[option] = options[option]; - }); + filteredOptions[option] = options[option]; + }); return filteredOptions; } - public initialize (): void { + public initialize(): void { this.commands = new commander.Command(); this.configureCommands(); this.configureHelp(); this.inputPath = path.normalize(this.commands.args[0] || ''); - this.inputCLIOptions = JavaScriptObfuscatorCLI.buildOptions(this.commands.opts()); - this.sourceCodeFileUtils = new SourceCodeFileUtils( - this.inputPath, - this.inputCLIOptions - ); - this.obfuscatedCodeFileUtils = new ObfuscatedCodeFileUtils( - this.inputPath, - this.inputCLIOptions + this.inputCLIOptions = JavaScriptObfuscatorCLI.buildOptions(this.commands.opts(), this.commands); + this.sourceCodeFileUtils = new SourceCodeFileUtils(this.inputPath, this.inputCLIOptions); + this.obfuscatedCodeFileUtils = new ObfuscatedCodeFileUtils(this.inputPath, this.inputCLIOptions); + this.identifierNamesCacheFileUtils = new IdentifierNamesCacheFileUtils( + this.inputCLIOptions.identifierNamesCachePath ); - this.identifierNamesCacheFileUtils = new IdentifierNamesCacheFileUtils(this.inputCLIOptions.identifierNamesCachePath); } - public run (): void { + public async run(): Promise { const canShowHelp: boolean = !this.arguments.length || this.arguments.includes('--help'); if (canShowHelp) { @@ -174,44 +185,23 @@ export class JavaScriptObfuscatorCLI implements IInitializable { const sourceCodeData: IFileData[] = this.sourceCodeFileUtils.readSourceCode(); - this.processSourceCodeData(sourceCodeData); + await this.processSourceCodeData(sourceCodeData); } - private configureCommands (): void { + private configureCommands(): void { this.commands .usage(' [options]') - .version( - Utils.buildVersionMessage(process.env.VERSION, process.env.BUILD_TIMESTAMP), - '-v, --version' - ) - .option( - '-o, --output ', - 'Output path for obfuscated code' - ) - .option( - '--compact ', - 'Disable one line output code compacting', - BooleanSanitizer - ) - .option( - '--config ', - 'Name of js / json config file' - ) - .option( - '--control-flow-flattening ', - 'Enables control flow flattening', - BooleanSanitizer - ) + .version(Utils.buildVersionMessage(process.env.VERSION, process.env.BUILD_TIMESTAMP), '-v, --version') + .option('-o, --output ', 'Output path for obfuscated code') + .option('--compact ', 'Disable one line output code compacting', BooleanSanitizer) + .option('--config ', 'Name of js / json config file') + .option('--control-flow-flattening ', 'Enables control flow flattening', BooleanSanitizer) .option( '--control-flow-flattening-threshold ', 'The probability that the control flow flattening transformation will be applied to the node', parseFloat ) - .option( - '--dead-code-injection ', - 'Enables dead code injection', - BooleanSanitizer - ) + .option('--dead-code-injection ', 'Enables dead code injection', BooleanSanitizer) .option( '--dead-code-injection-threshold ', 'The probability that the dead code injection transformation will be applied to the node', @@ -239,7 +229,7 @@ export class JavaScriptObfuscatorCLI implements IInitializable { ) .option( '--domain-lock-redirect-url ', - 'Allows the browser to be redirected to a passed URL if the source code isn\'t run on the domains specified by --domain-lock', + "Allows the browser to be redirected to a passed URL if the source code isn't run on the domains specified by --domain-lock" ) .option( '--exclude (comma separated, without whitespaces)', @@ -251,42 +241,31 @@ export class JavaScriptObfuscatorCLI implements IInitializable { 'Enables force transformation of string literals, which being matched by passed RegExp patterns (comma separated)', ArraySanitizer ) - .option( - '--identifier-names-cache-path ', - 'Sets path for identifier names cache' - ) + .option('--identifier-names-cache-path ', 'Sets path for identifier names cache') .option( '--identifier-names-generator ', 'Sets identifier names generator. ' + - `Values: ${CLIUtils.stringifyOptionAvailableValues(IdentifierNamesGenerator)}. ` + - `Default: ${IdentifierNamesGenerator.HexadecimalIdentifierNamesGenerator}` - ) - .option( - '--identifiers-prefix ', - 'Sets prefix for all global identifiers' + `Values: ${CLIUtils.stringifyOptionAvailableValues(IdentifierNamesGenerator)}. ` + + `Default: ${IdentifierNamesGenerator.HexadecimalIdentifierNamesGenerator}` ) + .option('--identifiers-prefix ', 'Sets prefix for all global identifiers') .option( '--identifiers-dictionary (comma separated, without whitespaces)', 'Identifiers dictionary (comma separated) for `--identifier-names-generator dictionary` option', ArraySanitizer ) .option( - '--ignore-imports ', 'Prevents obfuscation of `require` and `dynamic` imports', - BooleanSanitizer - ) - .option( - '--log ', 'Enables logging of the information to the console', - BooleanSanitizer - ) - .option( - '--numbers-to-expressions ', 'Enables numbers conversion to expressions', + '--ignore-imports ', + 'Prevents obfuscation of `require` and `dynamic` imports', BooleanSanitizer ) + .option('--log ', 'Enables logging of the information to the console', BooleanSanitizer) + .option('--numbers-to-expressions ', 'Enables numbers conversion to expressions', BooleanSanitizer) .option( '--options-preset ', 'Allows to set options preset. ' + - `Values: ${CLIUtils.stringifyOptionAvailableValues(OptionsPreset)}. ` + - `Default: ${OptionsPreset.Default}` + `Values: ${CLIUtils.stringifyOptionAvailableValues(OptionsPreset)}. ` + + `Default: ${OptionsPreset.Default}` ) .option( '--reserved-names (comma separated, without whitespaces)', @@ -299,38 +278,33 @@ export class JavaScriptObfuscatorCLI implements IInitializable { ArraySanitizer ) .option( - '--rename-globals ', 'Allows to enable obfuscation of global variable and function names with declaration', + '--rename-globals ', + 'Allows to enable obfuscation of global variable and function names with declaration', BooleanSanitizer ) .option( - '--rename-properties ', 'UNSAFE: Enables renaming of property names. This probably MAY break your code', + '--rename-properties ', + 'UNSAFE: Enables renaming of property names. This probably MAY break your code', BooleanSanitizer ) .option( '--rename-properties-mode ', 'Specify `--rename-properties` option mode. ' + - `Values: ${CLIUtils.stringifyOptionAvailableValues(RenamePropertiesMode)}. ` + - `Default: ${RenamePropertiesMode.Safe}` + `Values: ${CLIUtils.stringifyOptionAvailableValues(RenamePropertiesMode)}. ` + + `Default: ${RenamePropertiesMode.Safe}` ) .option( '--seed ', 'Sets seed for random generator. This is useful for creating repeatable results.', parseFloat ) + .option('--self-defending ', 'Disables self-defending for obfuscated code', BooleanSanitizer) .option( - '--self-defending ', - 'Disables self-defending for obfuscated code', - BooleanSanitizer - ) - .option( - '--simplify ', 'Enables additional code obfuscation through simplification', - BooleanSanitizer - ) - .option( - '--source-map ', - 'Enables source map generation', + '--simplify ', + 'Enables additional code obfuscation through simplification', BooleanSanitizer ) + .option('--source-map ', 'Enables source map generation', BooleanSanitizer) .option( '--source-map-base-url ', 'Sets base url to the source map import url when `--source-map-mode=separate`' @@ -342,25 +316,21 @@ export class JavaScriptObfuscatorCLI implements IInitializable { .option( '--source-map-mode ', 'Specify source map output mode. ' + - `Values: ${CLIUtils.stringifyOptionAvailableValues(SourceMapMode)}. ` + - `Default: ${SourceMapMode.Separate}` + `Values: ${CLIUtils.stringifyOptionAvailableValues(SourceMapMode)}. ` + + `Default: ${SourceMapMode.Separate}` ) .option( '--source-map-sources-mode ', 'Specify source map sources mode. ' + - `Values: ${CLIUtils.stringifyOptionAvailableValues(SourceMapSourcesMode)}. ` + - `Default: ${SourceMapSourcesMode.SourcesContent}` + `Values: ${CLIUtils.stringifyOptionAvailableValues(SourceMapSourcesMode)}. ` + + `Default: ${SourceMapSourcesMode.SourcesContent}` ) .option( '--split-strings ', 'Splits literal strings into chunks with length of `splitStringsChunkLength` option value', BooleanSanitizer ) - .option( - '--split-strings-chunk-length ', - 'Sets chunk length of `splitStrings` option', - parseFloat - ) + .option('--split-strings-chunk-length ', 'Sets chunk length of `splitStrings` option', parseFloat) .option( '--string-array ', 'Enables gathering of all literal strings into an array and replacing every literal string with an array call', @@ -379,15 +349,15 @@ export class JavaScriptObfuscatorCLI implements IInitializable { .option( '--string-array-encoding (comma separated, without whitespaces)', 'Encodes each string in strings array using base64 or rc4 (this option can slow down your code speed). ' + - `Values: ${CLIUtils.stringifyOptionAvailableValues(StringArrayEncoding)}. ` + - `Default: ${StringArrayEncoding.None}`, + `Values: ${CLIUtils.stringifyOptionAvailableValues(StringArrayEncoding)}. ` + + `Default: ${StringArrayEncoding.None}`, ArraySanitizer ) .option( '--string-array-indexes-type (comma separated, without whitespaces)', 'Encodes each string in strings array using base64 or rc4 (this option can slow down your code speed). ' + - `Values: ${CLIUtils.stringifyOptionAvailableValues(StringArrayIndexesType)}. ` + - `Default: ${StringArrayIndexesType.HexadecimalNumber}`, + `Values: ${CLIUtils.stringifyOptionAvailableValues(StringArrayIndexesType)}. ` + + `Default: ${StringArrayIndexesType.HexadecimalNumber}`, ArraySanitizer ) .option( @@ -396,13 +366,11 @@ export class JavaScriptObfuscatorCLI implements IInitializable { BooleanSanitizer ) .option( - '--string-array-rotate ', 'Enable rotation of string array values during obfuscation', - BooleanSanitizer - ) - .option( - '--string-array-shuffle ', 'Randomly shuffles string array items', + '--string-array-rotate ', + 'Enable rotation of string array values during obfuscation', BooleanSanitizer ) + .option('--string-array-shuffle ', 'Randomly shuffles string array items', BooleanSanitizer) .option( '--string-array-wrappers-count ', 'Sets the count of wrappers for the string array inside each root or function scope', @@ -421,8 +389,8 @@ export class JavaScriptObfuscatorCLI implements IInitializable { .option( '--string-array-wrappers-type ', 'Allows to select a type of the wrappers that are appending by the `--string-array-wrappers-count` option. ' + - `Values: ${CLIUtils.stringifyOptionAvailableValues(StringArrayWrappersType)}. ` + - `Default: ${StringArrayWrappersType.Variable}` + `Values: ${CLIUtils.stringifyOptionAvailableValues(StringArrayWrappersType)}. ` + + `Default: ${StringArrayWrappersType.Variable}` ) .option( '--string-array-threshold ', @@ -432,27 +400,172 @@ export class JavaScriptObfuscatorCLI implements IInitializable { .option( '--target ', 'Allows to set target environment for obfuscated code. ' + - `Values: ${CLIUtils.stringifyOptionAvailableValues(ObfuscationTarget)}. ` + - `Default: ${ObfuscationTarget.Browser}` + `Values: ${CLIUtils.stringifyOptionAvailableValues(ObfuscationTarget)}. ` + + `Default: ${ObfuscationTarget.Browser}` ) + .option('--transform-object-keys ', 'Enables transformation of object keys', BooleanSanitizer) .option( - '--transform-object-keys ', - 'Enables transformation of object keys', + '--unicode-escape-sequence ', + 'Allows to enable/disable string conversion to unicode escape sequence', BooleanSanitizer ) .option( - '--unicode-escape-sequence ', - 'Allows to enable/disable string conversion to unicode escape sequence', + '--pro-api-token ', + 'API token for Pro obfuscation via obfuscator.io (enables VM obfuscation via cloud API)' + ) + .option('--pro-api-version ', 'Obfuscator version to use with Pro API (e.g., "5.0.0")') + .option( + '--vm-obfuscation ', + 'Enables VM-based bytecode obfuscation for functions', + BooleanSanitizer + ) + .option( + '--vm-obfuscation-threshold ', + 'The probability that VM obfuscation will be applied to a function (Default: 1, Min: 0, Max: 1)', + parseFloat + ) + .option( + '--vm-preprocess-identifiers ', + 'Preprocesses identifiers before VM transformation (Default: false)', + BooleanSanitizer + ) + .option( + '--vm-dynamic-opcodes ', + 'Dynamically assembles VM dispatcher with shuffled case order and filters unused opcodes based on code analysis', BooleanSanitizer ) + .option( + '--vm-target-functions (comma separated, without whitespaces)', + 'List of specific function names to apply VM obfuscation to (comma separated)', + ArraySanitizer + ) + .option( + '--vm-exclude-functions (comma separated, without whitespaces)', + 'List of function names to exclude from VM obfuscation (comma separated)', + ArraySanitizer + ) + .option( + '--vm-target-functions-mode ', + 'Controls how functions are selected for VM obfuscation. ' + + `Values: ${CLIUtils.stringifyOptionAvailableValues(VMTargetFunctionsMode)}. ` + + `Default: ${VMTargetFunctionsMode.Root}` + ) + .option( + '--vm-wrap-top-level-initializers ', + 'Wraps top-level variable initializers in IIFEs so they can be VM-obfuscated (Default: false)', + BooleanSanitizer + ) + .option( + '--vm-opcode-shuffle ', + 'Randomizes the numeric values assigned to each opcode (Default: false)', + BooleanSanitizer + ) + .option( + '--vm-bytecode-encoding ', + 'Enables bytecode encryption with per-function keys (Default: false)', + BooleanSanitizer + ) + .option( + '--vm-bytecode-array-encoding ', + 'Enables encrypted bytecode array with lazy decryption (Default: false)', + BooleanSanitizer + ) + .option('--vm-bytecode-array-encoding-key ', 'Custom static key for bytecode array encoding') + .option( + '--vm-bytecode-array-encoding-key-getter ', + 'Custom key getter function code for bytecode array encoding' + ) + .option( + '--vm-instruction-shuffle ', + 'Shuffles instruction order within basic blocks (Default: false)', + BooleanSanitizer + ) + .option( + '--vm-jumps-encoding ', + 'Enables jump target encoding to prevent CFG reconstruction (Default: false)', + BooleanSanitizer + ) + .option( + '--vm-decoy-opcodes ', + 'Enables insertion of decoy opcodes and dead instructions (Default: false)', + BooleanSanitizer + ) + .option( + '--vm-dead-code-injection ', + 'Enables dead code injection with opaque predicates in bytecode (Default: false)', + BooleanSanitizer + ) + .option( + '--vm-split-dispatcher ', + 'Splits the VM interpreter into multiple category-based dispatchers (Default: false)', + BooleanSanitizer + ) + .option( + '--vm-macro-ops ', + 'Enables macro-op fusion to combine common instruction sequences (Default: false)', + BooleanSanitizer + ) + .option( + '--vm-debug-protection ', + 'Enables anti-debugging measures with state corruption (Default: false)', + BooleanSanitizer + ) + .option( + '--vm-runtime-opcode-derivation ', + 'Enables runtime opcode derivation from seeds instead of static mappings (Default: false)', + BooleanSanitizer + ) + .option( + '--vm-stateful-opcodes ', + 'Enables position-based stateful opcode decoding to prevent pattern matching (Default: false)', + BooleanSanitizer + ) + .option( + '--vm-stack-encoding ', + 'Enables stack value encoding to prevent stack inspection (Default: false)', + BooleanSanitizer + ) + .option( + '--vm-randomize-keys ', + 'Randomizes bytecode property keys to prevent pattern matching (Default: false)', + BooleanSanitizer + ) + .option( + '--vm-indirect-dispatch ', + 'Uses indirect dispatch via handler function table instead of switch statement (Default: false)', + BooleanSanitizer + ) + .option( + '--vm-compact-dispatcher ', + 'Uses a single unified dispatcher for both sync and generator execution, reducing code size (Default: false)', + BooleanSanitizer + ) + .option( + '--vm-bytecode-format ', + 'Sets the bytecode storage format. ' + + `Values: ${CLIUtils.stringifyOptionAvailableValues(VMBytecodeFormat)}. ` + + `Default: ${VMBytecodeFormat.Binary}` + ) + .option( + '--parse-html ', + 'Enables obfuscation of JavaScript within HTML