Skip to content

Commit

Permalink
Merge pull request #994 from postmanlabs/feature/modify-mainModule
Browse files Browse the repository at this point in the history
Modified `process.mainModule`
  • Loading branch information
codenirvana committed Apr 2, 2024
2 parents 213923c + 3a89181 commit 4ec95a4
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.yaml
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
unreleased:
fixed bugs:
- GH-994 Modified process.mainModule to prevent access to the Module object
chores:
- GH-993 Moved deprecation warnings to be on the first usage of API

Expand Down
30 changes: 30 additions & 0 deletions lib/postman-sandbox.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,15 @@ const _ = require('lodash'),
EXECUTION_TIMEOUT_ERROR_MESSAGE = 'sandbox not responding',
BRIDGE_DISCONNECTING_ERROR_MESSAGE = 'sandbox: execution interrupted, bridge disconnecting.';

let MAIN_MODULE = null,
ACTIVE_INSTANCES = 0;

class PostmanSandbox extends UniversalVM {
constructor () {
super();

this._executing = {};
this._initialized = false;
}

initialize (initOptions, connectOptions, callback) {
Expand All @@ -24,6 +27,17 @@ class PostmanSandbox extends UniversalVM {

this.debug = Boolean(connectOptions.debug);

// Modify mainModule to prevent access to the Module object
if (!MAIN_MODULE && typeof process === 'object' && process.mainModule) {
MAIN_MODULE = process.mainModule;
process.mainModule = {
..._.pick(process.mainModule, ['id', 'path', 'paths', 'filename', 'loaded']),
exports: {},
children: [],
parent: null
};
}

// set the dispatch timeout of UVM based on what is set in options unless original options sends the same
_.isFinite(connectOptions.timeout) &&
(connectOptions.dispatchTimeout = this.executionTimeout = connectOptions.timeout);
Expand All @@ -32,6 +46,9 @@ class PostmanSandbox extends UniversalVM {
if (err) { return callback(err); }

this.once('initialize', (err) => {
this._initialized = !err;
ACTIVE_INSTANCES++;

this.on(CONSOLE_EVENT_NAME, (cursor, level, args) => {
if (connectOptions.serializeLogs) {
return this.emit('console', cursor, level, args);
Expand Down Expand Up @@ -133,6 +150,10 @@ class PostmanSandbox extends UniversalVM {
}

dispose () {
if (!this._initialized) {
return;
}

_.forEach(this._executing, (irq, id) => {
irq && clearTimeout(irq);

Expand All @@ -146,6 +167,15 @@ class PostmanSandbox extends UniversalVM {

this.removeAllListeners(CONSOLE_EVENT_NAME);
this.disconnect();

this._initialized = false;
ACTIVE_INSTANCES--;

// reset the mainModule to its original value
if (ACTIVE_INSTANCES === 0 && MAIN_MODULE) {
process.mainModule = MAIN_MODULE;
MAIN_MODULE = null;
}
}
}

Expand Down

0 comments on commit 4ec95a4

Please sign in to comment.