Skip to content

Protect JavaScript source code with v8 snapshot

rogerwang edited this page Feb 21, 2013 · 20 revisions

Since v0.4.2

This feature is still experimental -- API & tool usage are subject to change in future versions.

The JavaScript source code of your application can be protected by compiling to native code. Only the native code is distributed with the application and is loaded when the application starts.

There are important limitations in the current implementation. Please see the 'Limitation' section.

Compilation

JS source code is compiled to native code (aka. 'snapshot') with the tool nwsnapshot, which is provided in the binary download of node-webkit. To use it:

nwsnapshot --extra_code source.js snapshot.bin

The snapshot.bin file is needed to be distributed with your application. You can name it whatever you want.

Package

Add the following field to package.json:

"snapshot" : "snapshot.bin"

Run

It's important to remember that the code being compiled is evaluated when you launch nwsnapshot. Then the JS heap state is saved to the binary file (e.g. snapshot.bin) and restored right before JS context creation (and before your application launches). So you may not want to run any code in the top level scope. So it's better to just define functions or variables there.

And the scripts runs/loads loads very early (you can assume it's earlier than context creation) so Node and DOM objects such as window is not defined. So you may want to defined functions and pass window as argument.

The snapshot is used by V8 as a kind of 'template' to create JS contexts. So the objects defined there will be in every JS contexts.

Limitation

The source code being compiled cannot be too big. nwsnapshot will report error when this happens.

Experiments show that 3 copies of the jquery library will exceed this limit. If you feel this is too small for your application, consider split your code into 2 parts: compiled and plain source, or you can file an issue.

The compiled code runs slower than normal JS: ~30% performance according to v8bench. Normal JS source code will not be affected.

The compiled code is not cross-platform nor compatible between versions of node-webkit. So you'll need to run nwsnapshot for each of the platforms when you package your application.

Sample

mytest.js: (this is the JS code to be protected)

function mytest(a) {
    document.write(a + 42);
}

Compile mytest.js to native code:

nwsnapshot --extra_code mytest.js mytest.bin

package.json:

{
  "name": "nw-demo",
  "main": "index.html",
  "snapshot": "mytest.bin"
}

index.html: (note that we don't need to distribute 'mytest.js' with it)

<html><head>
  <title>snapshot demo</title>
</head>
<body>
  <script>
  mytest(2); 
  </script>
</body></html>
Clone this wiki locally