Skip to content
Closed
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion packages/bun-types/bun.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1872,6 +1872,7 @@ declare module "bun" {
* Convert a {@link URL} to a filesystem path.
*
* @param url The URL to convert.
* @param options.windows When `true`, the path is returned in Windows format. Defaults to the current platform.
* @returns A filesystem path.
* @throws If `url` is not a valid URL.
*
Expand All @@ -1883,7 +1884,7 @@ declare module "bun" {
* console.log(path); // "/foo/bar.txt"
* ```
*/
function fileURLToPath(url: URL | string): string;
function fileURLToPath(url: URL | string, options?: { windows?: boolean }): string;

/**
* Fast incremental writer that becomes an {@link ArrayBuffer} on end().
Expand Down
25 changes: 0 additions & 25 deletions src/js/node/url.ts
Original file line number Diff line number Diff line change
Expand Up @@ -893,30 +893,6 @@ Url.prototype.parseHost = function parseHost() {
if (host) this.hostname = host;
};

// function fileURLToPath(...args) {
// // Since we use WTF::URL::fileSystemPath directly in Bun.fileURLToPath, we don't get invalid windows
// // path checking. We patch this in to `node:url` for compatibility. Note that
// // this behavior is missing from WATWG URL.
// if (process.platform === "win32") {
// var url: string;
// if ($isObject(args[0]) && args[0] instanceof Url) {
// url = (args[0] as { href: string }).href;
// } else if (typeof args[0] === "string") {
// url = args[0];
// } else {
// throw $ERR_INVALID_ARG_TYPE("url", ["string", "URL"], args[0]);
// }

// for (var i = 0; i < url.length; i++) {
// if (url.charCodeAt(i) === Char.PERCENT && (i + 1) < url.length) {
// switch (url.charCodeAt(i + 1)) {
// break;
// }
// }
// }
// return Bun.fileURLToPath.$call(args);
// }

/**
* Add new characters as needed from
* [here](https://github.com/nodejs/node/blob/main/lib/internal/constants.js).
Expand All @@ -933,7 +909,6 @@ const enum Char {
FORWARD_SLASH = 47, // /
HASH = 35, // #
QUESTION_MARK = 63, // ?
PERCENT = 37, // %
LEFT_SQUARE_BRACKET = 91, // [
RIGHT_SQUARE_BRACKET = 93, // ]

Expand Down
138 changes: 106 additions & 32 deletions src/jsc/bindings/BunObject.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
#include "helpers.h"
#include "IDLTypes.h"
#include "DOMURL.h"
#include <JavaScriptCore/Error.h>
#include <JavaScriptCore/JSPromise.h>
#include <JavaScriptCore/JSBase.h>
#include <JavaScriptCore/BuiltinNames.h>
Expand Down Expand Up @@ -44,6 +45,7 @@
#include "BunObjectModule.h"
#include "JSCookie.h"
#include "JSCookieMap.h"
#include "NodeURL.h"
#include "Secrets.h"

#ifdef WIN32
Expand Down Expand Up @@ -840,13 +842,76 @@ JSC_DEFINE_HOST_FUNCTION(functionGenerateHeapSnapshot, (JSC::JSGlobalObject * gl
RELEASE_AND_RETURN(throwScope, JSC::JSValue::encode(jsonValue));
}

// ECMA-262 `Decode` with an empty preserve set, which is what decodeURIComponent does.
// WTF::URL::fileSystemPath() is not usable here: it passes malformed escapes through
// verbatim and returns a null string for escapes that decode to invalid UTF-8.
static bool decodeFileURLPath(JSC::JSGlobalObject* globalObject, JSC::ThrowScope& scope, StringView input, String& result)
{
if (!input.contains('%')) {
result = input.toString();
return true;
}

// The URL parser percent-encodes everything outside of ASCII, so escapes are the
// only source of non-ASCII bytes.
ASSERT(input.containsOnlyASCII());

const unsigned length = input.length();
Vector<Latin1Character, 256> decoded;
decoded.reserveInitialCapacity(length);
for (unsigned i = 0; i < length;) {
char16_t character = input[i];
if (character != '%') {
decoded.append(static_cast<Latin1Character>(character));
++i;
continue;
}

if (i + 2 >= length || !isASCIIHexDigit(input[i + 1]) || !isASCIIHexDigit(input[i + 2])) {
throwException(globalObject, scope, createURIError(globalObject, "URI malformed"_s));
return false;
}

decoded.append(toASCIIHexValue(input[i + 1], input[i + 2]));
i += 3;
}

result = String::fromUTF8(decoded.span());
if (result.isNull()) {
throwException(globalObject, scope, createURIError(globalObject, "URI malformed"_s));
return false;
}
return true;
}

JSC_DEFINE_HOST_FUNCTION(functionFileURLToPath, (JSC::JSGlobalObject * globalObject, JSC::CallFrame* callFrame))
{
auto& vm = JSC::getVM(globalObject);
auto scope = DECLARE_THROW_SCOPE(vm);
JSValue arg0 = callFrame->argument(0);
WTF::URL url;

#if OS(WINDOWS)
constexpr bool windowsByDefault = true;
constexpr ASCIILiteral platformName = "win32"_s;
#elif OS(DARWIN)
constexpr bool windowsByDefault = false;
constexpr ASCIILiteral platformName = "darwin"_s;
#else
constexpr bool windowsByDefault = false;
constexpr ASCIILiteral platformName = "linux"_s;
#endif

// `options?.windows`, falling back to the host platform when absent.
bool windows = windowsByDefault;
JSValue options = callFrame->argument(1);
if (!options.isUndefinedOrNull()) {
JSValue windowsOption = options.get(globalObject, Identifier::fromString(vm, "windows"_s));
RETURN_IF_EXCEPTION(scope, {});
if (!windowsOption.isUndefinedOrNull())
windows = windowsOption.toBoolean(globalObject);
}

auto path = JSC::JSValue::encode(arg0);
auto* domURL = WebCoreCast<WebCore::JSDOMURL, WebCore::DOMURL>(path);
if (!domURL) {
Expand All @@ -867,50 +932,59 @@ JSC_DEFINE_HOST_FUNCTION(functionFileURLToPath, (JSC::JSGlobalObject * globalObj
return {};
}

// NOTE: On Windows, WTF::URL::fileSystemPath will handle UNC paths
// (`file:\\server\share\etc` -> `\\server\share\etc`), so hostname check only
// needs to happen on posix systems
#if !OS(WINDOWS)
// file://host/path is illegal if `host` is not `localhost`.
// Should be `file:///` instead
if (url.host().length() > 0 && url.host() != "localhost"_s) [[unlikely]] {
const StringView encodedPath = url.path();
const StringView host = url.host();

#if OS(DARWIN)
Bun::ERR::INVALID_FILE_URL_HOST(scope, globalObject, "darwin"_s);
return {};
#else
Bun::ERR::INVALID_FILE_URL_HOST(scope, globalObject, "linux"_s);
return {};
#endif
}
#endif

// ban url-encoded slashes. '/' on posix, '/' and '\' on windows.
const StringView p = url.path();
if (p.contains('%')) {
#if OS(WINDOWS)
if (p.contains("%2f"_s) || p.contains("%5c"_s) || p.contains("%2F"_s) || p.contains("%5C"_s)) {
Bun::ERR::INVALID_FILE_URL_PATH(scope, globalObject, "must not include encoded \\ or / characters"_s);
if (!windows) {
// file://host/path is illegal if `host` is not `localhost`.
// Should be `file:///` instead
if (host.length() > 0 && host != "localhost"_s) [[unlikely]] {
Bun::ERR::INVALID_FILE_URL_HOST(scope, globalObject, platformName);
return {};
}
#else
if (p.contains("%2f"_s) || p.contains("%2F"_s)) {

// ban url-encoded slashes.
if (encodedPath.contains('%') && (encodedPath.contains("%2f"_s) || encodedPath.contains("%2F"_s))) [[unlikely]] {
Bun::ERR::INVALID_FILE_URL_PATH(scope, globalObject, "must not include encoded / characters"_s);
return {};
}
#endif

String decodedPath;
if (!decodeFileURLPath(globalObject, scope, encodedPath, decodedPath))
return {};
return JSC::JSValue::encode(JSC::jsString(vm, decodedPath));
}

auto fileSystemPath = url.fileSystemPath();
// ban url-encoded slashes, '/' and '\' on windows.
if (encodedPath.contains('%') && (encodedPath.contains("%2f"_s) || encodedPath.contains("%2F"_s) || encodedPath.contains("%5c"_s) || encodedPath.contains("%5C"_s))) [[unlikely]] {
Bun::ERR::INVALID_FILE_URL_PATH(scope, globalObject, "must not include encoded \\ or / characters"_s);
return {};
}

#if OS(WINDOWS)
if (!isAbsolutePath(fileSystemPath)) {
Bun::ERR::INVALID_FILE_URL_PATH(scope, globalObject, "must be an absolute path"_s);
const String separatedPath = makeStringByReplacingAll(encodedPath, '/', '\\');
String decodedPath;
if (!decodeFileURLPath(globalObject, scope, separatedPath, decodedPath))
return {};

// UNC paths look like '\\server\share\etc', but in a URL they look like 'file://server/share/etc'.
if (!host.isEmpty()) {
// The parser leaves IDN hosts punycode-encoded; node hands the share name back in Unicode.
// Bun's parser, unlike node's, accepts hosts that are not decodable; keep those as-is rather
// than producing a UNC path with an empty server name.
String asciiHost = host.toString();
String serverName = Bun::domainToUnicode(asciiHost);
if (serverName.isNull())
serverName = asciiHost;
return JSC::JSValue::encode(JSC::jsString(vm, makeString("\\\\"_s, serverName, decodedPath)));
}

// Otherwise it is a local path, which requires a drive letter: '\C:\etc' -> 'C:\etc'.
if (decodedPath.length() < 3 || !isASCIIAlpha(decodedPath[1]) || decodedPath[2] != ':') [[unlikely]] {
Bun::ERR::INVALID_FILE_URL_PATH(scope, globalObject, "must be absolute"_s);
return {};
}
#endif

return JSC::JSValue::encode(JSC::jsString(vm, fileSystemPath));
return JSC::JSValue::encode(JSC::jsString(vm, decodedPath.substring(1)));
}

/* Source for BunObject.lut.h
Expand Down
50 changes: 31 additions & 19 deletions src/jsc/bindings/NodeURL.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,33 @@ JSC_DEFINE_HOST_FUNCTION(jsDomainToASCII, (JSC::JSGlobalObject * globalObject, J
return JSC::JSValue::encode(jsEmptyString(vm));
}

WTF::String domainToUnicode(const WTF::String& domain)
{
// this function is only for undoing punycode so its okay if utf-16 text makes it out unchanged.
if (!domain.is8Bit())
return domain;

WTF::String utf16Domain = domain;
utf16Domain.convertTo16Bit();

constexpr static int allowedNameToUnicodeErrors = UIDNA_ERROR_EMPTY_LABEL | UIDNA_ERROR_LABEL_TOO_LONG | UIDNA_ERROR_DOMAIN_NAME_TOO_LONG | UIDNA_ERROR_LEADING_HYPHEN | UIDNA_ERROR_TRAILING_HYPHEN | UIDNA_ERROR_HYPHEN_3_4;
constexpr static int hostnameBufferLength = 2048;

auto encoder = &WTF::URLParser::internationalDomainNameTranscoder();
char16_t hostnameBuffer[hostnameBufferLength];
UErrorCode error = U_ZERO_ERROR;
UIDNAInfo processingDetails = UIDNA_INFO_INITIALIZER;

const auto span = utf16Domain.span16();

int32_t numCharactersConverted = uidna_nameToUnicode(encoder, span.data(), span.size(), hostnameBuffer, hostnameBufferLength, &processingDetails, &error);

if (U_SUCCESS(error) && !(processingDetails.errors & ~allowedNameToUnicodeErrors) && numCharactersConverted)
return WTF::String(std::span { hostnameBuffer, static_cast<unsigned int>(numCharactersConverted) });

return {};
}

JSC_DEFINE_HOST_FUNCTION(jsDomainToUnicode, (JSC::JSGlobalObject * globalObject, JSC::CallFrame* callFrame))
{
auto& vm = JSC::getVM(globalObject);
Expand Down Expand Up @@ -118,27 +145,12 @@ JSC_DEFINE_HOST_FUNCTION(jsDomainToUnicode, (JSC::JSGlobalObject * globalObject,
return JSC::JSValue::encode(jsEmptyString(vm));

if (!domain.is8Bit())
// this function is only for undoing punycode so its okay if utf-16 text makes it out unchanged.
return JSC::JSValue::encode(arg0);

domain.convertTo16Bit();

constexpr static int allowedNameToUnicodeErrors = UIDNA_ERROR_EMPTY_LABEL | UIDNA_ERROR_LABEL_TOO_LONG | UIDNA_ERROR_DOMAIN_NAME_TOO_LONG | UIDNA_ERROR_LEADING_HYPHEN | UIDNA_ERROR_TRAILING_HYPHEN | UIDNA_ERROR_HYPHEN_3_4;
constexpr static int hostnameBufferLength = 2048;

auto encoder = &WTF::URLParser::internationalDomainNameTranscoder();
char16_t hostnameBuffer[hostnameBufferLength];
UErrorCode error = U_ZERO_ERROR;
UIDNAInfo processingDetails = UIDNA_INFO_INITIALIZER;

const auto span = domain.span16();

int32_t numCharactersConverted = uidna_nameToUnicode(encoder, span.data(), span.size(), hostnameBuffer, hostnameBufferLength, &processingDetails, &error);

if (U_SUCCESS(error) && !(processingDetails.errors & ~allowedNameToUnicodeErrors) && numCharactersConverted) {
return JSC::JSValue::encode(JSC::jsString(vm, WTF::String(std::span { hostnameBuffer, static_cast<unsigned int>(numCharactersConverted) })));
}
return JSC::JSValue::encode(jsEmptyString(vm));
auto unicodeDomain = domainToUnicode(domain);
if (unicodeDomain.isNull())
return JSC::JSValue::encode(jsEmptyString(vm));
return JSC::JSValue::encode(JSC::jsString(vm, unicodeDomain));
}

JSC::JSValue createNodeURLBinding(Zig::GlobalObject* globalObject)
Expand Down
3 changes: 3 additions & 0 deletions src/jsc/bindings/NodeURL.h
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,7 @@ namespace Bun {

JSC::JSValue createNodeURLBinding(Zig::GlobalObject*);

/// Undoes punycode encoding. Returns a null string when `domain` is not a valid IDN.
WTF::String domainToUnicode(const WTF::String& domain);

} // namespace Bun
16 changes: 15 additions & 1 deletion test/js/bun/util/fileUrl.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ describe("pathToFileURL", () => {
});

describe("fileURLToPath", () => {
const absoluteErrorMessage = "File URL path must be an absolute";
const absoluteErrorMessage = "File URL path must be absolute";
it("should convert a file url to a path", () => {
if (isWindows) {
expect(() => fileURLToPath("file:///path/to/file.js")).toThrow(absoluteErrorMessage);
Expand Down Expand Up @@ -61,4 +61,18 @@ describe("fileURLToPath", () => {
expect(fileURLToPath(url)).toBe(import.meta.path);
expect(fileURLToPath(import.meta.url)).toBe(import.meta.path);
});

it("should throw on malformed percent-encoding", () => {
expect(() => fileURLToPath("file:///%c3%28")).toThrow(URIError);
expect(() => fileURLToPath("file:///%")).toThrow(URIError);
expect(() => fileURLToPath(new URL("file:///%c3"))).toThrow(URIError);
});

it("should accept a windows option", () => {
expect(fileURLToPath("file:///C:/foo", { windows: true })).toBe("C:\\foo");
expect(fileURLToPath("file:///foo/bar", { windows: false })).toBe("/foo/bar");
expect(() => fileURLToPath("file:///C:/a%5Cb", { windows: true })).toThrow(
"File URL path must not include encoded \\ or / characters",
);
});
});
Loading
Loading