Skip to content

Commit 41f3dfd

Browse files
Aditi-1400marco-ippolito
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 faa08b1 commit 41f3dfd

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

lib/internal/modules/cjs/loader.js

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -170,6 +170,7 @@ const {
170170

171171
const {
172172
codes: {
173+
ERR_INVALID_ARG_TYPE,
173174
ERR_INVALID_ARG_VALUE,
174175
ERR_INVALID_MODULE_SPECIFIER,
175176
ERR_REQUIRE_CYCLE_MODULE,
@@ -223,6 +224,9 @@ function internalRequire(module, id) {
223224
* @param {string} filename Absolute path to the file
224225
*/
225226
function stat(filename) {
227+
// Guard against internal bugs where a non-string filename is passed in by mistake.
228+
assert(typeof filename === 'string');
229+
226230
filename = path.toNamespacedPath(filename);
227231
if (statCache !== null) {
228232
const result = statCache.get(filename);
@@ -704,6 +708,9 @@ Module._findPath = function(request, paths, isMain) {
704708
for (let i = 0; i < paths.length; i++) {
705709
// Don't search further if path doesn't exist
706710
const curPath = paths[i];
711+
if (typeof curPath !== 'string') {
712+
throw new ERR_INVALID_ARG_TYPE('paths', 'array of strings', paths);
713+
}
707714
if (insidePath && curPath && _stat(curPath) < 1) {
708715
continue;
709716
}
Lines changed: 18 additions & 0 deletions
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)