Skip to content

Commit

Permalink
module: fix require.resolve() crash on non-string paths
Browse files Browse the repository at this point in the history
Previously, `require.resolve()` could crash when:
- The first parameter was a relative path and
- The `paths` array contained non-string entries

This commit fixes the issue by adding a check in `Module._findPath` to ensure
all elements in `paths` are strings, and adding a validation in `stat` before
calling `InternalModuleStat` to guard against non-string filenames.
  • Loading branch information
Aditi-1400 committed Feb 7, 2025
1 parent 316014d commit 8c80bb8
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
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',
}
);
});
}

0 comments on commit 8c80bb8

Please sign in to comment.