Skip to content

Commit a274b28

Browse files
Aditi-1400targos
authored andcommitted
module: fix require.resolve() crash on non-string paths
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. PR-URL: #56942 Fixes: #47698 Reviewed-By: Joyee Cheung <joyeec9h3@gmail.com> Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com> Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
1 parent b5a8a81 commit a274b28

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

lib/internal/modules/cjs/loader.js

+7
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,7 @@ const {
181181

182182
const {
183183
codes: {
184+
ERR_INVALID_ARG_TYPE,
184185
ERR_INVALID_ARG_VALUE,
185186
ERR_INVALID_MODULE_SPECIFIER,
186187
ERR_REQUIRE_CYCLE_MODULE,
@@ -246,6 +247,9 @@ function wrapModuleLoad(request, parent, isMain) {
246247
* @param {string} filename Absolute path to the file
247248
*/
248249
function stat(filename) {
250+
// Guard against internal bugs where a non-string filename is passed in by mistake.
251+
assert(typeof filename === 'string');
252+
249253
filename = path.toNamespacedPath(filename);
250254
if (statCache !== null) {
251255
const result = statCache.get(filename);
@@ -738,6 +742,9 @@ Module._findPath = function(request, paths, isMain, conditions = getCjsCondition
738742
for (let i = 0; i < paths.length; i++) {
739743
// Don't search further if path doesn't exist
740744
const curPath = paths[i];
745+
if (typeof curPath !== 'string') {
746+
throw new ERR_INVALID_ARG_TYPE('paths', 'array of strings', paths);
747+
}
741748
if (insidePath && curPath && _stat(curPath) < 1) {
742749
continue;
743750
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
'use strict';
2+
3+
require('../common');
4+
const assert = require('assert');
5+
6+
// Test invalid `paths` entries: Ensure non-string entries throw an error
7+
{
8+
const paths = [1, false, null, undefined, () => {}, {}];
9+
paths.forEach((value) => {
10+
assert.throws(
11+
() => require.resolve('.', { paths: [value] }),
12+
{
13+
name: 'TypeError',
14+
code: 'ERR_INVALID_ARG_TYPE',
15+
}
16+
);
17+
});
18+
}

0 commit comments

Comments
 (0)