-
-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathframework.js
More file actions
60 lines (51 loc) · 1.65 KB
/
framework.js
File metadata and controls
60 lines (51 loc) · 1.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
'use strict';
// Example showing us how the framework creates an environment (sandbox) for
// appication runtime, load an application code and passes a sandbox into app
// as a global context and receives exported application interface
// The framework can require core libraries
const api = {};
api.fs = require('node:fs');
api.vm = require('node:vm');
api.sandboxedFs = require('sandboxed-fs');
const { cloneInterface, wrapFunction } = require('./wrapper.js');
const log = (s) => {
console.log('Prints something from sandbox');
console.log(s);
};
const safeRequire = (name) => {
if (name === 'fs') {
const msg = 'You dont have access to fs API';
console.log(msg);
return new Error(msg);
} else {
return require(name);
}
};
const runSandboxed = (path) => {
const fileName = path + 'main.js';
const context = {
module: {},
require: safeRequire,
api: {
console: { log },
timers: {
setTimeout: wrapFunction('setTimeout', setTimeout)
},
fs: cloneInterface(api.sandboxedFs.bind(path))
}
};
context.global = context;
const sandbox = api.vm.createContext(context);
// Read an application source code from the file
api.fs.readFile(fileName, (err, src) => {
// We need to handle errors here
// Run an application in sandboxed context
const script = new api.vm.Script(src, fileName);
const f = script.runInNewContext(sandbox);
if (f) f();
// We can access a link to exported interface from sandbox.module.exports
// to execute, save to the cache, print to console, etc.
});
};
runSandboxed('./applications/application1/');
runSandboxed('./applications/application2/');