Skip to content
This repository has been archived by the owner on May 5, 2023. It is now read-only.

Commit

Permalink
Fix filename option
Browse files Browse the repository at this point in the history
  • Loading branch information
TooTallNate committed Jul 12, 2021
1 parent ccc3445 commit 9d25bb6
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 7 deletions.
7 changes: 5 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { generate } from 'escodegen';
import { parseScript } from 'esprima';
import { visit, namedTypes as n, builders as b } from 'ast-types';
import { Context, RunningScriptOptions } from 'vm';
import { VM } from 'vm2';
import { VM, VMScript } from 'vm2';

/**
* Compiles sync JavaScript code into JavaScript with async Functions.
Expand Down Expand Up @@ -138,7 +138,10 @@ namespace degenerator {
): (...args: A) => Promise<R> {
const compiled = degenerator(code, names);
const vm = new VM(options);
const fn = vm.run(`${compiled};${returnName}`);
const script = new VMScript(`${compiled};${returnName}`, {
filename: options.filename,
});
const fn = vm.run(script);
if (typeof fn !== 'function') {
throw new Error(
`Expected a "function" to be returned for \`${returnName}\`, but got "${typeof fn}"`
Expand Down
26 changes: 21 additions & 5 deletions test/test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -159,26 +159,42 @@ describe('degenerator()', () => {
assert.equal(val, 'foo');
});
});
it('should prevent privilege escalation of untrusted code', async() => {
it('should prevent privilege escalation of untrusted code', async () => {
let err;
try {
const fn = compile<typeof process>(
`const f = this.constructor.constructor('return process');`,
'f',
[],
[]
);
await fn();
} catch(_err) {
} catch (_err) {
err = _err;
}
assert.equal(err.message,'process is not defined')
assert.equal(err.message, 'process is not defined');
});
it('should allow to return synchronous undefined', () => {
function u() {}
const fn = compile(`${u}`, 'u', ['']);
return fn().then(val => {
return fn().then((val) => {
assert.strictEqual(val, undefined);
});
});
it('should support "filename" option', async () => {
function u() {
throw new Error('fail');
}
let err;
const fn = compile(`${u}`, 'u', [''], {
filename: '/foo/bar/baz.js',
});
try {
await fn();
} catch (_err) {
err = _err;
}
assert.strictEqual(err.message, 'fail');
assert(err.stack.includes('at u (/foo/bar/baz.js:'));
});
});
});

0 comments on commit 9d25bb6

Please sign in to comment.