-
Notifications
You must be signed in to change notification settings - Fork 13
sandbox exercises #4
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
romanV7
wants to merge
1
commit into
HowProgrammingWorks:master
Choose a base branch
from
romanV7:master
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,19 +1,47 @@ | ||
'use strict'; | ||
// Tests requires | ||
let api; | ||
|
||
// File contains a small piece of the source to demonstrate main module | ||
// of a sample application to be executed in the sandboxed context by | ||
// another pice of code from `framework.js`. Read README.md for tasks. | ||
// Require some modules | ||
require('fs'); | ||
require('vm'); | ||
|
||
const fs = require('fs'); | ||
const net = require('net'); | ||
|
||
// Print from the global context of application module | ||
console.log('From application global context'); | ||
console.dir({ fs, net }, { depth: 1 }); | ||
console.dir({ global }, { depth: 1 }); | ||
console.dir({ api }, { depth: 2 }); | ||
// One call to util`s function | ||
const o = { a: 5, b: 6 }; | ||
o.self = o; | ||
api.console.log(api.util.inspect(o)); | ||
|
||
// Using setTimeout and setInterval | ||
// Exporting a function | ||
module.exports = () => { | ||
// Print from the exported function context | ||
console.log('From application exported function'); | ||
api.timers.setTimeout(() => { | ||
// Print from the exported function context | ||
api.console.log('setTimeout from application2 exported function'); | ||
}, 5000); | ||
|
||
api.timers.setInterval(() => { | ||
// Print from the exported function context | ||
api.console.log('setInterval from application2 exported function'); | ||
}, 2000); | ||
}; | ||
/* | ||
// Exporting an onject | ||
const obj = { | ||
fn1: () => {}, | ||
arr: Array.of({ length: 5 }), | ||
o: new Object({}), | ||
str: new String('string').valueOf(), | ||
//buffer: Buffer.alloc(10), | ||
bool: new Boolean(false).valueOf(), | ||
}; | ||
|
||
module.exports = obj; | ||
*/ | ||
// List of everything from the global context (application | ||
// sandbox) with the data types specified | ||
const def = obj => | ||
Object.keys(obj).reduce( | ||
(hash, key) => ((hash[key] = typeof obj[key]), hash), | ||
{} | ||
); | ||
api.console.log(def(global)); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,69 +1,82 @@ | ||
'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 | ||
|
||
const PARSING_TIMEOUT = 1000; | ||
const EXECUTION_TIMEOUT = 5000; | ||
// File contains a small piece of the source to demonstrate main module | ||
// of a sample application to be executed in the sandboxed context by | ||
// another pice of code from `framework.js`. | ||
|
||
// The framework can require core libraries | ||
const fs = require('fs'); | ||
const vm = require('vm'); | ||
const timers = require('timers'); | ||
const events = require('events'); | ||
|
||
// Create a hash and turn it into the sandboxed context which will be | ||
// the global context of an application | ||
const context = { | ||
module: {}, console, | ||
require: name => { | ||
if (name === 'fs') { | ||
console.log('Module fs is restricted'); | ||
return null; | ||
} | ||
return require(name); | ||
} | ||
}; | ||
// Tests require to initialize 'api', but with it, code is not running! | ||
let api; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. And this one too. |
||
global.api = {}; | ||
api.vm = require('vm'); | ||
api.fs = require('fs'); | ||
api.util = require('util'); | ||
|
||
context.global = context; | ||
const sandbox = vm.createContext(context); | ||
// This is a wrapper for 'console.log' to add more info into console output | ||
//in the following format: `<applicationName> <time> <message>` | ||
const wrapC = (path, fn) => message => { | ||
console.log(`application: ${path}`); | ||
const time = 'Time: ' + new Date(); | ||
console.log(time); | ||
fn(message); | ||
}; | ||
// Function for | ||
const def = obj => | ||
Object.keys(obj).reduce( | ||
(hash, key) => ((hash[key] = typeof obj[key]), hash), | ||
{} | ||
); | ||
|
||
// Prepare lambda context injection | ||
const api = { timers, events }; | ||
// Wrap 'require' function for logging to a file in the format: `<time> <module name>` | ||
const req = name => { | ||
const message = 'ModuleName: ' + name + '\nTime:' + new Date(); | ||
console.log(message); | ||
return require(name); | ||
}; | ||
// Print application parameter count and source code | ||
const countArgs = f => console.log(f.length); | ||
const content = f => console.log(f.toString()); | ||
|
||
// Read an application source code from the file | ||
const fileName = './application.js'; | ||
fs.readFile(fileName, 'utf8', (err, src) => { | ||
const runSandboxed = path => { | ||
// Create a hash and turn it into the sandboxed context which will be | ||
// the global context of an application | ||
const context = { | ||
module: {}, | ||
require: req, | ||
api: { | ||
timers: { setTimeout, setInterval }, | ||
util: api.util, | ||
console: { log: wrapC(path, console.log) }, | ||
}, | ||
}; | ||
context.global = context; | ||
const sandbox = api.vm.createContext(context); | ||
// We need to handle errors here | ||
|
||
// Wrap source to lambda, inject api | ||
src = `api => { ${src} };`; | ||
// Read an application source code from the file | ||
api.fs.readFile(path, 'utf-8', (err, data) => { | ||
if (err) return; | ||
// Run an application in sandboxed context | ||
const script = new api.vm.Script(data, path); | ||
const f = script.runInNewContext(sandbox); | ||
|
||
// Run an application in sandboxed context | ||
let script; | ||
try { | ||
script = new vm.Script(src, { timeout: PARSING_TIMEOUT }); | ||
} catch (e) { | ||
console.dir(e); | ||
console.log('Parsing timeout'); | ||
process.exit(1); | ||
} | ||
|
||
try { | ||
const f = script.runInNewContext(sandbox, { timeout: EXECUTION_TIMEOUT }); | ||
f(api); | ||
if (process.argv[2] === path || path === 'application.js') f; | ||
const exported = sandbox.module.exports; | ||
console.dir({ exported }); | ||
} catch (e) { | ||
console.dir(e); | ||
console.log('Execution timeout'); | ||
process.exit(1); | ||
} | ||
const type = typeof exported; | ||
if (type === 'function') { | ||
countArgs(exported); | ||
content(exported); | ||
exported(); | ||
} else if (type === 'object') { | ||
console.log(def(exported)); | ||
} | ||
// We can access a link to exported interface from sandbox.module.exports | ||
// to execute, save to the cache, print to console, etc. | ||
}); | ||
}; | ||
|
||
// We can access a link to exported interface from sandbox.module.exports | ||
// to execute, save to the cache, print to console, etc. | ||
}); | ||
runSandboxed('application.js'); | ||
|
||
process.on('uncaughtException', err => { | ||
console.log('Unhandled exception: ' + err); | ||
|
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It really needs to be deleted.