Securing JavaScript Code in NativeScript with Obfuscator in Webpack


One of the most important steps before releasing an app is to secure your source code, especially if you use JavaScript or TypeScript. Since .js files can be easily reverse-engineered, we need a way to make that process harder.

In this article, I’ll show you how to use javascript-obfuscator and webpack-obfuscator in your NativeScript project.

What is Obfuscation?

Obfuscation is a technique used to make JavaScript code harder to read. Its purpose:

  • Reduce the risk of code theft
  • Make reverse engineering more difficult
  • Protect sensitive application logic

Example before and after obfuscation:

const apiUrl = "https://api.myapp.com/data";

After obfuscation:

var _0x23a1=["\x68\x74\x74\x70\x73\x3A\x2F\x2F..."];
(function(_0xabc){ ... })();

Steps

1. Install the Obfuscator

npm install javascript-obfuscator webpack-obfuscator --save-dev

2. Configure webpack.config.js

Add this to your webpack.config.js file:

const { webpack } = require('@nativescript/webpack');
const JavaScriptObfuscator = require('webpack-obfuscator');

module.exports = env => {
  webpack.init(env);

  webpack.chainWebpack(config => {
    config.plugin('obfuscator')
      .use(JavaScriptObfuscator, [
        {
          rotateStringArray: true,
          stringArray: true,
          stringArrayEncoding: ['rc4'],
          stringArrayThreshold: 0.75,
          selfDefending: true,
          controlFlowFlattening: true,
          deadCodeInjection: true,
          identifierNamesGenerator: 'hexadecimal',
          renameGlobals: true,
          splitStrings: true,
          splitStringsChunkLength: 6
        },
        ['vendor.js']
      ]);
  });

  return webpack.resolveConfig();
};

3. Build the Application

Without signing:

ns build android --release --bundle

With signing:

ns build android --release --bundle --aab \
--key-store-path ./keystore.keystore \
--key-store-password yourPassword \
--key-store-alias yourAlias \
--key-store-alias-password yourPassword

4. Verify

Extract the .apk or .aab file, then open the bundle.js file located inside the assets/ or app/ folder.

If it works, you should see something like this:

var _0x23a1=["\x68\x74\x74\x70\x73\x3A\x2F\x2F..."];
(function(_0xabc){ ... })();

5. Additional Tips

  • Don’t obfuscate vendor.js or runtime.js — it may cause the app to crash
  • Always test your app thoroughly after building
  • If you want to obfuscate specific files only, use a pattern like ['**/main-page.js']

0/Post a Comment/Comments

Lebih baru Lebih lama