Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

module: prevent crashes in require.resolve() when path is not a string #56942

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions lib/internal/modules/cjs/loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,7 @@ const {

const {
codes: {
ERR_INVALID_ARG_TYPE,
ERR_INVALID_ARG_VALUE,
ERR_INVALID_MODULE_SPECIFIER,
ERR_REQUIRE_CYCLE_MODULE,
Expand Down Expand Up @@ -246,6 +247,9 @@ function wrapModuleLoad(request, parent, isMain) {
* @param {string} filename Absolute path to the file
*/
function stat(filename) {
// Guard against internal bugs where a non-string filename is passed in by mistake.
assert(typeof filename === 'string');

filename = path.toNamespacedPath(filename);
if (statCache !== null) {
const result = statCache.get(filename);
Expand Down Expand Up @@ -738,6 +742,9 @@ Module._findPath = function(request, paths, isMain, conditions = getCjsCondition
for (let i = 0; i < paths.length; i++) {
// Don't search further if path doesn't exist
const curPath = paths[i];
if (typeof curPath !== 'string') {
throw new ERR_INVALID_ARG_TYPE('paths', 'array of strings', paths);
}
if (insidePath && curPath && _stat(curPath) < 1) {
continue;
}
Expand Down
18 changes: 18 additions & 0 deletions test/parallel/test-require-resolve-invalid-paths.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
'use strict';

require('../common');
const assert = require('assert');

// Test invalid `paths` entries: Ensure non-string entries throw an error
{
const paths = [1, false, null, undefined, () => {}, {}];
paths.forEach((value) => {
assert.throws(
() => require.resolve('.', { paths: [value] }),
{
name: 'TypeError',
code: 'ERR_INVALID_ARG_TYPE',
}
);
});
}
Loading