How to Protect Angular Code Against Theft and Reverse-Engineering
April 30th, 2024 | By Antonello Semeraro | 13 min read
Angular stands as one of the foremost JavaScript frameworks, its popularity brings forth significant security considerations, particularly regarding safeguarding Angular code from theft and reverse-engineering.
Following the launch of Angular 2, Google has unveiled five additional iterations within a span of merely two years. This TypeScript-based framework facilitates the streamlined creation of front-end applications for both web and mobile platforms.
The continuous emergence of new Angular applications underscores the critical need for developers to fortify their Angular code using robust obfuscation and protection methods.
This comprehensive tutorial delineates the process of seamlessly integrating Jscrambler within Angular's build mechanism in mere minutes. For those new to Angular, it is recommended to commence with the official Angular quickstart guide.
Protect Angular Code against Reverse-Engineering
Prerequisites
To successfully incorporate Jscrambler into the Angular build process, two primary steps are required:
Creation of an Angular application
Configuration of Jscrambler
How to create an Angular application
Our guide begins with utilizing a boilerplate application designed for Angular's latest versions. Should you be working on safeguarding an application developed with Angular 5 or its predecessors, please consult our comprehensive documentation on integrating Jscrambler with Angular for guidance.
Additionally, we offer a detailed tutorial focused on AngularJS, outlining the steps to secure your application utilizing Jscrambler's robust solutions. To kickstart, initiate the installation of Angular CLI through npm.
npm install -g @angular/cli
The Angular CLI simplifies the setup by downloading and installing all necessary dependencies for the latest version of Angular.
Having set the stage, we're now poised to craft our foundational boilerplate app, serving as the cornerstone of this tutorial.
You can create this new application using the ng new command, a facility made available following the Angular CLI installation:
ng new angular-boilerplate
Throughout the installation journey, you'll encounter prompts inquiring whether you wish to incorporate Angular routing into your project, alongside options for selecting a stylesheet format.
Choose the alternatives that best align with your project needs. For simplicity, we opted for the default settings.
Upon the completion of these steps, we're ready to launch the boilerplate application:
cd angular-boilerplate
ng serve
This sequence of actions equips us with a functional Angular application. To verify its operational status, navigate to the app within your browser, where it typically resides at http://localhost:4200/.
Should you seek further enlightenment or require additional details, the official Angular documentation remains an invaluable resource. Moreover, executing ng help will unveil a comprehensive list of commands at your disposal.
The base project structure of our Angular application should look as follows:
angular-boilerplate/
|-- angular.json
|-- package-lock.json
|-- package.json
|-- tsconfig.json
|-- tslint.json
|-- dist/
| |-- angular-boilerplate/
|-- e2e/
| |-- src/
|-- node_modules/
|-- src/
| |-- app/
| |-- assets/
| |-- environments/
The angular.json file serves as a central hub for all CLI configurations across projects within the workspace, detailing the options for build, serve, and test tools utilized by the CLI.
The package.json file houses all npm-related configurations, including dependencies, versions, and scripts, facilitating package management and project setup.
Within the project, the src directory is the heart of your application, containing all source code. Post-build, the output — including the safeguarded HTML and JavaScript files — is deposited in the dist directory, ready for deployment.
Configuring Jscrambler
Before configuration, make sure you have registered for a Jscrambler account.
Configuration settings for Jscrambler are consolidated within a singular file named .jscramblerrc. This file is created to outline the specific transformations you aim to apply to your code for protection.
The most straightforward method to configure these settings is through the Jscrambler Web App.
Upon accessing the app, initiate by setting up a new application. Within the Application Modes tab, you're to select both the Language Specifications and the type of application you're working on.
Then, choose the desired transformations from the options provided, especially noting the Templates and Fine-Tuning tabs. For this example, we will employ the Obfuscation template. For additional guidance on these procedures, our tutorial on safeguarding your JavaScript offers comprehensive assistance.
Finally, you will download a JSON file encapsulating these configurations, which is mandatory for acquiring the required settings to proceed.
Now is the time to proceed by creating a new file named .jscramblerrc within the root directory of your Angular project. Begin by opening the jscrambler.json file that was previously downloaded. Then, copy all of its contents into the newly created .jscramblerrc file.
Following this initial step, it's necessary to enhance the .jscramblerrc file by adding two additional sections: filesSrc and filesDest. These sections are crucial for defining the source files to be processed and the destination for the protected files, respectively.
Upon completion of these steps, your .jscramblerrc file will be fully configured and should resemble the following structure:
{
"keys": {
"accessKey": <ACCESS_KEY_HERE>,
"secretKey": <SECRET_KEY_HERE>
},
"applicationId": <APP_ID_HERE>,
"filesSrc": [
"./dist/**/*.html",
"./dist/**/*.js"
],
"filesDest": "./",
"params": [
{
"name": "whitespaceRemoval"
},
{
"name": "identifiersRenaming",
"options": {
"mode": "SAFEST"
}
},
{
"name": "dotToBracketNotation"
},
{
"name": "deadCodeInjection"
},
{
"name": "stringConcealing"
},
{
"name": "functionReordering"
},
{
"options": {
"freq": 1,
"features": [
"opaqueFunctions"
]
},
"name": "functionOutlining"
},
{
"name": "propertyKeysObfuscation"
},
{
"name": "regexObfuscation"
},
{
"name": "booleanToAnything"
}
],
"areSubscribersOrdered": false,
"applicationTypes": {
"webBrowserApp": true,
"desktopApp": false,
"serverApp": false,
"hybridMobileApp": false,
"javascriptNativeApp": false,
"html5GameApp": false
},
"languageSpecifications": {
"es5": true,
"es6": false,
"es7": false
},
"useRecommendedOrder": true,
"jscramblerVersion": "5.<X>"
}
Having obtained the necessary information through the Jscrambler Web App, fields such as accessKey, secretKey, and applicationId within our configuration file are pre-populated for your convenience.
Should you prefer to gather these details manually, a wealth of tutorials is available, guiding you on utilizing Jscrambler to safeguard the client-side of your application.
It's important to note that within the params section of your configuration, the specified transformations are designated to protect your Angular application.
These transformations offer a range of options that you can either select directly within the web app or configure manually. For a comprehensive understanding of all the transformations available, the Jscrambler Help Center provides detailed documentation.
Additionally, you have the flexibility to modify the filesSrc configuration to align with the specific files you intend to protect.
While it's advisable to shield all .html and .js files within Angular applications, a deeper familiarity with your project will enable you to pinpoint which components are critical and thus, must be protected.
Opting for filesDest: './' as your destination path will result in the original files being overwritten with their new, protected versions. This approach ensures that the most secure iteration of your files is generated and ready for use.
Integrating Jscrambler in the Build Process
Integrating Jscrambler into the Angular build process can be achieved through two primary methods: utilizing the Angular CLI or Webpack. Each approach caters to different aspects of the build process, offering flexibility in how you protect your code.
Via Angular CLI
The Angular CLI is a prevalent tool for generating builds. To illustrate the integration of Jscrambler, we'll use a boilerplate application. The initial step involves installing the Jscrambler API Client with the following command:
npm install jscrambler --save-dev
To weave Jscrambler into the build process through the Angular CLI, a CLI hook must be established in the package.json's scripts section. This adjustment enables the integration:
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"build:prod": "ng build --prod && jscrambler",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},
The "build:prod": "ng build --prod && jscrambler" hook triggers the Jscrambler command post-build. For execution, the previously created .jscramblerrc file should be located in the project's root directory. Executing npm run build:prod compiles the production files into dist/<app-name>, ensuring your HTML and JavaScript files are safeguarded by Jscrambler against theft and reverse-engineering.
Via Webpack
With the deprecation of the ng eject command in Angular 6 and later, integrating Jscrambler via Webpack requires extending the build configurations using an angular-builder, such as the custom-webpack config object builder. After installing the builder with npm i -D @angular-builders/custom-webpack, you proceed to create a Webpack configuration file that complements the built-in configuration, focusing on development and production builds.
For the production build, the inclusion of the Jscrambler Webpack Plugin is paramount, installable via:
npm i --save-dev jscrambler-webpack-plugin
The production configuration, aimed at protecting the main chunk of the application, would resemble:
const JscramblerWebpack = require('jscrambler-webpack-plugin');
module.exports = {
plugins: [
new JscramblerWebpack({
chunks: ['main']
})
]
};
Updating the angular.json file to utilize these configurations is the next step, specifying the customWebpackConfig for production builds and potentially setting the vendorChunk flag to true to segregate vendor content into a separate bundle, enhancing organization and efficiency.
Finally, adjust the package.json build script for production to reflect these changes. This ensures that production builds (npm run build:prod) employ the Jscrambler Webpack client, leveraging the settings defined in .jscramblerrc to protect your code effectively.
Testing the Protected Angular App
After applying protection to your Angular app with Jscrambler, it's essential to test it to ensure everything operates as intended.
This process involves setting up a local server environment where your app can be hosted and run. Start by installing a local server using npm with the following command:
npm install http-server -g
With the server installed, you're ready to host your Angular application's files. Execute the command below to serve your app from the local server:
http-server ./dist/angular-boilerplate/
Upon launching the server, the terminal will display two ports: one that is publicly accessible and another that is private to your machine. Navigate to the provided URL in your web browser to start your app.
This is the perfect opportunity to examine how your protection measures have altered the appearance of your code. Access the browser's debugger tools and navigate to the "Sources" tab. Here, you can open and inspect the files, where you'll notice the protected code. The transformation applied by Jscrambler should make the code significantly more difficult to understand, serving as a testament to the effectiveness of your security measures.
Conclusion
Angular continues to stand out as an evolving framework that provides developers with the tools to build robust web and mobile applications. Through its adoption of data binding, services, and dependency injection conventions, Angular facilitates the creation of highly interactive and dynamic user experiences.
For applications requiring protection against code theft, reverse engineering, piracy, licensing infringements, or malware injections, integrating Jscrambler becomes indispensable. It offers an essential layer of security that ensures the integrity and confidentiality of your codebase, making it a critical tool for developers looking to safeguard their projects.
Thankfully, incorporating Jscrambler within Angular's build process is a straightforward endeavor, designed to be accessible and manageable for developers at all skill levels. However, should you find yourself in need of additional support or guidance, we are more than happy to assist. Do not hesitate to reach out to us for help!
Jscrambler
The leader in client-side Web security. With Jscrambler, JavaScript applications become self-defensive and capable of detecting and blocking client-side attacks like Magecart.
View All ArticlesMust read next
Monkey Patching: An Analysis of Code Poisoning JavaScript
Monkey patching enables dynamically changing the behavior of JavaScript. While it can be used legitimately, it can also enable attacks like Magecart.
October 15, 2019 | By Jscrambler | 6 min read
Full-stack JavaScript Source Code Protection
With Node.js you can do Full-stack JavaScript Web Apps. JScrambler 3.6 introduces Node.js support and is now the first Full-stack JS Protection solution.
September 8, 2014 | By Pedro Fortuna | 4 min read