4

I would like to allow the users of my site (my colleagues) to create and run arbitrary functions on a Node.js server. The function can be uploaded to the server, where it is stored and when someone access a URL on that server, it should execute the function. The function needn't be checked or be executed in a sandbox and the code should be considered as trusted. How can I achieve something like this? I know this is very close to FaaS but I don't think it's the same... I still need the server to run some pre-processing on the request, etc.

1 Answer 1

6

If you truly understand all consequences, you can use form eval function to run the code stored as text/string on server.

See here - https://nodejs.org/api/vm.html , e.g. like specified there:

Example: Running an HTTP Server within a VM

When using either script.runInThisContext() or vm.runInThisContext(), the code is executed within the current V8 global context. The code passed to this VM context will have its own isolated scope.

In order to run a simple web server using the http module the code passed to the context must either call require('http') on its own, or have a reference to the http module passed to it. For instance:

'use strict';
const vm = require('vm');

const code = `
(function(require) {
  const http = require('http');

  http.createServer((request, response) => {
    response.writeHead(200, { 'Content-Type': 'text/plain' });
    response.end('Hello World\\n');
  }).listen(8124);

  console.log('Server running at http://127.0.0.1:8124/');
})`;

vm.runInThisContext(code)(require);

Note: The require() in the above case shares the state with the context it is passed from. This may introduce risks when untrusted code is executed, e.g. altering objects in the context in unwanted ways.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks for the VM module (I totally missed that!) and the code example!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.