From 1d1d8f2df35d2b48fff0d822980e937dfd66f9ec Mon Sep 17 00:00:00 2001 From: Antoine du Hamel Date: Wed, 25 Dec 2024 19:42:11 +0100 Subject: [PATCH] url: use resolved path to convert UNC paths to URL PR-URL: https://github.com/nodejs/node/pull/56302 Fixes: https://github.com/nodejs/node/issues/56262 Reviewed-By: Benjamin Gruenbaum Reviewed-By: Yagiz Nizipli Reviewed-By: Luigi Pinca Reviewed-By: Xuguang Mei --- lib/internal/url.js | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/lib/internal/url.js b/lib/internal/url.js index 14b0ef61d2f91c..f6e58e196860fc 100644 --- a/lib/internal/url.js +++ b/lib/internal/url.js @@ -1512,32 +1512,35 @@ function fileURLToPath(path, options = kEmptyObject) { function pathToFileURL(filepath, options = kEmptyObject) { const windows = options?.windows ?? isWindows; - if (windows && StringPrototypeStartsWith(filepath, '\\\\')) { + const isUNC = windows && StringPrototypeStartsWith(filepath, '\\\\'); + let resolved = isUNC ? + filepath : + (windows ? path.win32.resolve(filepath) : path.posix.resolve(filepath)); + if (isUNC || (windows && StringPrototypeStartsWith(resolved, '\\\\'))) { // UNC path format: \\server\share\resource // Handle extended UNC path and standard UNC path // "\\?\UNC\" path prefix should be ignored. // Ref: https://learn.microsoft.com/en-us/windows/win32/fileio/maximum-file-path-limitation - const isExtendedUNC = StringPrototypeStartsWith(filepath, '\\\\?\\UNC\\'); + const isExtendedUNC = StringPrototypeStartsWith(resolved, '\\\\?\\UNC\\'); const prefixLength = isExtendedUNC ? 8 : 2; - const hostnameEndIndex = StringPrototypeIndexOf(filepath, '\\', prefixLength); + const hostnameEndIndex = StringPrototypeIndexOf(resolved, '\\', prefixLength); if (hostnameEndIndex === -1) { throw new ERR_INVALID_ARG_VALUE( 'path', - filepath, + resolved, 'Missing UNC resource path', ); } if (hostnameEndIndex === 2) { throw new ERR_INVALID_ARG_VALUE( 'path', - filepath, + resolved, 'Empty UNC servername', ); } - const hostname = StringPrototypeSlice(filepath, prefixLength, hostnameEndIndex); - return new URL(StringPrototypeSlice(filepath, hostnameEndIndex), hostname, kCreateURLFromWindowsPathSymbol); + const hostname = StringPrototypeSlice(resolved, prefixLength, hostnameEndIndex); + return new URL(StringPrototypeSlice(resolved, hostnameEndIndex), hostname, kCreateURLFromWindowsPathSymbol); } - let resolved = windows ? path.win32.resolve(filepath) : path.posix.resolve(filepath); // path.resolve strips trailing slashes so we must add them back const filePathLast = StringPrototypeCharCodeAt(filepath, filepath.length - 1);