Skip to content

Commit

Permalink
Define custom Error.prepareStackTrace
Browse files Browse the repository at this point in the history
  • Loading branch information
codenirvana committed Apr 10, 2023
1 parent 2759dd3 commit c25bb40
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 0 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.yaml
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
unreleased:
fixed bugs:
- GH-907 Defined `Error.prepareStackTrace` to prevent stack trace pollution

4.2.4:
date: 2023-03-10
fixed bugs:
Expand Down
16 changes: 16 additions & 0 deletions lib/sandbox/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,22 @@
// @note this deletes the constructor as well to make sure one can't recreate the same scope
contextObject = Object.getPrototypeOf(contextObject);
} while (contextObject && contextObject.constructor !== Object);

// define custom Error.prepareStackTrace
Object.defineProperty(Error, 'prepareStackTrace', {
value: function (error, structuredStackTrace) {
const errorString = error.toString();

if (Array.isArray(structuredStackTrace) && !structuredStackTrace.length) {
return errorString;
}

return `${errorString}\n at ${structuredStackTrace.join('\n at ')}`;
},
configurable: false,
enumerable: false,
writable: false
});
}());

// do include json purse
Expand Down
18 changes: 18 additions & 0 deletions test/unit/sandbox-sanity.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,24 @@ describe('sandbox', function () {
});
});

it('should not be able to mutate Error.prepareStackTrace', function (done) {
Sandbox.createContext(function (err, ctx) {
if (err) { return done(err); }
ctx.on('error', done);

ctx.execute(`
var assert = require('assert');
var fn = Error.prepareStackTrace;
Error.prepareStackTrace = () => {};
assert.equal(Error.prepareStackTrace, fn);
var err = new Error('Test');
assert.equal(err.stack.split('\\n')[0], 'Error: Test');
`, done);
});
});

it('should not have access to global properties', function (done) {
Sandbox.createContext({ debug: true }, function (err, ctx) {
if (err) { return done(err); }
Expand Down

0 comments on commit c25bb40

Please sign in to comment.