B
B
bitwheeze2021-07-08 21:34:07
Java
bitwheeze, 2021-07-08 21:34:07

How to make a nodejs module work in Java using GraalVM?

Tell me,

I am writing a program in java and there is an npm module (javascript) that is complex enough to rewrite it in java, so I thought to run it using graalvm in java code.

I connected graalvm and it can compile and execute simple javascripts, but it doesn’t go any further. I tried to compile the npm module webpack and esbuild to one file, everything rests on the npm get-random-values ​​library. Depending on whether it is executed in the browser or as a nodejs module, it calls either window.crypto.getRandomValues ​​or require("crypto").randomBytes

In graalvm , window.crypto.getRandomValues ​​is naturally not present. Also, graalvm does not know how to require and naturally cannotrequire("crypto").randomBytes .

Graalvm has a nodejs module, but I don't understand how to use it in Java. Maybe there is some module that can emulate a browser with its window object? It would be easier. Or at least a more or less reliable implementation of crypto.randomBytes or window.crypto.getRandomValues ​​in bare javascript? Although you can probably forget about reliability.

Thanks

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
rPman, 2021-07-10
@rPman

Maybe there is some module that can emulate a browser with its window object?

I can suggest solving your problem in a different way, using javascript from the standard JavaFX WebView and WebEngine component (this is a webkit), the code is very simple, from the disadvantages - there is no support for gpu acceleration (playing youtube videos loads the processor) ... access to the dom html of the page as direct and indirectly, through a javascript injection (through setTimeout there will be access only to the sandbox of the web page), i.e. you can open a stupidly blank page and add the necessary scripts there.

B
bitwheeze, 2021-07-09
@bitwheeze

I poked around yesterday and got the idea to use a java class to generate random numbers. To do this, I wrote the following javascript and loaded it before the problematic library.

var SecureRandom = Java.type('java.security.SecureRandom');

var window = {
  crypto: {
    getRandomValues: (buf) => {
      var bytes = SecureRandom.getSeed(buf.length);
      buf.set(bytes);
    }
  }
};

That is, from JS I call the getSeed method of the java.security.SecureRandom class. Apparently this works. Now I can use webpack-generated js script. Loads without errors, but still not quite working. But these are small things, I think.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question