44// appication runtime, load an application code and passes a sandbox into app
55// as a global context and receives exported application interface
66
7+ const PARSING_TIMEOUT = 1000 ;
8+ const EXECUTION_TIMEOUT = 5000 ;
9+
710// The framework can require core libraries
811const fs = require ( 'fs' ) ;
912const vm = require ( 'vm' ) ;
1013
1114// Create a hash and turn it into the sandboxed context which will be
1215// the global context of an application
13- const context = { module : { } , console } ;
16+ const context = {
17+ module : { } , console,
18+ require : ( name ) => {
19+ if ( name === 'fs' ) {
20+ console . log ( 'Module fs is restricted' ) ;
21+ return null ;
22+ }
23+ return require ( name ) ;
24+ }
25+ } ;
26+
1427context . global = context ;
1528const sandbox = vm . createContext ( context ) ;
1629
@@ -20,13 +33,27 @@ fs.readFile(fileName, (err, src) => {
2033 // We need to handle errors here
2134
2235 // Run an application in sandboxed context
23- const script = vm . createScript ( src , fileName ) ;
24- script . runInNewContext ( sandbox ) ;
36+ let script ;
37+ try {
38+ script = new vm . Script ( src , { timeout : PARSING_TIMEOUT } ) ;
39+ } catch ( e ) {
40+ console . log ( 'Parsing timeout' ) ;
41+ process . exit ( 1 ) ;
42+ }
43+
44+ try {
45+ script . runInNewContext ( sandbox , { timeout : EXECUTION_TIMEOUT } ) ;
46+ const exported = sandbox . module . exports ;
47+ console . dir ( { exported } ) ;
48+ } catch ( e ) {
49+ console . log ( 'Execution timeout' ) ;
50+ process . exit ( 1 ) ;
51+ }
2552
2653 // We can access a link to exported interface from sandbox.module.exports
2754 // to execute, save to the cache, print to console, etc.
2855} ) ;
2956
3057process . on ( 'uncaughtException' , ( err ) => {
31- console . log ( '>>> ' + err . stack ) ;
58+ console . log ( 'Unhandled exception: ' + err ) ;
3259} ) ;
0 commit comments