Skip to content

Instantly share code, notes, and snippets.

@magiskboy
Created June 20, 2023 07:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save magiskboy/0e8d5fa57533c1de5c6e53f9b02f6548 to your computer and use it in GitHub Desktop.
Save magiskboy/0e8d5fa57533c1de5c6e53f9b02f6548 to your computer and use it in GitHub Desktop.
Example for sandbox environments in Javascript
const { Console } = require("console");
const stream = require("stream");
const sandboxProxies = new WeakMap();
function compileCode(src) {
src = 'with (sandbox) {' + src + '}';
const code = new Function('sandbox', src);
return function(sandbox) {
if (!sandboxProxies.has(sandbox)) {
const sandboxProxy = new Proxy(sandbox, { has, get });
sandboxProxies.set(sandbox, sandboxProxy);
};
return code(sandboxProxies.get(sandbox));
}
}
function has(target, key) {
return true;
}
function get(target, key) {
if (key === Symbol.unscopables) return undefined;
return target[key];
}
function makeStandardSandbox() {
const stdout = new stream.Duplex();
const stderr = new stream.Duplex();
const stdin = new stream.Duplex();
return {
globalThis: {
process: {
stderr,
stdout,
stdin,
},
console: new Console(stdout, stderr),
}
}
}
function runCode(src) {
try {
const executor = compileCode(src);
const sandbox = makeStandardSandbox();
const output = [];
sandbox.globalThis.process.stdout._write = function(chunk, encoding, callback) {
output.push(chunk.toString());
if (callback) {
callback();
}
}
executor(sandbox);
return output.join('');
}
catch (e) {
console.error(e);
}
return '';
}
module.exports = {
compileCode,
makeStandardSandbox,
runCode,
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment