DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Creating a Secure REST API in Node.js
  • Deploying a Simple Golang Web App on Heroku
  • How to Build a Concurrent Chat App With Go and WebSockets
  • Electron Js + jQuery + Bootstrap - Dev to Build

Trending

  • GDPR Compliance With .NET: Securing Data the Right Way
  • How to Build Scalable Mobile Apps With React Native: A Step-by-Step Guide
  • Why Documentation Matters More Than You Think
  • Zero Trust for AWS NLBs: Why It Matters and How to Do It
  1. DZone
  2. Coding
  3. JavaScript
  4. How To Protect Node.js Apps With Jscrambler

How To Protect Node.js Apps With Jscrambler

Whether you want to protect important code logic or to prevent unauthorized access, here are the steps you should take to secure the source code of your Node.js apps.

By 
Pedro Fortuna user avatar
Pedro Fortuna
·
Oct. 13, 20 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
7.2K Views

Join the DZone community and get the full member experience.

Join For Free

Node.js is an extremely popular and open-source JavaScript runtime environment to create server-side applications.

This tutorial will explain how to integrate Jscrambler seamlessly into the build process of a typical Node.js app in just a few minutes. You'll learn how to protect your Node.js source code with the most advanced polymorphic obfuscation techniques, along with code locks and self-defensive capabilities.

Pre-Requisites

First, make sure that you have the latest version of npm installed on your local machine:

Shell
xxxxxxxxxx
1
 
1
npm update -g npm


Now, of course, we need a sample Node.js app to use in this tutorial. Let's go ahead and use a very simple "Hello World" Express app. First, let's install Express:

Shell
xxxxxxxxxx
1
 
1
npm install express --save


Then, let's create an app.js file in our project's root folder with the following code, provided in the Express website:

JavaScript
xxxxxxxxxx
1
11
 
1
const express = require('express')
2
const app = express()
3
const port = 3000
4
5
app.get('/', (req, res) => {
6
  res.send('Hello World!')
7
})
8
9
app.listen(port, () => {
10
  console.log(`Example app listening at http://localhost:${port}`)
11
})


This app starts a server and listens on port 3000 for connections. The app responds with “Hello World!” for requests to the root URL (/) or route.

If we run the app with:

Shell
xxxxxxxxxx
1
 
1
node app.js


We will see a "Hello World" message on localhost:3000.

Integrating Jscrambler

Let's begin by getting a ready-to-use file with our intended Jscrambler configuration.

If you haven't created a Jscrambler account yet, be sure to do so before moving forward.

Log into the Jscrambler Web App. Once there, create a new app. Now, it's time to pick the Jscrambler transformations that we want to use. We can pick them one-by-one in the Fine-Tuning tab but, in our case, let's go ahead to the Templates tab and pick the Obfuscation template. If you need help with these steps, please refer to this guide.

Now, we simply have to download a JSON file with all this configuration, which will be used only for quickly getting the required settings. You can do this by clicking the cogwheel next to "Protect App" on the right sidebar, which will present the following screen:

quick settings in jscrambler

Now that you have the file with the needed configuration, you can integrate Jscrambler into your Node.js app's build process using one of two tools: Grunt or Gulp. Let's explore both approaches.

Grunt

Grunt is a JavaScript task runner with the goal of automating repetitive tasks like minification, compilation, unit testing, code protection, etc. In this case, it is a handy option to ensure that the source code of your Node.js app is always protected at build time.

To get started with Grunt, let's install it as a dev dependency:

Shell
xxxxxxxxxx
1
 
1
npm install grunt --save-dev


Now, we need to create a configuration file for Grunt, Gruntfile.js. This file contains our project and Grunt task configuration and loads Grunt plugins and tasks.

To keep things simple, let's set up a basic Gruntfile:

JavaScript
xxxxxxxxxx
1
 
1
module.exports = function(grunt) {
2
  grunt.initConfig({
3
    pkg: grunt.file.readJSON('package.json')
4
  });
5
};


Next, we want to add the Jscrambler Grunt plugin:

Shell
xxxxxxxxxx
1
 
1
npm install grunt-jscrambler --save-dev


Now that the plugin is installed, we must enable it in our Gruntfile by adding this line at the bottom:

JavaScript
xxxxxxxxxx
1
 
1
grunt.loadNpmTasks('grunt-jscrambler');


Right after this line, we have to set the "default" Grunt task with:

JavaScript
xxxxxxxxxx
1
 
1
grunt.registerTask('default', ['jscrambler']);


Now that this is done, we also need to specify the task itself. Here, we will use some parts of the jscrambler.json file we downloaded earlier: accessKey, secretKey, applicationId, and the params array.

Our final Gruntfile.js file should look like this:

JavaScript
xxxxxxxxxx
1
75
 
1
module.exports = function(grunt) {
2
3
    grunt.initConfig({
4
      pkg: grunt.file.readJSON('package.json'),
5
      jscrambler: {
6
        main: {
7
          options: {
8
            keys: {
9
              accessKey: 'YOUR_ACCESS_KEY',
10
              secretKey: 'YOUR_SECRET_KEY'
11
            },
12
            applicationId: 'YOUR_APPLICATION_ID',
13
            params: [
14
                {
15
                    "name": "objectPropertiesSparsing"
16
                  },
17
                  {
18
                    "name": "variableMasking"
19
                  },
20
                  {
21
                    "name": "whitespaceRemoval"
22
                  },
23
                  {
24
                    "name": "identifiersRenaming",
25
                    "options": {
26
                      "mode": "SAFEST"
27
                    }
28
                  },
29
                  {
30
                    "name": "dotToBracketNotation"
31
                  },
32
                  {
33
                    "name": "stringConcealing"
34
                  },
35
                  {
36
                    "name": "functionReordering"
37
                  },
38
                  {
39
                    "options": {
40
                      "freq": 1,
41
                      "features": [
42
                        "opaqueFunctions"
43
                      ]
44
                    },
45
                    "name": "functionOutlining"
46
                  },
47
                  {
48
                    "name": "propertyKeysObfuscation",
49
                    "options": {
50
                      "encoding": [
51
                        "hexadecimal"
52
                      ]
53
                    }
54
                  },
55
                  {
56
                    "name": "regexObfuscation"
57
                  },
58
                  {
59
                    "name": "booleanToAnything"
60
                  }
61
                ]
62
          },
63
          files: [
64
            {expand: true, src: ['app.js'], dest: 'dist/'},
65
          ]
66
        }
67
      }
68
    });
69
  
70
    grunt.loadNpmTasks('grunt-jscrambler');
71
    
72
    
73
    grunt.registerTask('default', ['jscrambler']);
74
    
75
  };


If we take a closer look at the files array, we'll see that Jscrambler will use the app.js file, protect it, and then place the protected version on the dist/ folder. You can change these to match your project's requirements.

Now, all that's left is to make sure that our build process is using Grunt. In our case, we must make sure that there's a script in our package.json file to build our app using Grunt:

JSON
 




xxxxxxxxxx
1


 
1
"scripts": {
2
    "build": "grunt"
3
  },



We're now ready to run our build:

Shell
xxxxxxxxxx
1
 
1
npm run build


That's it! If we check our /dist/app.js file, we will see that it has been obfuscated with Jscrambler.

Gulp

According to the 2019 State of JavaScript survey, Gulp is the second most popular build tool for JS. Similarly to Grunt, it allows you to automate repetitive workflows into efficient build pipelines.

To get started with Gulp, let's install it as a dev dependency:

Shell
xxxxxxxxxx
1
 
1
npm install gulp --save-dev


Let's also install the Jscrambler Gulp plugin:

Shell
xxxxxxxxxx
1
 
1
npm install gulp-jscrambler --save-dev


Now, we need to create a configuration file for Gulp, gulpfile.js.

Let's go right ahead and add the configurations we need to get Jscrambler working with Gulp. To do this, we will need some parts of the jscrambler.json file we downloaded earlier: accessKey, secretKey, applicationId, and the params array.

Our final gulpfile.js file should look like this:

JavaScript
xxxxxxxxxx
1
65
 
1
var gulp = require('gulp');
2
var jscrambler = require('gulp-jscrambler');
3
4
gulp.task('default', function (done) {
5
  gulp
6
    .src('app/**/*.js')
7
    .pipe(jscrambler({
8
      keys: {
9
        accessKey: 'YOUR_ACCESS_KEY',
10
        secretKey: 'YOUR_SECRET_KEY'
11
      },
12
      applicationId: 'YOUR_APPLICATION_ID',
13
      params: [
14
        {
15
            "name": "objectPropertiesSparsing"
16
          },
17
          {
18
            "name": "variableMasking"
19
          },
20
          {
21
            "name": "whitespaceRemoval"
22
          },
23
          {
24
            "name": "identifiersRenaming",
25
            "options": {
26
              "mode": "SAFEST"
27
            }
28
          },
29
          {
30
            "name": "dotToBracketNotation"
31
          },
32
          {
33
            "name": "stringConcealing"
34
          },
35
          {
36
            "name": "functionReordering"
37
          },
38
          {
39
            "options": {
40
              "freq": 1,
41
              "features": [
42
                "opaqueFunctions"
43
              ]
44
            },
45
            "name": "functionOutlining"
46
          },
47
          {
48
            "name": "propertyKeysObfuscation",
49
            "options": {
50
              "encoding": [
51
                "hexadecimal"
52
              ]
53
            }
54
          },
55
          {
56
            "name": "regexObfuscation"
57
          },
58
          {
59
            "name": "booleanToAnything"
60
          }
61
        ]
62
    }))
63
    .pipe(gulp.dest('dist/'))
64
    .on('end', done);
65
});


If we take a closer look at this file, we'll see that src specified the path to the files that Jscrambler will use. At the bottom of the file, .pipe(gulp.dest('dist/')) places the protected version on the dist/ folder. You can change these to match your project's requirements.

Now, all that's left is to make sure that our build process is using Gulp. In our case, we must make sure that there's a script in our package.json file to build our app using Gulp:

JSON
xxxxxxxxxx
1
 
1
"scripts": {
2
    "build": "gulp"
3
  },


We're now ready to run our build:

Shell
xxxxxxxxxx
1
 
1
npm run build


That's it! If we check our /dist/app.js file, we will see that it has been obfuscated with Jscrambler.

Final Thoughts

Node.js is clearly the technology of choice to build server-side apps, especially thanks to useful frameworks like Express.

If you're building Node.js applications that have sensitive logic and want to prevent reverse-engineering, licensing violations, and tampering, hardening your source code with a resilient JavaScript protection solution is a must.

As we saw, you can easily integrate Jscrambler into Node's build process using either Grunt or Gulp.

Even though we used the Obfuscation template, feel free to try other templates and protection layers like Self-Defending for improved runtime protection.

app Node.js Grunt (software) Build (game engine) JavaScript shell Express

Published at DZone with permission of . See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Creating a Secure REST API in Node.js
  • Deploying a Simple Golang Web App on Heroku
  • How to Build a Concurrent Chat App With Go and WebSockets
  • Electron Js + jQuery + Bootstrap - Dev to Build

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!