Skip to content

Commit

Permalink
Prevent require-ing bin/shjs (#848)
Browse files Browse the repository at this point in the history
* Prevent require-ing bin/shjs

* Move require guard up, and improve function name

* Move require up and clarify comment
  • Loading branch information
freitagbr committed Jun 27, 2018
1 parent aa9d443 commit 93bbf68
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 6 deletions.
19 changes: 14 additions & 5 deletions bin/shjs
@@ -1,12 +1,23 @@
#!/usr/bin/env node

if (require.main !== module) {
throw new Error('Executable-only module should not be required');
}

// we must import global ShellJS methods after the require.main check to prevent the global
// namespace from being polluted if the error is caught
require('../global');

if (process.argv.length < 3) {
console.log('ShellJS: missing argument (script name)');
function exitWithErrorMessage(msg) {
console.log(msg);
console.log();
process.exit(1);
}

if (process.argv.length < 3) {
exitWithErrorMessage('ShellJS: missing argument (script name)');
}

var args,
scriptName = process.argv[2];
env['NODE_PATH'] = __dirname + '/../..';
Expand All @@ -19,9 +30,7 @@ if (!scriptName.match(/\.js/) && !scriptName.match(/\.coffee/)) {
}

if (!test('-f', scriptName)) {
console.log('ShellJS: script not found ('+scriptName+')');
console.log();
process.exit(1);
exitWithErrorMessage('ShellJS: script not found ('+scriptName+')');
}

args = process.argv.slice(3);
Expand Down
11 changes: 10 additions & 1 deletion test/shjs.js
Expand Up @@ -4,9 +4,10 @@ import test from 'ava';

import shell from '..';

const binPath = path.resolve(__dirname, '../bin/shjs');

function runWithShjs(name) {
// prefix with 'node ' for Windows, don't prefix for unix
const binPath = path.resolve(__dirname, '../bin/shjs');
const execPath = process.platform === 'win32'
? `${JSON.stringify(shell.config.execPath)} `
: '';
Expand Down Expand Up @@ -52,3 +53,11 @@ test('Extension detection', t => {
t.is(result.stdout, 'OK!\n');
t.falsy(result.stderr);
});

//
// Invalids
//

test('disallow require-ing', t => {
t.throws(() => require(binPath), 'Executable-only module should not be required');
});

0 comments on commit 93bbf68

Please sign in to comment.