◐ Shell
clean mode source ↗

module: fix require.resolve() crash on non-string paths · nodejs/node@a274b28

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+

}