From ba86f84d5f89ffbbf69a497bd345d1a6dc91b240 Mon Sep 17 00:00:00 2001 From: Aditi Date: Thu, 6 Feb 2025 04:30:46 +0530 Subject: [PATCH] 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. --- lib/internal/modules/cjs/loader.js | 7 +++++++ .../test-require-resolve-invalid-paths.js | 18 ++++++++++++++++++ 2 files changed, 25 insertions(+) create mode 100644 test/parallel/test-require-resolve-invalid-paths.js diff --git a/lib/internal/modules/cjs/loader.js b/lib/internal/modules/cjs/loader.js index 2e0492151a29bc..39eea53e429681 100644 --- a/lib/internal/modules/cjs/loader.js +++ b/lib/internal/modules/cjs/loader.js @@ -181,6 +181,7 @@ const { const { codes: { + ERR_INVALID_ARG_TYPE, ERR_INVALID_ARG_VALUE, ERR_INVALID_MODULE_SPECIFIER, ERR_REQUIRE_CYCLE_MODULE, @@ -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); @@ -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; } diff --git a/test/parallel/test-require-resolve-invalid-paths.js b/test/parallel/test-require-resolve-invalid-paths.js new file mode 100644 index 00000000000000..efe929d0c308f4 --- /dev/null +++ b/test/parallel/test-require-resolve-invalid-paths.js @@ -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', + } + ); + }); +}