From 3fcad404d832acc7358810229d6dd2e631be7db2 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Thu, 26 Nov 2026 18:47:24 -0300 Subject: [PATCH 01/13] test(runtime): pin the spelling of the module URLs dev tooling emits Records what the loader does today for the URL shapes dev servers emit, both as registry keys (with and without a tooling-shaped canonicalization vocabulary) and as loaded modules reached from a file module directly and through an import-map entry: import.meta.url, getLoadedModuleUrls(), the request target the server saw, and eviction by invalidateModules. --- TestRunner/app/tests/HttpEsmLoaderTests.js | 206 ++++++++++++++++++ .../tests/esm/tooling-url/static-importer.mjs | 1 + 2 files changed, 207 insertions(+) create mode 100644 TestRunner/app/tests/esm/tooling-url/static-importer.mjs diff --git a/TestRunner/app/tests/HttpEsmLoaderTests.js b/TestRunner/app/tests/HttpEsmLoaderTests.js index ad4511f4..9e6ad98a 100644 --- a/TestRunner/app/tests/HttpEsmLoaderTests.js +++ b/TestRunner/app/tests/HttpEsmLoaderTests.js @@ -2172,6 +2172,109 @@ describe("HTTP ESM Loader", function() { }); }); }); + + // The spelling of these URLs is what dev tooling compares module URLs + // against, so it must survive every route into the loader byte for byte. + describe("module URLs in the shapes dev tooling emits", function () { + var nsModule = require("ns:module"); + + afterEach(function () { + nsModule.configureLoader({ importMap: { imports: {} } }); + }); + + // Each module reports the request target the server saw and its own + // import.meta.url. + function expectSpelledAsWritten(ns, url) { + var target = url.slice(url.indexOf("/", url.indexOf("://") + 3)); + var q = target.indexOf("?"); + expect(ns.url).toBe(url); + expect(ns.path).toBe(q < 0 ? target : target.slice(0, q)); + expect(ns.query).toBe(q < 0 ? "" : target.slice(q + 1)); + expect(nsModule.getLoadedModuleUrls()).toContain(url); + } + + function expectEvicted(urls) { + nsModule.invalidateModules(urls); + var loaded = nsModule.getLoadedModuleUrls(); + urls.forEach(function (url) { + expect(loaded).not.toContain(url); + }); + } + + it("keeps them as written when a file module imports them", function (done) { + var origin = getHostOrigin(); + if (!origin) { + pending("REPORT_BASEURL not set; skipping host HTTP tests"); + done(); + return; + } + var written = origin.replace("127.0.0.1", "LOCALHOST"); + var base = origin + "/esm/resolve/tooling-direct"; + var urls = [ + base + "/ns/m/src/app.ts?v=abc", + base + "/ns/core/index.js", + base + "/ns/node/x", + base + "/ns/m/node_modules/pkg/index.js", + base + "/ns/asm?path=%2Fsrc%2FApp.vue&mode=inline", + base + "/ns/asm?path=/src/App.vue&mode=inline", + base + "/ns/sfc/src/App.vue?vue&type=script", + base + "/ns/m/q.js?b=2&a=1", + base + "/@ng/component?c=x&t=1", + base + "/@id/__x00__virtual:thing", + base + "/@fs/Users/me/proj/x.ts", + written + "/esm/resolve/tooling-direct/ns/m/upper.js?v=1", + ]; + Promise.all(urls.map(function (url) { + return import(url); + })).then(function (namespaces) { + namespaces.forEach(function (ns, i) { + expectSpelledAsWritten(ns, urls[i]); + }); + expectEvicted(urls); + done(); + }).catch(function (error) { + expect("rejected: " + formatError(error)).toBe("resolved"); + done(); + }); + }); + + it("keeps them as written when an import-map entry targets them", function (done) { + var origin = getHostOrigin(); + if (!origin) { + pending("REPORT_BASEURL not set; skipping host HTTP tests"); + done(); + return; + } + var written = origin.replace("127.0.0.1", "LOCALHOST"); + var base = origin + "/esm/resolve/tooling-mapped"; + var dynamicUrl = base + "/ns/m/src/dynamic.ts?v=abc"; + var staticUrl = base + "/ns/asm?path=%2Fsrc%2FApp.vue&mode=inline"; + var upperUrl = written + "/esm/resolve/tooling-mapped/ns/m/upper.js?b=2&a=1"; + nsModule.configureLoader({ + importMap: { + imports: { + "ns-tooling-url-dynamic": dynamicUrl, + "ns-tooling-url-static": staticUrl, + "ns-tooling-url-upper": upperUrl, + }, + }, + }); + Promise.all([ + import("ns-tooling-url-dynamic"), + import("~/tests/esm/tooling-url/static-importer.mjs"), + import("ns-tooling-url-upper"), + ]).then(function (namespaces) { + expectSpelledAsWritten(namespaces[0], dynamicUrl); + expectSpelledAsWritten(namespaces[1].dep, staticUrl); + expectSpelledAsWritten(namespaces[2], upperUrl); + expectEvicted([dynamicUrl, staticUrl, upperUrl]); + done(); + }).catch(function (error) { + expect("rejected: " + formatError(error)).toBe("resolved"); + done(); + }); + }); + }); }); // Focused, deterministic coverage for the native HTTP canonical-key function. @@ -2184,6 +2287,8 @@ describe("HTTP canonical key (ns:module canonicalizeHttpUrlKey)", function () { return require("ns:module").canonicalizeHttpUrlKey; } + // A registered key is canonicalized again whenever it is looked up, so a key + // must be a fixed point. function checkKey(input, expected) { var canon = getCanon(); if (typeof canon !== "function") { @@ -2191,8 +2296,77 @@ describe("HTTP canonical key (ns:module canonicalizeHttpUrlKey)", function () { return; } expect(canon(input)).toBe(expected); + expect(canon(expected)).toBe(expected); } + // [input, key with no vocabulary, key under TOOLING_VOCABULARY] + var TOOLING_URLS = [ + ["http://h:5173/ns/m/src/app.ts?v=abc", + "http://h:5173/ns/m/src/app.ts?v=abc", + "http://h:5173/ns/m/src/app.ts"], + ["http://h:5173/ns/core/index.js", + "http://h:5173/ns/core/index.js", + "http://h:5173/ns/core/index.js"], + ["http://h:5173/ns/node/x", + "http://h:5173/ns/node/x", + "http://h:5173/ns/node/x"], + ["http://h:5173/ns/m/node_modules/pkg/index.js?v=abc", + "http://h:5173/ns/m/node_modules/pkg/index.js?v=abc", + "http://h:5173/ns/m/node_modules/pkg/index.js"], + ["http://h:5173/ns/asm?path=%2Fsrc%2FApp.vue&mode=inline", + "http://h:5173/ns/asm?path=%2Fsrc%2FApp.vue&mode=inline", + "http://h:5173/ns/asm?mode=inline&path=%2Fsrc%2FApp.vue"], + ["http://h:5173/ns/asm?path=/src/App.vue&mode=inline", + "http://h:5173/ns/asm?path=/src/App.vue&mode=inline", + "http://h:5173/ns/asm?mode=inline&path=/src/App.vue"], + ["http://h:5173/ns/sfc/src/App.vue?vue&type=script", + "http://h:5173/ns/sfc/src/App.vue?vue&type=script", + "http://h:5173/ns/sfc/src/App.vue?type=script&vue"], + ["http://h:5173/ns/m/q.js?b=2&a=1", + "http://h:5173/ns/m/q.js?b=2&a=1", + "http://h:5173/ns/m/q.js?a=1&b=2"], + ["http://h:5173/@ng/component?c=x&t=1", + "http://h:5173/@ng/component?c=x&t=1", + "http://h:5173/@ng/component?c=x&t=1"], + ["http://h:5173/@id/__x00__virtual:thing?import", + "http://h:5173/@id/__x00__virtual:thing?import", + "http://h:5173/@id/__x00__virtual:thing"], + ["http://h:5173/@fs/Users/me/proj/x.ts?t=1", + "http://h:5173/@fs/Users/me/proj/x.ts?t=1", + "http://h:5173/@fs/Users/me/proj/x.ts"], + ["http://h:5173/node_modules/.vite/deps/pkg.js?v=abc", + "http://h:5173/node_modules/.vite/deps/pkg.js?v=abc", + "http://h:5173/node_modules/.vite/deps/pkg.js"], + ["http://MyMac.local:5173/ns/m/app.js?v=1", + "http://MyMac.local:5173/ns/m/app.js?v=1", + "http://MyMac.local:5173/ns/m/app.js"], + ["http://MyMac.local:5173/ns/m/app.js?", + "http://MyMac.local:5173/ns/m/app.js?", + "http://MyMac.local:5173/ns/m/app.js"], + ["http://MyMac.local:5173/ns/m/app.js#", + "http://MyMac.local:5173/ns/m/app.js", + "http://MyMac.local:5173/ns/m/app.js"], + ["http://h:80/ns/m/app.js?v=1", + "http://h:80/ns/m/app.js?v=1", + "http://h:80/ns/m/app.js"], + ["http://192.168.1.20:5173/ns/m/app.js?v=1", + "http://192.168.1.20:5173/ns/m/app.js?v=1", + "http://192.168.1.20:5173/ns/m/app.js"], + ["http://[::1]:5173/ns/m/app.js?v=1", + "http://[::1]:5173/ns/m/app.js?v=1", + "http://[::1]:5173/ns/m/app.js"], + // The URL parser rejects a zone id; the key keeps the URL as written. + ["http://[fe80::1%25en0]:5173/ns/m/app.js?v=1#x", + "http://[fe80::1%25en0]:5173/ns/m/app.js?v=1", + "http://[fe80::1%25en0]:5173/ns/m/app.js"], + ]; + + var TOOLING_VOCABULARY = { + stripParams: ["t", "v", "import"], + forPathPrefixes: ["/ns/", "/@id/", "/@fs/", "/node_modules/.vite/"], + preserveQueryFor: ["/@ng/component"], + }; + it("is exposed as a function in debug builds", function () { var canon = getCanon(); if (typeof canon !== "function") { @@ -2249,6 +2423,38 @@ describe("HTTP canonical key (ns:module canonicalizeHttpUrlKey)", function () { checkKey("https://cdn.example.com/lib.js?token=abc#frag", "https://cdn.example.com/lib.js?token=abc"); }); + + it("keeps the URLs dev tooling emits as written", function () { + TOOLING_URLS.forEach(function (row) { + checkKey(row[0], row[1]); + }); + }); + }); + + describe("with a tooling-shaped vocabulary", function () { + beforeEach(function () { + var nsModule = require("ns:module"); + if (typeof nsModule.canonicalizeHttpUrlKey !== "function") { + return; + } + nsModule.configureLoader({ canonicalization: TOOLING_VOCABULARY }); + }); + + afterEach(function () { + var nsModule = require("ns:module"); + if (typeof nsModule.canonicalizeHttpUrlKey !== "function") { + return; + } + nsModule.configureLoader({ + canonicalization: { stripParams: [], forPathPrefixes: [], preserveQueryFor: [] }, + }); + }); + + it("keys the URLs dev tooling emits", function () { + TOOLING_URLS.forEach(function (row) { + checkKey(row[0], row[2]); + }); + }); }); // Canonicalization config is process-wide, so each spec here installs its diff --git a/TestRunner/app/tests/esm/tooling-url/static-importer.mjs b/TestRunner/app/tests/esm/tooling-url/static-importer.mjs new file mode 100644 index 00000000..d4c10436 --- /dev/null +++ b/TestRunner/app/tests/esm/tooling-url/static-importer.mjs @@ -0,0 +1 @@ +export * as dep from "ns-tooling-url-static"; From ae45c1ff3c63c0bfeefcb38908ef2199d40c8b69 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Thu, 26 Nov 2026 18:55:21 -0300 Subject: [PATCH 02/13] refactor(runtime): one shared unit for the loader's module URL helpers IsHttpRegistryKey, ParseModuleUrl and the written-authority rule move out of ModuleInternalCallbacks.mm into ModuleUrl, which also gains NormalizeHttpModuleUrl: the spelling the loader gives an absolute http(s) module URL, falling back to the input itself for an HTTP-prefixed string the URL parser rejects. ParseModuleUrl now rebuilds the written-authority href by replacing only the authority inside the parser's href. Rebuilding from the pathname, search and hash getters lost a bare trailing '?' or '#', so the re-parse check failed and the parser's lowercased host replaced the written one. --- .../runtime/ModuleInternalCallbacks.mm | 97 +---------------- NativeScript/runtime/ModuleUrl.cpp | 103 ++++++++++++++++++ NativeScript/runtime/ModuleUrl.h | 37 +++++++ TestRunner/app/tests/HttpEsmLoaderTests.js | 21 ++++ v8ios.xcodeproj/project.pbxproj | 8 ++ 5 files changed, 171 insertions(+), 95 deletions(-) create mode 100644 NativeScript/runtime/ModuleUrl.cpp create mode 100644 NativeScript/runtime/ModuleUrl.h diff --git a/NativeScript/runtime/ModuleInternalCallbacks.mm b/NativeScript/runtime/ModuleInternalCallbacks.mm index a5f1895c..ebf21583 100644 --- a/NativeScript/runtime/ModuleInternalCallbacks.mm +++ b/NativeScript/runtime/ModuleInternalCallbacks.mm @@ -28,12 +28,12 @@ #include "Helpers.h" // for tns::Exists #include "HttpLoader.h" #include "ModuleInternal.h" // for CompileFileEsModule / EvaluateModuleGraph +#include "ModuleUrl.h" #include "NativeScriptException.h" #include "NativeScriptPlatform.h" #include "NsBuiltinModules.h" #include "Runtime.h" // for GetAppConfigValue #include "RuntimeConfig.h" -#include "ada/ada.h" // Do NOT pull all v8 symbols into namespace here; String would clash with // other typedefs inside the NativeScript codebase. We refer to v8 symbols @@ -90,19 +90,6 @@ static inline bool StartsWith(const std::string& s, const char* prefix) { return s.size() >= n && s.compare(0, n, prefix) == 0; } -// Whether `key` is spelled the way the loader keys an HTTP module: a lowercase -// `http://` or `https://` prefix, file modules being keyed by absolute paths. -// Deliberately not a URL parse: it gates the rule that an HTTP importer never -// reaches the filesystem implicitly, so a key the URL parser would reject (an -// IPv6 zone id, say) must still count as HTTP. -static bool IsHttpRegistryKey(const std::string& key) { - if (key.compare(0, 4, "http") != 0) { - return false; - } - const size_t schemeEnd = key.size() > 4 && key[4] == 's' ? 5 : 4; - return key.compare(schemeEnd, 3, "://") == 0; -} - static bool ShouldTraceRegistryKey(const std::string& rawKey, const std::string& registryKey); static std::string CanonicalizeRegistryKey(const std::string& key); static const char* ModuleStatusToString(v8::Module::Status status); @@ -1560,85 +1547,6 @@ static void DrainStreamedCompilesForIsolate(v8::Isolate* isolate) { return "Cannot find module '" + resolution.specifier + "' (tried " + resolution.attempted + ")"; } -static bool HasHttpScheme(const ada::url_aggregator& url) { - return url.type == ada::scheme::type::HTTP || url.type == ada::scheme::type::HTTPS; -} - -// The authority (userinfo, host, port) of an absolute or scheme-relative URL -// exactly as written, or empty when `url` does not spell one plainly. -static std::string WrittenAuthority(const std::string& url) { - size_t start = 0; - if (StartsWith(url, "//")) { - start = 2; - } else { - const size_t colon = url.find(':'); - if (colon == std::string::npos || url.compare(colon, 3, "://") != 0) { - return std::string(); - } - start = colon + 3; - } - const size_t end = url.find_first_of("/?#", start); - std::string authority = url.substr(start, end == std::string::npos ? end : end - start); - for (const char c : authority) { - if (static_cast(c) <= 0x20 || c == '\\') { - return std::string(); - } - } - return authority; -} - -struct ModuleUrl { - bool parsed = false; - bool http = false; // the scheme is http or https - std::string href; -}; - -// `input` parsed with the WHATWG URL parser (the one behind JS `new URL()`): -// as an absolute URL when `base` is empty, otherwise as a path- or -// scheme-relative reference against `base`. -// -// An http(s) result keeps its authority as written by whichever string -// supplied it: tooling compares module URLs against the origin string it was -// configured with, so that spelling is part of a module's identity until every -// loader entry point canonicalizes. The parser's own href is used whenever the -// written authority would not name the same URL. -static ModuleUrl ParseModuleUrl(const std::string& input, const std::string& base) { - ModuleUrl result; - ada::result url; - if (base.empty()) { - url = ada::parse(input, nullptr); - } else { - auto baseUrl = ada::parse(base, nullptr); - if (!baseUrl) { - return result; - } - url = ada::parse(input, &baseUrl.value()); - } - if (!url) { - return result; - } - result.parsed = true; - result.http = HasHttpScheme(*url); - result.href = std::string(url->get_href()); - if (!result.http) { - return result; - } - - const std::string authority = - WrittenAuthority(base.empty() || StartsWith(input, "//") ? input : base); - if (authority.empty()) { - return result; - } - const std::string written = std::string(url->get_protocol()) + "//" + authority + - std::string(url->get_pathname()) + std::string(url->get_search()) + - std::string(url->get_hash()); - auto reparsed = ada::parse(written, nullptr); - if (reparsed && reparsed->get_href() == url->get_href()) { - result.href = written; - } - return result; -} - struct UrlSpecifier { enum class Kind { kHttpUrl, // an http(s) URL @@ -3163,8 +3071,7 @@ static void FinishHttpDynamicImport(v8::Isolate* isolate, v8::Local // app path the registry keys by, or no scope would match it. const std::string resourceName(*resourceUtf8); const std::string resourceUrl = RepairCollapsedUrlScheme(resourceName); - const auto parsedResource = ada::parse(resourceUrl, nullptr); - if (parsedResource && HasHttpScheme(*parsedResource)) { + if (ParseModuleUrl(resourceUrl, std::string()).http) { dynamicReferrerKey = CanonicalizeRegistryKey(resourceUrl); } else { const ModuleResolution referrer = diff --git a/NativeScript/runtime/ModuleUrl.cpp b/NativeScript/runtime/ModuleUrl.cpp new file mode 100644 index 00000000..3742e534 --- /dev/null +++ b/NativeScript/runtime/ModuleUrl.cpp @@ -0,0 +1,103 @@ +#include "ModuleUrl.h" + +#include + +#include "ada/ada.h" + +namespace tns { + +namespace { + +bool StartsWith(const std::string& s, const char* prefix) { + const size_t n = std::char_traits::length(prefix); + return s.size() >= n && s.compare(0, n, prefix) == 0; +} + +bool HasHttpScheme(const ada::url_aggregator& url) { + return url.type == ada::scheme::type::HTTP || + url.type == ada::scheme::type::HTTPS; +} + +// The authority (userinfo, host, port) of an absolute or scheme-relative URL +// exactly as written, or empty when `url` does not spell one plainly. +std::string WrittenAuthority(const std::string& url) { + size_t start = 0; + if (StartsWith(url, "//")) { + start = 2; + } else { + const size_t colon = url.find(':'); + if (colon == std::string::npos || url.compare(colon, 3, "://") != 0) { + return std::string(); + } + start = colon + 3; + } + const size_t end = url.find_first_of("/?#", start); + std::string authority = + url.substr(start, end == std::string::npos ? end : end - start); + for (const char c : authority) { + if (static_cast(c) <= 0x20 || c == '\\') { + return std::string(); + } + } + return authority; +} + +} // namespace + +bool IsHttpRegistryKey(const std::string& key) { + if (key.compare(0, 4, "http") != 0) { + return false; + } + const size_t schemeEnd = key.size() > 4 && key[4] == 's' ? 5 : 4; + return key.compare(schemeEnd, 3, "://") == 0; +} + +ModuleUrl ParseModuleUrl(const std::string& input, const std::string& base) { + ModuleUrl result; + ada::result url; + if (base.empty()) { + url = ada::parse(input, nullptr); + } else { + auto baseUrl = ada::parse(base, nullptr); + if (!baseUrl) { + return result; + } + url = ada::parse(input, &baseUrl.value()); + } + if (!url) { + return result; + } + result.parsed = true; + result.http = HasHttpScheme(*url); + result.href = std::string(url->get_href()); + if (!result.http) { + return result; + } + + const std::string authority = + WrittenAuthority(base.empty() || StartsWith(input, "//") ? input : base); + if (authority.empty()) { + return result; + } + // Everything after the authority comes from the parser's own href: its + // getters drop an empty query's '?' and an empty fragment's '#'. + const std::string_view href = url->get_href(); + const std::string written = + std::string(url->get_protocol()) + "//" + authority + + std::string(href.substr(url->get_components().pathname_start)); + auto reparsed = ada::parse(written, nullptr); + if (reparsed && reparsed->get_href() == href) { + result.href = written; + } + return result; +} + +std::string NormalizeHttpModuleUrl(const std::string& input) { + const ModuleUrl url = ParseModuleUrl(input, std::string()); + if (url.parsed) { + return url.http ? url.href : std::string(); + } + return IsHttpRegistryKey(input) ? input : std::string(); +} + +} // namespace tns diff --git a/NativeScript/runtime/ModuleUrl.h b/NativeScript/runtime/ModuleUrl.h new file mode 100644 index 00000000..eb3ec7c8 --- /dev/null +++ b/NativeScript/runtime/ModuleUrl.h @@ -0,0 +1,37 @@ +#pragma once + +#include + +namespace tns { + +// Whether `key` is spelled the way the loader keys an HTTP module: a lowercase +// `http://` or `https://` prefix, file modules being keyed by absolute paths. +// Deliberately not a URL parse: it gates the rule that an HTTP importer never +// reaches the filesystem implicitly, so a key the URL parser would reject (an +// IPv6 zone id, say) must still count as HTTP. +bool IsHttpRegistryKey(const std::string& key); + +struct ModuleUrl { + bool parsed = false; + bool http = false; // the scheme is http or https + std::string href; +}; + +// `input` parsed with the WHATWG URL parser (the one behind JS `new URL()`): +// as an absolute URL when `base` is empty, otherwise as a path- or +// scheme-relative reference against `base`. +// +// An http(s) result keeps its authority as written by whichever string +// supplied it: tooling compares module URLs against the origin string it was +// configured with, so that spelling is part of a module's identity. The +// parser's own href is used whenever the written authority would not name the +// same URL. +ModuleUrl ParseModuleUrl(const std::string& input, const std::string& base); + +// The spelling the loader gives `input` as an absolute http(s) module URL: +// ParseModuleUrl's href; `input` itself when the parser rejects it but it is +// spelled as an HTTP key (fail closed: it stays HTTP); empty when `input` is +// not an http(s) URL. +std::string NormalizeHttpModuleUrl(const std::string& input); + +} // namespace tns diff --git a/TestRunner/app/tests/HttpEsmLoaderTests.js b/TestRunner/app/tests/HttpEsmLoaderTests.js index 9e6ad98a..f957a6f1 100644 --- a/TestRunner/app/tests/HttpEsmLoaderTests.js +++ b/TestRunner/app/tests/HttpEsmLoaderTests.js @@ -1934,6 +1934,27 @@ describe("HTTP ESM Loader", function() { }); }); + it("keeps the importer's origin as written when the query or fragment is empty", + function (done) { + var origin = getHostOrigin(); + if (!origin) { + pending("REPORT_BASEURL not set; skipping host HTTP tests"); + done(); + return; + } + var written = origin.replace("127.0.0.1", "LOCALHOST"); + importer(written, "authority-empty").then(function (mod) { + return Promise.all([mod.load("./query.mjs?"), mod.load("./hash.mjs#")]); + }).then(function (mods) { + expect(mods[0].url).toBe(written + "/esm/resolve/authority-empty/query.mjs?"); + expect(mods[1].url).toBe(written + "/esm/resolve/authority-empty/hash.mjs"); + done(); + }).catch(function (error) { + expect("rejected: " + formatError(error)).toBe("resolved"); + done(); + }); + }); + it("normalizes a specifier the way the WHATWG URL parser does", function (done) { var origin = getHostOrigin(); if (!origin) { diff --git a/v8ios.xcodeproj/project.pbxproj b/v8ios.xcodeproj/project.pbxproj index 93c7c50c..c5178f96 100644 --- a/v8ios.xcodeproj/project.pbxproj +++ b/v8ios.xcodeproj/project.pbxproj @@ -70,6 +70,8 @@ AA5DBFD42EC191F8008D12F9 /* HttpLoader.h in Headers */ = {isa = PBXBuildFile; fileRef = AA5DBFD12EC191F8008D12F9 /* HttpLoader.h */; }; AA8C47B12E27114300649BF5 /* ModuleInternalCallbacks.h in Headers */ = {isa = PBXBuildFile; fileRef = AA8C47AF2E27114300649BF5 /* ModuleInternalCallbacks.h */; }; AA8C47B22E27114300649BF5 /* ModuleInternalCallbacks.mm in Sources */ = {isa = PBXBuildFile; fileRef = AA8C47B02E27114300649BF5 /* ModuleInternalCallbacks.mm */; }; + B0E1A0032F0A000100000001 /* ModuleUrl.h in Headers */ = {isa = PBXBuildFile; fileRef = B0E1A0012F0A000100000001 /* ModuleUrl.h */; }; + B0E1A0042F0A000100000001 /* ModuleUrl.cpp in Sources */ = {isa = PBXBuildFile; fileRef = B0E1A0022F0A000100000001 /* ModuleUrl.cpp */; }; C205257F2577D6F900C12A5C /* NativeScript.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = C2DDEB32229EAB3B00345BFE /* NativeScript.framework */; }; C20525802577D6F900C12A5C /* NativeScript.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = C2DDEB32229EAB3B00345BFE /* NativeScript.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; C20AB5E626E1015300E2B41D /* OneByteStringResource.cpp in Sources */ = {isa = PBXBuildFile; fileRef = C20AB5E426E1015200E2B41D /* OneByteStringResource.cpp */; }; @@ -550,6 +552,8 @@ AA5DBFD22EC191F8008D12F9 /* HttpLoader.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = HttpLoader.mm; sourceTree = ""; }; AA8C47AF2E27114300649BF5 /* ModuleInternalCallbacks.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = ModuleInternalCallbacks.h; sourceTree = ""; }; AA8C47B02E27114300649BF5 /* ModuleInternalCallbacks.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = ModuleInternalCallbacks.mm; sourceTree = ""; }; + B0E1A0012F0A000100000001 /* ModuleUrl.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = ModuleUrl.h; sourceTree = ""; }; + B0E1A0022F0A000100000001 /* ModuleUrl.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = ModuleUrl.cpp; sourceTree = ""; }; C2003F9E23FA78CD0043B815 /* TNSDerivedClass.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TNSDerivedClass.h; sourceTree = ""; }; C20525A72577D86600C12A5C /* TNSWidgets.xcframework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.xcframework; path = TNSWidgets.xcframework; sourceTree = ""; }; C20AB5E426E1015200E2B41D /* OneByteStringResource.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = OneByteStringResource.cpp; sourceTree = ""; }; @@ -1561,6 +1565,8 @@ C2DDEB89229EAC8300345BFE /* ModuleInternal.h */, AA8C47AF2E27114300649BF5 /* ModuleInternalCallbacks.h */, AA8C47B02E27114300649BF5 /* ModuleInternalCallbacks.mm */, + B0E1A0012F0A000100000001 /* ModuleUrl.h */, + B0E1A0022F0A000100000001 /* ModuleUrl.cpp */, C2DDEB81229EAC8200345BFE /* ModuleInternal.mm */, 2B7EA6AE2353477000E5184E /* NativeScriptException.h */, 2B7EA6AD2353476F00E5184E /* NativeScriptException.mm */, @@ -1820,6 +1826,7 @@ C247C16822F82842001D2CA2 /* libplatform-export.h in Headers */, F1F30E762B58FC74006A62C0 /* URLSearchParamsImpl.h in Headers */, AA8C47B12E27114300649BF5 /* ModuleInternalCallbacks.h in Headers */, + B0E1A0032F0A000100000001 /* ModuleUrl.h in Headers */, C2DDEBA7229EAC8300345BFE /* ClassBuilder.h in Headers */, 6573B9ED291FE5B700B0ED7C /* JSIRuntime.h in Headers */, AA5DBFD42EC191F8008D12F9 /* HttpLoader.h in Headers */, @@ -2484,6 +2491,7 @@ 4A5C201A2E2B000100000007 /* RuntimeBuiltins.cpp in Sources */, C2A5F86A2359AEB600074AFA /* ExtVector.cpp in Sources */, AA8C47B22E27114300649BF5 /* ModuleInternalCallbacks.mm in Sources */, + B0E1A0042F0A000100000001 /* ModuleUrl.cpp in Sources */, C2DDEBAF229EAC8300345BFE /* ObjectManager.mm in Sources */, 1DE238EF3BDD0EF221E13C44 /* WrapperLifetime.mm in Sources */, 2A9D21FFAFE7419B7E69B585 /* WrapperLifetimeCanary.mm in Sources */, From ed556e1c621b7f3f5ab1423a1484f90564dcfde8 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Thu, 26 Nov 2026 19:01:13 -0300 Subject: [PATCH 03/13] fix(runtime): spell every absolute http(s) module URL with the URL parser Every route by which an absolute http(s) URL enters the loader now classifies and spells it with NormalizeHttpModuleUrl: the registry key (CanonicalizeHttpUrlKey and CanonicalizeRegistryKey, hence invalidateModules, import.meta.url and getLoadedModuleUrls), a specifier or import-map target from any importer, a dynamic import()'s query handling and HTTP branch, the graph-walk root, the synchronous fallback fetch, LoadESModule/RunModule roots and the require() URL guard. The fetched URL and the registry key derive from the same string. From a file module, HTTP://h/x and http:/h/x are now http URLs as they already were from an HTTP module, dot segments resolve before the fetch, and characters the parser percent-encodes are encoded in the key. The authority keeps its written spelling. An HTTP-prefixed string the parser rejects stays an HTTP URL in its raw spelling. --- NativeScript/runtime/HttpLoader.mm | 5 +- NativeScript/runtime/ModuleInternal.mm | 40 ++++------ .../runtime/ModuleInternalCallbacks.mm | 28 ++++--- TestRunner/app/tests/HttpEsmLoaderTests.js | 76 +++++++++++++++++++ 4 files changed, 110 insertions(+), 39 deletions(-) diff --git a/NativeScript/runtime/HttpLoader.mm b/NativeScript/runtime/HttpLoader.mm index 533da2a9..150e22dd 100644 --- a/NativeScript/runtime/HttpLoader.mm +++ b/NativeScript/runtime/HttpLoader.mm @@ -12,6 +12,7 @@ #include "Helpers.h" #include "ModuleInternal.h" #include "ModuleInternalCallbacks.h" +#include "ModuleUrl.h" #include "Runtime.h" #include "RuntimeConfig.h" #include "robin_hood.h" @@ -156,9 +157,11 @@ bool IsRemoteUrlAllowed(const std::string& url) { if (StartsWith(normalizedUrl, "file://http:/") || StartsWith(normalizedUrl, "file://https:/")) { normalizedUrl = RepairCollapsedUrlScheme(normalizedUrl.substr(strlen("file://"))); } - if (!(StartsWith(normalizedUrl, "http://") || StartsWith(normalizedUrl, "https://"))) { + const std::string httpUrl = NormalizeHttpModuleUrl(normalizedUrl); + if (httpUrl.empty()) { return normalizedUrl; } + normalizedUrl = httpUrl; // Drop fragment entirely size_t hashPos = normalizedUrl.find('#'); std::string noHash = diff --git a/NativeScript/runtime/ModuleInternal.mm b/NativeScript/runtime/ModuleInternal.mm index bf006564..ec0365a8 100644 --- a/NativeScript/runtime/ModuleInternal.mm +++ b/NativeScript/runtime/ModuleInternal.mm @@ -11,6 +11,7 @@ #include "Helpers.h" #include "HttpLoader.h" #include "ModuleInternalCallbacks.h" // for ResolveModuleCallback +#include "ModuleUrl.h" #include "NativeScriptException.h" #include "NsBuiltinModules.h" #include "Runtime.h" @@ -80,33 +81,20 @@ static inline bool StartsWith(const std::string& value, const char* prefix) { return value.size() >= n && value.compare(0, n, prefix) == 0; } -static std::string NormalizeHttpModuleUrl(const std::string& path) { - if (path.empty()) { - return path; - } - - std::string normalized = path; - if (StartsWith(normalized, "file://http://") || StartsWith(normalized, "file://https://")) { - normalized = normalized.substr(strlen("file://")); +// `path` as an http(s) module URL, or empty when it names none. +static std::string HttpModuleUrl(const std::string& path) { + if (StartsWith(path, "file://http://") || StartsWith(path, "file://https://")) { + return NormalizeHttpModuleUrl(path.substr(strlen("file://"))); } - - if (normalized.rfind("http:/", 0) == 0 && normalized.rfind("http://", 0) != 0) { - normalized.insert(5, "/"); - } else if (normalized.rfind("https:/", 0) == 0 && normalized.rfind("https://", 0) != 0) { - normalized.insert(6, "/"); - } - - return normalized; + return NormalizeHttpModuleUrl(path); } -static bool IsHttpModulePath(const std::string& path) { - std::string normalized = NormalizeHttpModuleUrl(path); - return StartsWith(normalized, "http://") || StartsWith(normalized, "https://"); -} +static bool IsHttpModulePath(const std::string& path) { return !HttpModuleUrl(path).empty(); } static std::string CanonicalizeModulePath(const std::string& path) { - if (IsHttpModulePath(path)) { - return CanonicalizeHttpUrlKey(NormalizeHttpModuleUrl(path)); + const std::string url = HttpModuleUrl(path); + if (!url.empty()) { + return CanonicalizeHttpUrlKey(url); } return NormalizePath(path); @@ -250,7 +238,7 @@ static bool IsHttpModulePath(const std::string& path) { if (IsESModule(path) || isHttpModule) { Local moduleNamespace; if (isHttpModule) { - TNS_DEBUG(Esm, "run-module http-esm begin %s", NormalizeHttpModuleUrl(path).c_str()); + TNS_DEBUG(Esm, "run-module http-esm begin %s", HttpModuleUrl(path).c_str()); } try { // The entry runs before this thread's event loop does, so its graph can @@ -277,7 +265,7 @@ throw NativeScriptException( "console for the matching [esm][evaluate][promise-timeout] entry."); } if (isHttpModule) { - TNS_DEBUG(Esm, "run-module http-esm ok %s", NormalizeHttpModuleUrl(path).c_str()); + TNS_DEBUG(Esm, "run-module http-esm ok %s", HttpModuleUrl(path).c_str()); } return; } @@ -534,7 +522,7 @@ throw NativeScriptException( try { // Guard: URL-based modules must be loaded via dynamic import() in dev HTTP ESM mode. moduleName = tns::ToString(isolate, info[0]); - if (moduleName.rfind("http://", 0) == 0 || moduleName.rfind("https://", 0) == 0) { + if (!NormalizeHttpModuleUrl(moduleName).empty()) { std::string msg = std::string("NativeScript: require() of URL module is not supported: ") + moduleName + ". Use dynamic import() instead."; throw NativeScriptException(msg.c_str()); @@ -1491,7 +1479,7 @@ throw NativeScriptException("Module evaluation interrupted by isolate terminatio const ModuleEvaluationOptions& options) { bool isHttpModule = IsHttpModulePath(path); std::string canonicalPath = CanonicalizeModulePath(path); - std::string requestPath = isHttpModule ? NormalizeHttpModuleUrl(path) : canonicalPath; + std::string requestPath = isHttpModule ? HttpModuleUrl(path) : canonicalPath; auto context = isolate->GetCurrentContext(); auto* registryPtr = ModuleRegistryFor(isolate); if (registryPtr == nullptr) { diff --git a/NativeScript/runtime/ModuleInternalCallbacks.mm b/NativeScript/runtime/ModuleInternalCallbacks.mm index ebf21583..d7a575e1 100644 --- a/NativeScript/runtime/ModuleInternalCallbacks.mm +++ b/NativeScript/runtime/ModuleInternalCallbacks.mm @@ -779,7 +779,7 @@ static bool ShouldTraceRegistryKey(const std::string& rawKey, const std::string& const char* classification = "path"; bool traceEvenWithoutChange = false; - if (IsHttpRegistryKey(key) || StartsWith(key, "file://http://") || + if (!NormalizeHttpModuleUrl(key).empty() || StartsWith(key, "file://http://") || StartsWith(key, "file://https://")) { registryKey = CanonicalizeHttpUrlKey(key); classification = "http"; @@ -815,12 +815,14 @@ static bool ShouldTraceRegistryKey(const std::string& rawKey, const std::string& v8::MaybeLocal LoadHttpModuleForUrl(v8::Isolate* isolate, v8::Local context, - const std::string& requestedUrl) { + const std::string& requestedUrlArg) { auto* moduleState = ModuleLoaderStateFor(isolate); if (moduleState == nullptr) { return v8::MaybeLocal(); } auto& registry = moduleState->registry; + const std::string normalizedUrl = NormalizeHttpModuleUrl(requestedUrlArg); + const std::string& requestedUrl = normalizedUrl.empty() ? requestedUrlArg : normalizedUrl; const std::string registryKey = CanonicalizeHttpUrlKey(requestedUrl); TNS_DEBUG(Esm, "[http-esm][load][begin] request=%s key=%s", requestedUrl.c_str(), @@ -1722,9 +1724,10 @@ static ModuleResolution ResolveSpecifierToPath( } } - if (IsHttpRegistryKey(spec)) { + const std::string httpUrl = NormalizeHttpModuleUrl(spec); + if (!httpUrl.empty()) { result.kind = ModuleResolution::Kind::kHttp; - result.url = spec; + result.url = httpUrl; return result; } @@ -2207,9 +2210,10 @@ static void AsyncGraphEnqueue(const std::shared_ptr& load, static ModuleResolution ResolutionForRoot(const std::string& root) { ModuleResolution resolution; resolution.specifier = root; - if (IsHttpRegistryKey(root)) { + const std::string httpUrl = NormalizeHttpModuleUrl(root); + if (!httpUrl.empty()) { resolution.kind = ModuleResolution::Kind::kHttp; - resolution.url = root; + resolution.url = httpUrl; } else if (IsRegularFile(root)) { resolution.kind = ModuleResolution::Kind::kFile; resolution.path = root; @@ -3071,7 +3075,7 @@ static void FinishHttpDynamicImport(v8::Isolate* isolate, v8::Local // app path the registry keys by, or no scope would match it. const std::string resourceName(*resourceUtf8); const std::string resourceUrl = RepairCollapsedUrlScheme(resourceName); - if (ParseModuleUrl(resourceUrl, std::string()).http) { + if (!NormalizeHttpModuleUrl(resourceUrl).empty()) { dynamicReferrerKey = CanonicalizeRegistryKey(resourceUrl); } else { const ModuleResolution referrer = @@ -3091,7 +3095,7 @@ static void FinishHttpDynamicImport(v8::Isolate* isolate, v8::Local // A file importer's query/fragment never names part of a file, so it is // dropped up front; an absolute http(s) specifier keeps it as identity. For // an HTTP importer the seam resolves the specifier as a URL, query included. - const bool isHttpLike = IsHttpRegistryKey(normalizedSpec); + const bool isHttpLike = !NormalizeHttpModuleUrl(normalizedSpec).empty(); if (!isHttpLike && !importerIsHttp) { size_t qpos = normalizedSpec.find_first_of("?#"); if (qpos != std::string::npos) { @@ -3121,9 +3125,9 @@ static void FinishHttpDynamicImport(v8::Isolate* isolate, v8::Local TNS_DEBUG(Esm, "[dyn-import][import-map] rewrite: %s -> %s", rawSpec.c_str(), normalizedSpec.c_str()); } - // An HTTP importer's relative, root-relative and scheme-relative imports - // continue as the absolute URL the seam resolved, through the HTTP path. - if (importerIsHttp && dynamicResolution.kind == ModuleResolution::Kind::kHttp && + // Whatever resolves to an http(s) URL continues as the URL the resolver + // spelled, through the HTTP path. + if (dynamicResolution.kind == ModuleResolution::Kind::kHttp && dynamicResolution.url != normalizedSpec) { normalizedSpec = dynamicResolution.url; specifier = tns::ToV8String(isolate, normalizedSpec.c_str()); @@ -3478,7 +3482,7 @@ static void FinishHttpDynamicImport(v8::Isolate* isolate, v8::Local // If spec is an HTTP(S) URL, try HTTP fetch+compile directly // Security: HttpFetchModule gates remote module access centrally. - if (!normalizedSpec.empty() && IsHttpRegistryKey(normalizedSpec)) { + if (dynamicResolution.kind == ModuleResolution::Kind::kHttp) { TNS_DEBUG(Esm, "[dyn-import][http-loader] trying URL %s", normalizedSpec.c_str()); std::string key = CanonicalizeHttpUrlKey(normalizedSpec); // Volatile pattern check: if the URL matches any configured volatile diff --git a/TestRunner/app/tests/HttpEsmLoaderTests.js b/TestRunner/app/tests/HttpEsmLoaderTests.js index f957a6f1..97e79817 100644 --- a/TestRunner/app/tests/HttpEsmLoaderTests.js +++ b/TestRunner/app/tests/HttpEsmLoaderTests.js @@ -2296,6 +2296,68 @@ describe("HTTP ESM Loader", function() { }); }); }); + + describe("absolute http(s) URLs from a file module", function () { + var nsModule = require("ns:module"); + + afterEach(function () { + nsModule.configureLoader({ importMap: { imports: {} } }); + }); + + it("are spelled by the URL parser, keeping the authority as written", function (done) { + var origin = getHostOrigin(); + if (!origin) { + pending("REPORT_BASEURL not set; skipping host HTTP tests"); + done(); + return; + } + var hostport = origin.replace(/^http:\/\//, ""); + var base = origin + "/esm/resolve/file-abs"; + nsModule.configureLoader({ + importMap: { imports: { "ns-file-abs-mapped": base + "/mapped/../mapped.mjs" } }, + }); + Promise.all([ + import("HTTP://" + hostport + "/esm/resolve/file-abs/upper.mjs"), + import("http:/" + hostport + "/esm/resolve/file-abs/collapsed.mjs?k=1"), + import(base + "/sub/../dots.mjs"), + import(base + "/mödule.mjs"), + import("ns-file-abs-mapped"), + ]).then(function (mods) { + expect(mods.map(function (m) { return m.url; })).toEqual([ + base + "/upper.mjs", + base + "/collapsed.mjs?k=1", + base + "/dots.mjs", + base + "/m%C3%B6dule.mjs", + base + "/mapped.mjs", + ]); + expect(mods.map(function (m) { return m.path + "?" + m.query; })).toEqual([ + "/esm/resolve/file-abs/upper.mjs?", + "/esm/resolve/file-abs/collapsed.mjs?k=1", + "/esm/resolve/file-abs/dots.mjs?", + "/esm/resolve/file-abs/m%C3%B6dule.mjs?", + "/esm/resolve/file-abs/mapped.mjs?", + ]); + nsModule.invalidateModules(["HTTP://" + hostport + "/esm/resolve/file-abs/upper.mjs"]); + expect(nsModule.getLoadedModuleUrls()).not.toContain(base + "/upper.mjs"); + done(); + }).catch(function (error) { + expect("rejected: " + formatError(error)).toBe("resolved"); + done(); + }); + }); + + it("are refused by require() whatever their scheme's case", function () { + ["http://h/x.js", "HTTP://h/x.js"].forEach(function (url) { + var message = ""; + try { + require(url); + } catch (e) { + message = String((e && e.message) || e); + } + expect(message).toContain("require() of URL module is not supported: " + url); + }); + }); + }); }); // Focused, deterministic coverage for the native HTTP canonical-key function. @@ -2445,6 +2507,20 @@ describe("HTTP canonical key (ns:module canonicalizeHttpUrlKey)", function () { "https://cdn.example.com/lib.js?token=abc"); }); + it("spells a URL the way the URL parser does, authority aside", function () { + checkKey("HTTP://h/x", "http://h/x"); + checkKey("http:h/x", "http://h/x"); + checkKey(" http://h/x", "http://h/x"); + checkKey("http://h", "http://h/"); + checkKey("http://h?x", "http://h/?x"); + checkKey("http://h/a/../b.js", "http://h/b.js"); + checkKey("http://h/%2e%2e/b.js", "http://h/b.js"); + checkKey("http://h\\x\\y.js", "http://h/x/y.js"); + checkKey("http://h/mödule.js", "http://h/m%C3%B6dule.js"); + checkKey("http://h/a b.js?q=a b", "http://h/a%20b.js?q=a%20b"); + checkKey("http://H:80/x?", "http://H:80/x?"); + }); + it("keeps the URLs dev tooling emits as written", function () { TOOLING_URLS.forEach(function (row) { checkKey(row[0], row[1]); From 28850ec1399442cf2057e3cc18b9585e689252a4 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Thu, 26 Nov 2026 19:07:21 -0300 Subject: [PATCH 04/13] fix(runtime): drop the legacy module URL forms MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Nothing in the runtime feeds the loader a file://http(s):// wrapper, a collapsed http:/ scheme or a URL embedded in a joined path any more, so the unwraps in CanonicalizeHttpUrlKey, CanonicalizeRegistryKey and ModuleInternal, HttpUrlEmbeddedInPath and RepairCollapsedUrlScheme go. A collapsed http:/host still keys as http://host because the URL parser reads it that way; a wrapped file://http://… is a file: URL that names no file, so import() of it rejects without fetching. A dynamic import() from an HTTP module that the resolver left unresolved now rejects instead of re-resolving in the tail, which path-joined an http referrer the URL parser rejects (an IPv6 zone id) into a collapsed URL. An http(s) worker script is labelled with its own URL in the inspector. The unused adjustedRegistryKey is gone. --- NativeScript/runtime/HttpLoader.h | 8 --- NativeScript/runtime/HttpLoader.mm | 34 ++------- NativeScript/runtime/ModuleInternal.mm | 23 ++---- .../runtime/ModuleInternalCallbacks.mm | 70 ++++-------------- NativeScript/runtime/WorkerWrapper.mm | 5 +- TestRunner/app/tests/HttpEsmLoaderTests.js | 71 +++++++++++++++---- 6 files changed, 86 insertions(+), 125 deletions(-) diff --git a/NativeScript/runtime/HttpLoader.h b/NativeScript/runtime/HttpLoader.h index 7c9a9d5f..c78ad5dd 100644 --- a/NativeScript/runtime/HttpLoader.h +++ b/NativeScript/runtime/HttpLoader.h @@ -58,14 +58,6 @@ struct CanonicalizationConfig { // module under exactly one URL and never varies it for freshness. std::string CanonicalizeHttpUrlKey(const std::string& url); -// Repairs `http:/host` (one slash) back to `http://host`. Upstream path joins -// collapse the double slash, and every key derivation has to undo it BEFORE it -// tests the scheme — otherwise the collapsed form fails the test, is passed -// through verbatim, and the same module ends up with two registry identities: -// one from the resolver (which repairs) and one from whatever came in through -// invalidateModules or a cache-bust mark (which did not). -std::string RepairCollapsedUrlScheme(const std::string& url); - // What a module response turned out to be. Decided once, by the shared // classifier, for whichever transport produced the response. enum class ModuleResponseKind { diff --git a/NativeScript/runtime/HttpLoader.mm b/NativeScript/runtime/HttpLoader.mm index 150e22dd..1c134821 100644 --- a/NativeScript/runtime/HttpLoader.mm +++ b/NativeScript/runtime/HttpLoader.mm @@ -128,40 +128,14 @@ bool IsRemoteUrlAllowed(const std::string& url) { // URLs touched before the client configures anything (the local trampoline's // clean `/ns/core/*` imports) carry no query, so they canonicalize identically // under any vocabulary. -std::string RepairCollapsedUrlScheme(const std::string& url) { - if (StartsWith(url, "http:/") && !StartsWith(url, "http://")) { - std::string repaired = url; - repaired.insert(5, "/"); - return repaired; - } - if (StartsWith(url, "https:/") && !StartsWith(url, "https://")) { - std::string repaired = url; - repaired.insert(6, "/"); - return repaired; - } - return url; -} - std::string CanonicalizeHttpUrlKey(const std::string& url) { // Per-isolate vocabulary, so this runs on the isolate's own thread. Fetch // threads never reach here — they carry keys computed for them. const CanonicalizationConfig* canonConfig = CanonicalizationConfigForCurrentIsolate(); - // Some loaders wrap HTTP module URLs as file://http(s)://... - // Repaired before any scheme test, so a collapsed `http:/host` keys the same - // as the URL it means rather than passing through untouched. - std::string normalizedUrl = RepairCollapsedUrlScheme(url); - // The wrapper is tested on the one-slash forms as well: a path join can - // collapse the scheme INSIDE the wrapper (`file://http:/host/x`), which - // matches neither the two-slash unwrap nor the repair above (whose prefix is - // `file://`, not `http:/`) and would otherwise key as its own identity. - if (StartsWith(normalizedUrl, "file://http:/") || StartsWith(normalizedUrl, "file://https:/")) { - normalizedUrl = RepairCollapsedUrlScheme(normalizedUrl.substr(strlen("file://"))); - } - const std::string httpUrl = NormalizeHttpModuleUrl(normalizedUrl); - if (httpUrl.empty()) { - return normalizedUrl; - } - normalizedUrl = httpUrl; + const std::string normalizedUrl = NormalizeHttpModuleUrl(url); + if (normalizedUrl.empty()) { + return url; + } // Drop fragment entirely size_t hashPos = normalizedUrl.find('#'); std::string noHash = diff --git a/NativeScript/runtime/ModuleInternal.mm b/NativeScript/runtime/ModuleInternal.mm index ec0365a8..a355722f 100644 --- a/NativeScript/runtime/ModuleInternal.mm +++ b/NativeScript/runtime/ModuleInternal.mm @@ -76,23 +76,12 @@ static ModuleEvaluationOptions RequireEvaluationOptions(ModuleEvaluationPolicy p return options; } -static inline bool StartsWith(const std::string& value, const char* prefix) { - size_t n = strlen(prefix); - return value.size() >= n && value.compare(0, n, prefix) == 0; +static bool IsHttpModulePath(const std::string& path) { + return !NormalizeHttpModuleUrl(path).empty(); } -// `path` as an http(s) module URL, or empty when it names none. -static std::string HttpModuleUrl(const std::string& path) { - if (StartsWith(path, "file://http://") || StartsWith(path, "file://https://")) { - return NormalizeHttpModuleUrl(path.substr(strlen("file://"))); - } - return NormalizeHttpModuleUrl(path); -} - -static bool IsHttpModulePath(const std::string& path) { return !HttpModuleUrl(path).empty(); } - static std::string CanonicalizeModulePath(const std::string& path) { - const std::string url = HttpModuleUrl(path); + const std::string url = NormalizeHttpModuleUrl(path); if (!url.empty()) { return CanonicalizeHttpUrlKey(url); } @@ -238,7 +227,7 @@ static inline bool StartsWith(const std::string& value, const char* prefix) { if (IsESModule(path) || isHttpModule) { Local moduleNamespace; if (isHttpModule) { - TNS_DEBUG(Esm, "run-module http-esm begin %s", HttpModuleUrl(path).c_str()); + TNS_DEBUG(Esm, "run-module http-esm begin %s", NormalizeHttpModuleUrl(path).c_str()); } try { // The entry runs before this thread's event loop does, so its graph can @@ -265,7 +254,7 @@ throw NativeScriptException( "console for the matching [esm][evaluate][promise-timeout] entry."); } if (isHttpModule) { - TNS_DEBUG(Esm, "run-module http-esm ok %s", HttpModuleUrl(path).c_str()); + TNS_DEBUG(Esm, "run-module http-esm ok %s", NormalizeHttpModuleUrl(path).c_str()); } return; } @@ -1479,7 +1468,7 @@ throw NativeScriptException("Module evaluation interrupted by isolate terminatio const ModuleEvaluationOptions& options) { bool isHttpModule = IsHttpModulePath(path); std::string canonicalPath = CanonicalizeModulePath(path); - std::string requestPath = isHttpModule ? HttpModuleUrl(path) : canonicalPath; + std::string requestPath = isHttpModule ? NormalizeHttpModuleUrl(path) : canonicalPath; auto context = isolate->GetCurrentContext(); auto* registryPtr = ModuleRegistryFor(isolate); if (registryPtr == nullptr) { diff --git a/NativeScript/runtime/ModuleInternalCallbacks.mm b/NativeScript/runtime/ModuleInternalCallbacks.mm index d7a575e1..4993ed53 100644 --- a/NativeScript/runtime/ModuleInternalCallbacks.mm +++ b/NativeScript/runtime/ModuleInternalCallbacks.mm @@ -765,22 +765,19 @@ static bool ShouldTraceRegistryKey(const std::string& rawKey, const std::string& return StartsWith(registryKey, "node:") || StartsWith(registryKey, "blob:"); } -static std::string CanonicalizeRegistryKey(const std::string& rawKey) { - if (rawKey.empty()) { - return rawKey; +static std::string CanonicalizeRegistryKey(const std::string& key) { + if (key.empty()) { + return key; } - // Before any scheme test: a collapsed `http:/host` would otherwise fail the - // http tests below, fall through as a custom scheme, and give the module a - // second identity that never matches the resolver's. - const std::string key = RepairCollapsedUrlScheme(rawKey); - std::string registryKey; const char* classification = "path"; bool traceEvenWithoutChange = false; - if (!NormalizeHttpModuleUrl(key).empty() || StartsWith(key, "file://http://") || - StartsWith(key, "file://https://")) { + // Before any other scheme test: an http(s) URL in a spelling other than the + // key's (`HTTP://`, `http:/host`) must not fall through as a custom scheme + // and give the module a second identity. + if (!NormalizeHttpModuleUrl(key).empty()) { registryKey = CanonicalizeHttpUrlKey(key); classification = "http"; } else if (StartsWith(key, "file://")) { @@ -1592,28 +1589,6 @@ static bool IsRegularFile(const std::string& p) { return (st.st_mode & S_IFMT) == S_IFREG; } -// Rebuild an HTTP URL a path join swallowed ('/app/http:/host/x' → -// 'http://host/x'), or empty when the path embeds none. -static std::string HttpUrlEmbeddedInPath(const std::string& p) { - size_t pos1 = p.find("/http:/"); - size_t pos2 = p.find("/https:/"); - size_t pos = std::min(pos1 == std::string::npos ? SIZE_MAX : pos1, - pos2 == std::string::npos ? SIZE_MAX : pos2); - if (pos == SIZE_MAX) { - return ""; - } - std::string tail = p.substr(pos + 1); - if (StartsWith(tail, "http:/") && !StartsWith(tail, "http://")) { - tail.insert(5, "/"); - } else if (StartsWith(tail, "https:/") && !StartsWith(tail, "https://")) { - tail.insert(6, "/"); - } - if (!IsHttpRegistryKey(tail)) { - return ""; - } - return tail; -} - enum class ImportMapLookup { kApply, kSkip, // the specifier is an existing module's origin, which the map never rewrites @@ -1636,10 +1611,7 @@ static ModuleResolution ResolveSpecifierToPath( return result; } - // Repair 'http:/host' (single slash) left by upstream path joins, so the URL - // takes the HTTP path instead of becoming '/app/http:/host'. Shared with the - // key derivations, so the resolver and the registry agree on one identity. - std::string spec = RepairCollapsedUrlScheme(rawSpec); + std::string spec = rawSpec; TNS_DEBUG(Esm, "[resolver][spec] %s", spec.c_str()); @@ -1850,14 +1822,6 @@ static ModuleResolution ResolveSpecifierToPath( for (const std::string& baseCandidate : candidateBases) { absPath = NormalizePath(baseCandidate); - std::string embedded = HttpUrlEmbeddedInPath(absPath); - if (!embedded.empty()) { - TNS_DEBUG(Esm, "[resolver][http-embedded] %s -> %s", absPath.c_str(), embedded.c_str()); - result.kind = ModuleResolution::Kind::kHttp; - result.url = embedded; - return result; - } - bool existsNow = IsRegularFile(absPath); TNS_DEBUG(Esm, "[resolver] %s -> %s", absPath.c_str(), existsNow ? "file" : "missing"); @@ -3074,9 +3038,8 @@ static void FinishHttpDynamicImport(v8::Isolate* isolate, v8::Local // map. A local origin (`file:///app/…`) still has to become the absolute // app path the registry keys by, or no scope would match it. const std::string resourceName(*resourceUtf8); - const std::string resourceUrl = RepairCollapsedUrlScheme(resourceName); - if (!NormalizeHttpModuleUrl(resourceUrl).empty()) { - dynamicReferrerKey = CanonicalizeRegistryKey(resourceUrl); + if (!NormalizeHttpModuleUrl(resourceName).empty()) { + dynamicReferrerKey = CanonicalizeRegistryKey(resourceName); } else { const ModuleResolution referrer = ResolveSpecifierToPath(resourceName, std::string(), ImportMapLookup::kSkip); @@ -3669,12 +3632,12 @@ static void FinishHttpDynamicImport(v8::Isolate* isolate, v8::Local return scope.Escape(resolver->GetPromise()); } - // The tail below re-resolves with no referrer, which would let an HTTP - // importer's unmapped other-scheme specifier ('data:', 'file:/x') reach - // '/' on disk. Only explicit file:// URLs and import-map - // targets may continue into it. + // The tail below re-resolves with no referrer and joins relative + // specifiers onto the referrer as a path, which would let an HTTP + // importer's specifier reach '/' on disk or path-join an http + // URL. Only explicit file:// URLs may continue into it. if (importerIsHttp && dynamicResolution.kind == ModuleResolution::Kind::kUnresolved && - normalizedSpec == rawSpec && !StartsWith(normalizedSpec, "file://")) { + !StartsWith(normalizedSpec, "file://")) { resolver ->Reject(context, v8::Exception::Error(tns::ToV8String( isolate, UnresolvedModuleMessage(dynamicResolution)))) @@ -3745,9 +3708,6 @@ static void FinishHttpDynamicImport(v8::Isolate* isolate, v8::Local TNS_DEBUG(Esm, "[dyn-import][resolver-call] raw=%s normalized=%s adjusted=%s", rawSpec.c_str(), normalizedSpec.c_str(), cAdj); } - v8::String::Utf8Value adjustedSpecUtf8(isolate, adjustedSpecifier); - std::string adjustedRegistryKey = - *adjustedSpecUtf8 ? CanonicalizeRegistryKey(*adjustedSpecUtf8) : std::string(); if (maybeModule.IsEmpty()) { if (resolveTc.HasCaught()) { // Reject the promise with the thrown exception so callers don't hang diff --git a/NativeScript/runtime/WorkerWrapper.mm b/NativeScript/runtime/WorkerWrapper.mm index b19b0b7c..419687fc 100644 --- a/NativeScript/runtime/WorkerWrapper.mm +++ b/NativeScript/runtime/WorkerWrapper.mm @@ -4,6 +4,7 @@ #include "DataWrapper.h" #include "ErrorEvents.h" #include "Helpers.h" +#include "ModuleUrl.h" #include "ObjectManager.h" #include "Runtime.h" #include "RuntimeConfig.h" @@ -484,7 +485,9 @@ static void PostThreadEndedNotification(Isolate* mainIsolate, std::weak_ptrworkerId_, isolate, CFRunLoopGetCurrent(), url); diff --git a/TestRunner/app/tests/HttpEsmLoaderTests.js b/TestRunner/app/tests/HttpEsmLoaderTests.js index 97e79817..01087b81 100644 --- a/TestRunner/app/tests/HttpEsmLoaderTests.js +++ b/TestRunner/app/tests/HttpEsmLoaderTests.js @@ -1934,6 +1934,32 @@ describe("HTTP ESM Loader", function() { }); }); + it("rejects an import() whose import-map target resolves to nothing", function (done) { + var origin = getHostOrigin(); + if (!origin) { + pending("REPORT_BASEURL not set; skipping host HTTP tests"); + done(); + return; + } + nsModule.configureLoader({ + importMap: { + imports: { + "ns-tail-a": "ns-tail-b", + "ns-tail-b": "~/tests/esm/query-map/literal.mjs", + }, + }, + }); + importer(origin, "tail").then(function (mod) { + return rejectionMessage(mod.load("ns-tail-a")); + }).then(function (message) { + expect(message).toContain("Cannot find module 'ns-tail-b'"); + done(); + }).catch(function (error) { + expect("rejected: " + formatError(error)).toBe("resolved"); + done(); + }); + }); + it("keeps the importer's origin as written when the query or fragment is empty", function (done) { var origin = getHostOrigin(); @@ -2346,6 +2372,30 @@ describe("HTTP ESM Loader", function() { }); }); + it("are not unwrapped from a file:// URL", function (done) { + var origin = getHostOrigin(); + if (!origin) { + pending("REPORT_BASEURL not set; skipping host HTTP tests"); + done(); + return; + } + var target = "/esm/resolve/file-abs/wrapped.mjs"; + import("file://" + origin + target).then(function () { + expect("resolved").toBe("rejected"); + }, function (error) { + expect(String((error && error.message) || error)).toContain("Cannot find module"); + }).then(function () { + return import(origin + "/esm/request-stats.json?target=" + + encodeURIComponent(target)); + }).then(function (stats) { + expect(stats.default.count).toBe(0); + done(); + }).catch(function (error) { + expect("rejected: " + formatError(error)).toBe("resolved"); + done(); + }); + }); + it("are refused by require() whatever their scheme's case", function () { ["http://h/x.js", "HTTP://h/x.js"].forEach(function (url) { var message = ""; @@ -2473,26 +2523,19 @@ describe("HTTP canonical key (ns:module canonicalizeHttpUrlKey)", function () { "https://cdn.example.com/lib.js?token=abc"); }); - // Upstream path joins collapse `http://` to `http:/`. Every key - // derivation repairs that before it tests the scheme, so a key that - // arrives collapsed — through invalidateModules or a cache-bust mark — - // lands on the same identity the resolver produces. + // The URL parser reads `http:/host` as `http://host`, so a key that + // arrives collapsed, through invalidateModules say, lands on the same + // identity the resolver produces. it("repairs a collapsed scheme to one identity", function () { checkKey("http:/h/ns/core", "http://h/ns/core"); checkKey("https:/h/ns/core", "https://h/ns/core"); - // Already well-formed keys are untouched by the repair. checkKey("http://h/ns/core", "http://h/ns/core"); }); - // Some loaders hand the URL over wrapped as file://http(s)://…, and a - // path join can collapse the scheme inside that wrapper too. Unwrapping - // and repairing have to compose, or the wrapped-collapsed form becomes - // a third identity for the same module. - it("repairs a collapsed scheme inside a file:// wrapper", function () { - checkKey("file://http:/h/ns/core", "http://h/ns/core"); - checkKey("file://https:/h/ns/core", "https://h/ns/core"); - // The well-formed wrapper still unwraps to the same key. - checkKey("file://http://h/ns/core", "http://h/ns/core"); + it("does not read an http URL inside a file:// URL as an http key", function () { + checkKey("file://http:/h/ns/core", "file://http:/h/ns/core"); + checkKey("file://https:/h/ns/core", "file://https:/h/ns/core"); + checkKey("file://http://h/ns/core", "file://http://h/ns/core"); }); it("treats module identity as literally the URL — no path-tag collapses", function () { From 77d79bb1367155bd83ca7df1d7638563d3be88ec Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Thu, 26 Nov 2026 19:07:28 -0300 Subject: [PATCH 05/13] docs: how the loader spells absolute http(s) module URLs --- docs/ns-builtin-modules.md | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index 35bc4ee9..9949f6bb 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -695,7 +695,13 @@ Inside either section — labelled `imports` or `scope ''`: #### Registry canonicalization -The registry keys modules by a canonical URL. The mechanism — fragment strip, +The registry keys modules by a canonical URL. Before the vocabulary applies, +an absolute http(s) URL is spelled by the WHATWG URL parser with its authority +as written, whichever way it arrives — a specifier from any importer, an +import-map target, or `invalidateModules` — so `HTTP://host/a/../x.js` and +`http:/host/x.js` key as `http://host/x.js`. A `file://http://…` string is not +an http(s) URL: it keys as itself, and `import()` of it fails with +`Cannot find module` without fetching anything. The mechanism — fragment strip, cache-buster param drop, param sort — is the runtime's; the *vocabulary* is server policy, supplied here: From e79bf93d85639fdc6a680178cb75ffdcd8effb5b Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Thu, 26 Nov 2026 19:32:01 -0300 Subject: [PATCH 06/13] fix(runtime): spell remote-module allowlist entries like the URLs they gate The allowlist compares fetched URLs, which the loader now spells with the URL parser (dot segments resolved, characters such as non-ASCII percent-encoded). Each security.remoteModuleAllowlist entry is spelled the same way once, when the allowlist is loaded, with the written authority kept; an entry that is not an http(s) URL stays verbatim. The prefix-and-boundary rule is unchanged. The rule is factored into RemoteUrlMatchesAllowlist, which IsRemoteUrlAllowed applies, and debug builds expose it on ns:module as remoteUrlMatchesAllowlist(url, entries) so it can be tested; release builds omit the member. --- NativeScript/runtime/HttpLoader.h | 12 +++ NativeScript/runtime/HttpLoader.mm | 25 +++-- .../runtime/ModuleInternalCallbacks.h | 2 + .../runtime/ModuleInternalCallbacks.mm | 41 ++++++++ NativeScript/runtime/js/ns-module.js | 6 +- TestRunner/app/tests/HttpEsmLoaderTests.js | 7 +- .../app/tests/RemoteModuleSecurityTests.js | 94 +++++++++++++++++++ docs/ns-builtin-modules.md | 10 +- types/ns-module.d.ts | 11 ++- 9 files changed, 188 insertions(+), 20 deletions(-) diff --git a/NativeScript/runtime/HttpLoader.h b/NativeScript/runtime/HttpLoader.h index c78ad5dd..e257367a 100644 --- a/NativeScript/runtime/HttpLoader.h +++ b/NativeScript/runtime/HttpLoader.h @@ -143,4 +143,16 @@ bool IsRemoteModulesAllowed(); // (or all URLs if the allowlist is empty). bool IsRemoteUrlAllowed(const std::string& url); +// An allowlist entry spelled the way the loader spells the URLs it fetches +// (NormalizeHttpModuleUrl), so path-scoped entries compare against resolved +// paths; an entry that is not an http(s) URL is kept verbatim. Applied once, +// when the allowlist is loaded. +std::string NormalizeRemoteModuleAllowlistEntry(const std::string& entry); + +// The allowlist rule IsRemoteUrlAllowed applies: `url`, as fetched, matches +// one of `entries` (each already normalized) by prefix, the match ending at a +// URL-component boundary. +bool RemoteUrlMatchesAllowlist(const std::string& url, + const std::vector& entries); + } // namespace tns diff --git a/NativeScript/runtime/HttpLoader.mm b/NativeScript/runtime/HttpLoader.mm index 1c134821..c1c82b5d 100644 --- a/NativeScript/runtime/HttpLoader.mm +++ b/NativeScript/runtime/HttpLoader.mm @@ -55,6 +55,20 @@ static bool RemoteUrlMatchesAllowlistEntry(const std::string& url, const std::st return next == '/' || next == '?' || next == '#'; } +std::string NormalizeRemoteModuleAllowlistEntry(const std::string& entry) { + const std::string url = NormalizeHttpModuleUrl(entry); + return url.empty() ? entry : url; +} + +bool RemoteUrlMatchesAllowlist(const std::string& url, const std::vector& entries) { + for (const std::string& entry : entries) { + if (RemoteUrlMatchesAllowlistEntry(url, entry)) { + return true; + } + } + return false; +} + static void InitializeSecurityConfig() { std::call_once(s_securityConfigInitFlag, []() { @autoreleasepool { @@ -77,7 +91,8 @@ static void InitializeSecurityConfig() { if ([item isKindOfClass:[NSString class]]) { NSString* str = (NSString*)item; if (str.length > 0) { - s_remoteModuleAllowlist.push_back(std::string([str UTF8String])); + s_remoteModuleAllowlist.push_back( + NormalizeRemoteModuleAllowlistEntry(std::string([str UTF8String]))); } } } @@ -110,13 +125,7 @@ bool IsRemoteUrlAllowed(const std::string& url) { return true; } - for (const std::string& entry : s_remoteModuleAllowlist) { - if (RemoteUrlMatchesAllowlistEntry(url, entry)) { - return true; - } - } - - return false; + return RemoteUrlMatchesAllowlist(url, s_remoteModuleAllowlist); } // ───────────────────────────────────────────────────────────── diff --git a/NativeScript/runtime/ModuleInternalCallbacks.h b/NativeScript/runtime/ModuleInternalCallbacks.h index f0211dd0..e71421dd 100644 --- a/NativeScript/runtime/ModuleInternalCallbacks.h +++ b/NativeScript/runtime/ModuleInternalCallbacks.h @@ -236,6 +236,8 @@ void SetVolatilePatterns(const std::vector& patterns); // filename/URL and splits the two // exported flavors) // - canonicalizeHttpUrlKey(url) (debug builds only; test diagnostic) +// - remoteUrlMatchesAllowlist(url, entries) +// (debug builds only; test diagnostic) // // Worker teardown across HMR cycles is userland: the dev client intercepts // the global `Worker` constructor and terminates tracked instances diff --git a/NativeScript/runtime/ModuleInternalCallbacks.mm b/NativeScript/runtime/ModuleInternalCallbacks.mm index 4993ed53..a8833b7c 100644 --- a/NativeScript/runtime/ModuleInternalCallbacks.mm +++ b/NativeScript/runtime/ModuleInternalCallbacks.mm @@ -4194,6 +4194,47 @@ bool BuildNsModuleBinding(v8::Local context, v8::Local return false; } } + + // Debug-only diagnostic: the release allowlist rule, which debug builds + // never apply to fetches. `url` is spelled as the loader spells the URL it + // fetches and `entries` as the allowlist is loaded. + auto allowlistCb = [](const v8::FunctionCallbackInfo& info) { + v8::Isolate* iso = info.GetIsolate(); + v8::Local ctx = iso->GetCurrentContext(); + std::vector entries; + bool valid = info.Length() >= 2 && info[0]->IsString() && info[1]->IsArray(); + if (valid) { + v8::Local list = info[1].As(); + for (uint32_t i = 0; valid && i < list->Length(); i++) { + v8::Local item; + if (!list->Get(ctx, i).ToLocal(&item)) { + return; // the element getter threw + } + valid = item->IsString(); + if (valid) { + entries.push_back(NormalizeRemoteModuleAllowlistEntry(tns::ToString(iso, item))); + } + } + } + if (!valid) { + iso->ThrowException(v8::Exception::TypeError(tns::ToV8String( + iso, "remoteUrlMatchesAllowlist expects a URL string and an array of strings"))); + return; + } + const std::string raw = tns::ToString(iso, info[0]); + const std::string url = NormalizeHttpModuleUrl(raw); + info.GetReturnValue().Set(RemoteUrlMatchesAllowlist(url.empty() ? raw : url, entries)); + }; + v8::Local allowlistFn; + if (v8::Function::New(context, allowlistCb).ToLocal(&allowlistFn)) { + allowlistFn->SetName(tns::ToV8String(isolate, "remoteUrlMatchesAllowlist")); + if (!binding + ->CreateDataProperty(context, tns::ToV8String(isolate, "remoteUrlMatchesAllowlist"), + allowlistFn) + .FromMaybe(false)) { + return false; + } + } } return true; diff --git a/NativeScript/runtime/js/ns-module.js b/NativeScript/runtime/js/ns-module.js index 4059a7c1..9d57e30e 100644 --- a/NativeScript/runtime/js/ns-module.js +++ b/NativeScript/runtime/js/ns-module.js @@ -6,7 +6,8 @@ // and freezes the exports. // // Membership varies by build: -// - `canonicalizeHttpUrlKey` exists only in debug builds (test diagnostic). +// - `canonicalizeHttpUrlKey` and `remoteUrlMatchesAllowlist` exist only in +// debug builds (test diagnostics). // Missing members are simply absent — never present-but-throwing — so // feature checks work. @@ -179,5 +180,8 @@ const surface = { if (binding.canonicalizeHttpUrlKey !== undefined) { surface.canonicalizeHttpUrlKey = binding.canonicalizeHttpUrlKey; } +if (binding.remoteUrlMatchesAllowlist !== undefined) { + surface.remoteUrlMatchesAllowlist = binding.remoteUrlMatchesAllowlist; +} module.exports = ObjectFreeze(surface); diff --git a/TestRunner/app/tests/HttpEsmLoaderTests.js b/TestRunner/app/tests/HttpEsmLoaderTests.js index 01087b81..92ead612 100644 --- a/TestRunner/app/tests/HttpEsmLoaderTests.js +++ b/TestRunner/app/tests/HttpEsmLoaderTests.js @@ -1433,14 +1433,15 @@ describe("HTTP ESM Loader", function() { // The export set is public API, declared in types/ns-module.d.ts and // docs/ns-builtin-modules.md — all three must change together. - // `canonicalizeHttpUrlKey` is a debug-only diagnostic (absent from the - // .d.ts and from release builds), so the expected set varies by build. + // `canonicalizeHttpUrlKey` and `remoteUrlMatchesAllowlist` are + // debug-only diagnostics (absent from the .d.ts and from release + // builds), so the expected set varies by build. it("exposes exactly the declared surface", function () { var nsModule = require("ns:module"); var expected = ["configureLoader", "createPumpingRequire", "createRequire", "getLoadedModuleUrls", "invalidateModules"]; if (typeof nsModule.canonicalizeHttpUrlKey === "function") { - expected.push("canonicalizeHttpUrlKey"); + expected.push("canonicalizeHttpUrlKey", "remoteUrlMatchesAllowlist"); } expect(Object.keys(nsModule).sort()).toEqual(expected.sort()); }); diff --git a/TestRunner/app/tests/RemoteModuleSecurityTests.js b/TestRunner/app/tests/RemoteModuleSecurityTests.js index a926ff93..79e51d9f 100644 --- a/TestRunner/app/tests/RemoteModuleSecurityTests.js +++ b/TestRunner/app/tests/RemoteModuleSecurityTests.js @@ -227,6 +227,100 @@ describe("Remote Module Security", function() { }); }); }); + + // The release allowlist rule, through the debug-only diagnostic that runs + // it: debug builds never gate a fetch on it. + describe("Allowlist rule (ns:module remoteUrlMatchesAllowlist)", function() { + function matches(url, entries) { + var fn = require("ns:module").remoteUrlMatchesAllowlist; + if (typeof fn !== "function") { + pending("ns:module.remoteUrlMatchesAllowlist not exposed (release build)"); + return undefined; + } + return fn(url, entries); + } + + function expectRows(entry, rows) { + rows.forEach(function (row) { + var actual = matches(row[0], [entry]); + if (actual === undefined) { + return; + } + expect(entry + " vs " + row[0] + ": " + actual).toBe(entry + " vs " + row[0] + ": " + row[1]); + }); + } + + it("matches a plain entry by prefix at a component boundary", function() { + expectRows("https://cdn.example", [ + ["https://cdn.example/x.js", true], + ["https://cdn.example", true], + ["https://cdn.example.evil/x.js", false], + ["https://cdn.example@evil/x.js", false], + ["https://cdn.example:9999/x.js", false], + ]); + }); + + it("keeps a path-scoped entry from being escaped by dot segments", function() { + expectRows("https://cdn.example/modules/", [ + ["https://cdn.example/modules/x.js", true], + ["https://cdn.example/modules/../../x.js", false], + ["https://cdn.example/modules/%2e%2e/x.js", false], + ["https://cdn.example/other/../modules/x.js", true], + ]); + }); + + it("treats an entry with and without a trailing slash by the boundary rule", function() { + expectRows("https://cdn.example/modules", [ + ["https://cdn.example/modules/x.js", true], + ["https://cdn.example/modules?v=1", true], + ["https://cdn.example/modulesx/y.js", false], + ]); + expectRows("https://cdn.example/modules/", [ + ["https://cdn.example/modules", false], + ["https://cdn.example/modulesx/y.js", false], + ]); + }); + + it("compares the host as written", function() { + expectRows("https://CDN.example/modules/", [ + ["https://CDN.example/modules/x.js", true], + ["https://cdn.example/modules/x.js", false], + ]); + expectRows("HTTPS://cdn.example/modules/", [ + ["https://cdn.example/modules/x.js", true], + ]); + }); + + it("spells an entry's path the way fetched URLs are spelled", function() { + expectRows("https://cdn.example/mödule/", [ + ["https://cdn.example/mödule/x.js", true], + ["https://cdn.example/m%C3%B6dule/x.js", true], + ]); + }); + + it("keeps an entry that is not a parseable http(s) URL verbatim", function() { + expectRows("https://[fe80::1%25en0]/", [ + ["https://[fe80::1%25en0]/x.js", true], + ]); + expectRows("cdn.example/", [ + ["https://cdn.example/x.js", false], + ]); + }); + + it("rejects arguments that are not a URL string and an array of strings", function() { + var fn = require("ns:module").remoteUrlMatchesAllowlist; + if (typeof fn !== "function") { + pending("ns:module.remoteUrlMatchesAllowlist not exposed (release build)"); + return; + } + [[], ["https://h/x.js"], ["https://h/x.js", "https://h/"], [1, []], + ["https://h/x.js", [1]]].forEach(function (args) { + expect(function () { fn.apply(null, args); }) + .toThrowError(TypeError, + "remoteUrlMatchesAllowlist expects a URL string and an array of strings"); + }); + }); + }); }); console.log("Remote Module Security tests loaded"); diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index 9949f6bb..be576ad3 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -622,8 +622,11 @@ works; adding them is a change to this specification first. Debug builds additionally carry `canonicalizeHttpUrlKey(url)`, a pure test diagnostic that takes a string and throws -`canonicalizeHttpUrlKey expects a URL string` otherwise; release builds omit -it. Missing members are simply absent — never +`canonicalizeHttpUrlKey expects a URL string` otherwise, and +`remoteUrlMatchesAllowlist(url, entries)`, which applies the release +`security.remoteModuleAllowlist` rule to `url` against `entries` and throws +`remoteUrlMatchesAllowlist expects a URL string and an array of strings` +otherwise; release builds omit both. Missing members are simply absent — never present-but-throwing — so feature checks work. The module is registered in every build: the security boundary for remote module loading sits at the network layer (`security.allowRemoteModules` in nativescript.config, enforced @@ -657,7 +660,8 @@ A **scope key is matched as a plain prefix of the importing module's canonical registry key** — an absolute `http(s)` URL for a served module, or a canonical absolute path for a file on disk. That key is this runtime's analogue of the web's resolved referrer URL, which is what scope prefixes match in a browser. -End a scope key with `/` to keep it on a directory boundary. Resolution +End a scope key with +`/` to keep it on a directory boundary. Resolution consults the most specific matching scope first (longest prefix wins), then progressively less specific ones, then `imports` — so a scope can override a global mapping for one subtree and fall through to it everywhere else. The diff --git a/types/ns-module.d.ts b/types/ns-module.d.ts index 00f15997..c5efd298 100644 --- a/types/ns-module.d.ts +++ b/types/ns-module.d.ts @@ -158,9 +158,10 @@ declare module "ns:module" { options?: PumpingRequireOptions, ): (specifier: string) => any; - // Debug builds additionally carry `canonicalizeHttpUrlKey(url)`, a pure - // test diagnostic; release builds omit the member entirely. It is - // deliberately not declared here: it is not public API, and declaring it - // unconditionally would misrepresent release builds, where feature checks - // must observe it as absent. + // Debug builds additionally carry `canonicalizeHttpUrlKey(url)` and + // `remoteUrlMatchesAllowlist(url, entries)`, pure test diagnostics; release + // builds omit both members entirely. They are deliberately not declared + // here: they are not public API, and declaring them unconditionally would + // misrepresent release builds, where feature checks must observe them as + // absent. } From 92bf2954f97dc20c94af2479e4a8aa9232807155 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Thu, 26 Nov 2026 19:32:12 -0300 Subject: [PATCH 07/13] docs: an HTTP module's import() follows one import-map entry --- docs/ns-builtin-modules.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index be576ad3..c1b79016 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -996,8 +996,9 @@ CommonJS or ES modules on disk. From a file module, a static `import 'pkg?x'` looks `pkg?x` up in the import map, while `import('pkg?x')` drops the query and looks up `pkg`. An import-map -target should not itself be a key of the map: `import()` may look a target up -a second time. +target should not itself be a key of the map: a file module's `import()` may +look a target up a second time (an HTTP module's follows one entry, as its +static import does). ### The `require()` specifier From 0d282683b948fef534352becd7288cbd7c91bb7a Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Thu, 26 Nov 2026 19:32:26 -0300 Subject: [PATCH 08/13] fix(runtime): spell http(s) import-map scope keys like the referrer keys they match A scope key matches the importing module's registry key by plain prefix, and http(s) registry keys are spelled by the URL parser, so a scope written with dot segments or a non-ASCII segment matched nothing. An http(s) scope key is now spelled the same way when the map is installed, ending in '/' exactly when it was written so; other scope keys (app paths) and imports keys stay as written. --- .../runtime/ModuleInternalCallbacks.mm | 17 ++++++++- TestRunner/app/tests/HttpEsmLoaderTests.js | 35 +++++++++++++++++++ docs/ns-builtin-modules.md | 4 ++- 3 files changed, 54 insertions(+), 2 deletions(-) diff --git a/NativeScript/runtime/ModuleInternalCallbacks.mm b/NativeScript/runtime/ModuleInternalCallbacks.mm index a8833b7c..b53e32ff 100644 --- a/NativeScript/runtime/ModuleInternalCallbacks.mm +++ b/NativeScript/runtime/ModuleInternalCallbacks.mm @@ -937,6 +937,21 @@ static bool ParseImportMapEntries(NSDictionary* source, const std::string& secti return true; } +// A scope key matches referrer registry keys by plain prefix, and an http(s) +// referrer key is spelled by NormalizeHttpModuleUrl, so an http(s) scope key +// is spelled the same way. Whether it ends in '/' stays as written: the parser +// gives a path-less URL the path "/", which would narrow the prefix. +static std::string ImportMapScopePrefix(const std::string& scopeKey) { + std::string prefix = NormalizeHttpModuleUrl(scopeKey); + if (prefix.empty()) { + return scopeKey; + } + if (scopeKey.back() != '/' && prefix.back() == '/') { + prefix.pop_back(); + } + return prefix; +} + // Parse without touching the live map. On any failure `error` explains what is // wrong and `out` is meaningless — the caller keeps whatever it already had. static bool ParseImportMap(const std::string& json, ParsedImportMap* out, std::string* error) { @@ -1009,7 +1024,7 @@ static bool ParseImportMap(const std::string& json, ParsedImportMap* out, std::s error)) { return false; } - out->scopes.emplace_back(scopePrefix, std::move(entries)); + out->scopes.emplace_back(ImportMapScopePrefix(scopePrefix), std::move(entries)); } } } diff --git a/TestRunner/app/tests/HttpEsmLoaderTests.js b/TestRunner/app/tests/HttpEsmLoaderTests.js index 92ead612..6c0bf929 100644 --- a/TestRunner/app/tests/HttpEsmLoaderTests.js +++ b/TestRunner/app/tests/HttpEsmLoaderTests.js @@ -1935,6 +1935,41 @@ describe("HTTP ESM Loader", function() { }); }); + it("matches an http(s) scope the way the URL parser spells it", function (done) { + var origin = getHostOrigin(); + if (!origin) { + pending("REPORT_BASEURL not set; skipping host HTTP tests"); + done(); + return; + } + var base = origin + "/esm/resolve/scope-norm"; + var scopes = {}; + scopes[base + "/x/../dots/"] = { "ns-scope-norm": base + "/target.mjs?k=dots" }; + scopes[base + "/mödir/"] = { "ns-scope-norm": base + "/target.mjs?k=nonascii" }; + // No trailing slash: still a plain prefix, here inside a segment. + scopes[base + "/pla"] = { "ns-scope-norm": base + "/target.mjs?k=plain" }; + scopes[origin] = { "ns-scope-norm-origin": base + "/target.mjs?k=origin" }; + nsModule.configureLoader({ importMap: { imports: {}, scopes: scopes } }); + function load(dir, spec) { + return importer(origin, "scope-norm/" + dir).then(function (mod) { + return mod.load(spec); + }); + } + Promise.all([ + load("dots", "ns-scope-norm"), + load("mödir", "ns-scope-norm"), + load("plain", "ns-scope-norm"), + load("dots", "ns-scope-norm-origin"), + ]).then(function (mods) { + expect(mods.map(function (m) { return m.query; })) + .toEqual(["k=dots", "k=nonascii", "k=plain", "k=origin"]); + done(); + }).catch(function (error) { + expect("rejected: " + formatError(error)).toBe("resolved"); + done(); + }); + }); + it("rejects an import() whose import-map target resolves to nothing", function (done) { var origin = getHostOrigin(); if (!origin) { diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index c1b79016..517223e0 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -660,7 +660,9 @@ A **scope key is matched as a plain prefix of the importing module's canonical registry key** — an absolute `http(s)` URL for a served module, or a canonical absolute path for a file on disk. That key is this runtime's analogue of the web's resolved referrer URL, which is what scope prefixes match in a browser. -End a scope key with +An `http(s)` scope key is spelled the way registry keys are (see +[Registry canonicalization](#registry-canonicalization)) when the map is +installed, ending in `/` exactly when it is written so. End a scope key with `/` to keep it on a directory boundary. Resolution consults the most specific matching scope first (longest prefix wins), then progressively less specific ones, then `imports` — so a scope can override a From 02e939ddc1a3eb1ddc03e1079cc66263a2cbd8c1 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Thu, 26 Nov 2026 19:35:13 -0300 Subject: [PATCH 09/13] perf(runtime): spell each module URL once per key NormalizeHttpModuleUrl rejects a string that cannot be an http(s) URL from its first character instead of attempting a parse, so file paths pay nothing for it. ParseModuleUrl returns the parser's href unchanged when the written authority already matches it, skipping the rebuild and its re-parse. CanonicalizeHttpUrlKey splits into the spelling step and CanonicalizeNormalizedHttpUrlKey, which applies the vocabulary to an already spelled URL. CanonicalizeRegistryKey, the graph walk (enqueue, fetch completion, root), the dynamic-import HTTP branch, LoadESModule and LoadHttpModuleForUrl, whose callers pass resolved URLs, spell a URL at most once. --- NativeScript/runtime/HttpLoader.h | 3 ++ NativeScript/runtime/HttpLoader.mm | 9 +++--- NativeScript/runtime/ModuleInternal.mm | 10 ++++--- .../runtime/ModuleInternalCallbacks.h | 2 ++ .../runtime/ModuleInternalCallbacks.mm | 30 ++++++++++--------- NativeScript/runtime/ModuleUrl.cpp | 24 ++++++++++++--- TestRunner/app/tests/HttpEsmLoaderTests.js | 2 ++ 7 files changed, 54 insertions(+), 26 deletions(-) diff --git a/NativeScript/runtime/HttpLoader.h b/NativeScript/runtime/HttpLoader.h index e257367a..a0fbd7a7 100644 --- a/NativeScript/runtime/HttpLoader.h +++ b/NativeScript/runtime/HttpLoader.h @@ -58,6 +58,9 @@ struct CanonicalizationConfig { // module under exactly one URL and never varies it for freshness. std::string CanonicalizeHttpUrlKey(const std::string& url); +// CanonicalizeHttpUrlKey for a URL already spelled by NormalizeHttpModuleUrl. +std::string CanonicalizeNormalizedHttpUrlKey(const std::string& normalizedUrl); + // What a module response turned out to be. Decided once, by the shared // classifier, for whichever transport produced the response. enum class ModuleResponseKind { diff --git a/NativeScript/runtime/HttpLoader.mm b/NativeScript/runtime/HttpLoader.mm index c1c82b5d..8aa33bb0 100644 --- a/NativeScript/runtime/HttpLoader.mm +++ b/NativeScript/runtime/HttpLoader.mm @@ -138,13 +138,14 @@ bool IsRemoteUrlAllowed(const std::string& url) { // clean `/ns/core/*` imports) carry no query, so they canonicalize identically // under any vocabulary. std::string CanonicalizeHttpUrlKey(const std::string& url) { + const std::string normalizedUrl = NormalizeHttpModuleUrl(url); + return normalizedUrl.empty() ? url : CanonicalizeNormalizedHttpUrlKey(normalizedUrl); +} + +std::string CanonicalizeNormalizedHttpUrlKey(const std::string& normalizedUrl) { // Per-isolate vocabulary, so this runs on the isolate's own thread. Fetch // threads never reach here — they carry keys computed for them. const CanonicalizationConfig* canonConfig = CanonicalizationConfigForCurrentIsolate(); - const std::string normalizedUrl = NormalizeHttpModuleUrl(url); - if (normalizedUrl.empty()) { - return url; - } // Drop fragment entirely size_t hashPos = normalizedUrl.find('#'); std::string noHash = diff --git a/NativeScript/runtime/ModuleInternal.mm b/NativeScript/runtime/ModuleInternal.mm index a355722f..4a1818c5 100644 --- a/NativeScript/runtime/ModuleInternal.mm +++ b/NativeScript/runtime/ModuleInternal.mm @@ -83,7 +83,7 @@ static bool IsHttpModulePath(const std::string& path) { static std::string CanonicalizeModulePath(const std::string& path) { const std::string url = NormalizeHttpModuleUrl(path); if (!url.empty()) { - return CanonicalizeHttpUrlKey(url); + return CanonicalizeNormalizedHttpUrlKey(url); } return NormalizePath(path); @@ -1466,9 +1466,11 @@ throw NativeScriptException("Module evaluation interrupted by isolate terminatio Local ModuleInternal::LoadESModule(Isolate* isolate, const std::string& path, const ModuleEvaluationOptions& options) { - bool isHttpModule = IsHttpModulePath(path); - std::string canonicalPath = CanonicalizeModulePath(path); - std::string requestPath = isHttpModule ? NormalizeHttpModuleUrl(path) : canonicalPath; + const std::string httpUrl = NormalizeHttpModuleUrl(path); + bool isHttpModule = !httpUrl.empty(); + std::string canonicalPath = + isHttpModule ? CanonicalizeNormalizedHttpUrlKey(httpUrl) : NormalizePath(path); + std::string requestPath = isHttpModule ? httpUrl : canonicalPath; auto context = isolate->GetCurrentContext(); auto* registryPtr = ModuleRegistryFor(isolate); if (registryPtr == nullptr) { diff --git a/NativeScript/runtime/ModuleInternalCallbacks.h b/NativeScript/runtime/ModuleInternalCallbacks.h index e71421dd..86bb5e84 100644 --- a/NativeScript/runtime/ModuleInternalCallbacks.h +++ b/NativeScript/runtime/ModuleInternalCallbacks.h @@ -115,6 +115,8 @@ v8::MaybeLocal GetOrCreateRequireFacade( // Authoritative HTTP URL loader for dev-served ESM. This compiles and // registers the module under its canonical URL key without evaluating it. +// `requestedUrl` must be spelled by NormalizeHttpModuleUrl: it is fetched as is +// and its key derives from it without spelling it again. v8::MaybeLocal LoadHttpModuleForUrl( v8::Isolate* isolate, v8::Local context, const std::string& requestedUrl); diff --git a/NativeScript/runtime/ModuleInternalCallbacks.mm b/NativeScript/runtime/ModuleInternalCallbacks.mm index b53e32ff..a828daf3 100644 --- a/NativeScript/runtime/ModuleInternalCallbacks.mm +++ b/NativeScript/runtime/ModuleInternalCallbacks.mm @@ -777,8 +777,9 @@ static bool ShouldTraceRegistryKey(const std::string& rawKey, const std::string& // Before any other scheme test: an http(s) URL in a spelling other than the // key's (`HTTP://`, `http:/host`) must not fall through as a custom scheme // and give the module a second identity. - if (!NormalizeHttpModuleUrl(key).empty()) { - registryKey = CanonicalizeHttpUrlKey(key); + const std::string httpUrl = NormalizeHttpModuleUrl(key); + if (!httpUrl.empty()) { + registryKey = CanonicalizeNormalizedHttpUrlKey(httpUrl); classification = "http"; } else if (StartsWith(key, "file://")) { registryKey = NormalizePath(FileURLToPath(key)); @@ -812,15 +813,13 @@ static bool ShouldTraceRegistryKey(const std::string& rawKey, const std::string& v8::MaybeLocal LoadHttpModuleForUrl(v8::Isolate* isolate, v8::Local context, - const std::string& requestedUrlArg) { + const std::string& requestedUrl) { auto* moduleState = ModuleLoaderStateFor(isolate); if (moduleState == nullptr) { return v8::MaybeLocal(); } auto& registry = moduleState->registry; - const std::string normalizedUrl = NormalizeHttpModuleUrl(requestedUrlArg); - const std::string& requestedUrl = normalizedUrl.empty() ? requestedUrlArg : normalizedUrl; - const std::string registryKey = CanonicalizeHttpUrlKey(requestedUrl); + const std::string registryKey = CanonicalizeNormalizedHttpUrlKey(requestedUrl); TNS_DEBUG(Esm, "[http-esm][load][begin] request=%s key=%s", requestedUrl.c_str(), registryKey.c_str()); @@ -1974,7 +1973,7 @@ static void AsyncGraphOnFetchCompleted(const std::shared_ptr& lo load->pendingFetches--; - const std::string key = CanonicalizeHttpUrlKey(url); + const std::string key = CanonicalizeNormalizedHttpUrlKey(url); const bool isRoot = (key == load->rootKey); if (!load->failed) { @@ -2096,10 +2095,11 @@ static void AsyncGraphEnqueue(const std::shared_ptr& load, const ModuleResolution& resolution) { const bool isHttp = resolution.kind == ModuleResolution::Kind::kHttp; const std::string& target = isHttp ? resolution.url : resolution.path; - // One keying function for both schemes: it dispatches to the HTTP canonical - // key for URLs and to the normalized path otherwise, so the walk registers - // every module under the exact key the resolver will look up. - const std::string key = CanonicalizeRegistryKey(target); + // The keys CanonicalizeRegistryKey gives these targets, so the walk registers + // every module under the exact key the resolver will look up; a resolved + // URL is already spelled, so only its vocabulary is applied. + const std::string key = + isHttp ? CanonicalizeNormalizedHttpUrlKey(target) : CanonicalizeRegistryKey(target); if (!load->visited.insert(key).second) { return; } @@ -2207,10 +2207,13 @@ void StartModuleGraphLoad( double fetchDeadline, std::function context)> onComplete) { + const ModuleResolution rootResolution = ResolutionForRoot(root); auto load = std::make_shared(); load->isolate = isolate; load->context.Reset(isolate, context); - load->rootKey = CanonicalizeRegistryKey(root); + load->rootKey = rootResolution.kind == ModuleResolution::Kind::kHttp + ? CanonicalizeNormalizedHttpUrlKey(rootResolution.url) + : CanonicalizeRegistryKey(root); load->startUs = (uint64_t)(CFAbsoluteTimeGetCurrent() * 1000.0 * 1000.0); load->fetchDeadline = fetchDeadline; load->onComplete = std::move(onComplete); @@ -2220,7 +2223,6 @@ void StartModuleGraphLoad( TNS_DEBUG(Esm, "[graph][start] root=%s key=%s", root.c_str(), load->rootKey.c_str()); - const ModuleResolution rootResolution = ResolutionForRoot(root); if (rootResolution.kind != ModuleResolution::Kind::kUnresolved) { AsyncGraphEnqueue(load, rootResolution); } @@ -3462,7 +3464,7 @@ static void FinishHttpDynamicImport(v8::Isolate* isolate, v8::Local // Security: HttpFetchModule gates remote module access centrally. if (dynamicResolution.kind == ModuleResolution::Kind::kHttp) { TNS_DEBUG(Esm, "[dyn-import][http-loader] trying URL %s", normalizedSpec.c_str()); - std::string key = CanonicalizeHttpUrlKey(normalizedSpec); + std::string key = CanonicalizeNormalizedHttpUrlKey(normalizedSpec); // Volatile pattern check: if the URL matches any configured volatile // pattern, evict the cached module so we always re-fetch. The pattern // list is policy and is supplied exclusively by the dev client via diff --git a/NativeScript/runtime/ModuleUrl.cpp b/NativeScript/runtime/ModuleUrl.cpp index 3742e534..e805ced5 100644 --- a/NativeScript/runtime/ModuleUrl.cpp +++ b/NativeScript/runtime/ModuleUrl.cpp @@ -79,12 +79,18 @@ ModuleUrl ParseModuleUrl(const std::string& input, const std::string& base) { if (authority.empty()) { return result; } + const std::string_view href = url->get_href(); + const size_t authorityStart = url->get_protocol().size() + 2; + const size_t pathnameStart = url->get_components().pathname_start; + if (href.substr(authorityStart, pathnameStart - authorityStart) == + authority) { + return result; + } // Everything after the authority comes from the parser's own href: its // getters drop an empty query's '?' and an empty fragment's '#'. - const std::string_view href = url->get_href(); - const std::string written = - std::string(url->get_protocol()) + "//" + authority + - std::string(href.substr(url->get_components().pathname_start)); + const std::string written = std::string(url->get_protocol()) + "//" + + authority + + std::string(href.substr(pathnameStart)); auto reparsed = ada::parse(written, nullptr); if (reparsed && reparsed->get_href() == href) { result.href = written; @@ -93,6 +99,16 @@ ModuleUrl ParseModuleUrl(const std::string& input, const std::string& base) { } std::string NormalizeHttpModuleUrl(const std::string& input) { + // Fast reject only: the parser drops leading C0 controls and spaces, after + // which an http(s) URL (or an HTTP key) starts with 'h' or 'H'. + size_t first = 0; + while (first < input.size() && + static_cast(input[first]) <= 0x20) { + first++; + } + if (first == input.size() || (input[first] != 'h' && input[first] != 'H')) { + return std::string(); + } const ModuleUrl url = ParseModuleUrl(input, std::string()); if (url.parsed) { return url.http ? url.href : std::string(); diff --git a/TestRunner/app/tests/HttpEsmLoaderTests.js b/TestRunner/app/tests/HttpEsmLoaderTests.js index 6c0bf929..26986cfa 100644 --- a/TestRunner/app/tests/HttpEsmLoaderTests.js +++ b/TestRunner/app/tests/HttpEsmLoaderTests.js @@ -2590,6 +2590,8 @@ describe("HTTP canonical key (ns:module canonicalizeHttpUrlKey)", function () { checkKey("HTTP://h/x", "http://h/x"); checkKey("http:h/x", "http://h/x"); checkKey(" http://h/x", "http://h/x"); + checkKey("\t\n HTTPS://h/x", "https://h/x"); + checkKey("h\tttp://h/x", "http://h/x"); checkKey("http://h", "http://h/"); checkKey("http://h?x", "http://h/?x"); checkKey("http://h/a/../b.js", "http://h/b.js"); From e6b5bf02d8eb4b137277d4748473dd88735b18ea Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Thu, 26 Nov 2026 19:38:50 -0300 Subject: [PATCH 10/13] refactor(runtime): build the URL a module is reported under in one place MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Script origins of classic scripts, file ES modules and JSON modules, import.meta.url and the worker inspector URL each built their own file:// URL from a path. ReportedModuleUrl in ModuleUrl now does it for all of them: an http(s) URL in the loader's spelling, any other string that carries a scheme unchanged, and otherwise file:// plus the path with the base directory removed (file:///app/ when empty). The outputs are unchanged except the worker inspector URL, which for an http(s) script is now the normalized URL and for any other scheme-carrying script is the script string itself rather than a file:// prefix glued onto it. The docs no longer describe the file://http… string, which is not a form the loader accepts. --- NativeScript/runtime/ModuleInternal.mm | 7 +--- .../runtime/ModuleInternalCallbacks.mm | 2 +- NativeScript/runtime/ModuleUrl.cpp | 41 +++++++++++++++++++ NativeScript/runtime/ModuleUrl.h | 12 ++++++ NativeScript/runtime/Runtime.mm | 31 ++------------ NativeScript/runtime/WorkerWrapper.mm | 4 +- docs/ns-builtin-modules.md | 4 +- 7 files changed, 62 insertions(+), 39 deletions(-) diff --git a/NativeScript/runtime/ModuleInternal.mm b/NativeScript/runtime/ModuleInternal.mm index 4a1818c5..f957a3e6 100644 --- a/NativeScript/runtime/ModuleInternal.mm +++ b/NativeScript/runtime/ModuleInternal.mm @@ -963,9 +963,7 @@ throw NativeScriptException("Module evaluation interrupted by isolate terminatio } auto context = isolate->GetCurrentContext(); - // build URL - std::string base = ReplaceAll(canonicalPath, RuntimeConfig.BaseDir, ""); - std::string url = "file://" + base; + const std::string url = ReportedModuleUrl(canonicalPath); // wrap & cache lookup Local sourceText = ModuleInternal::WrapModuleContent(isolate, canonicalPath); @@ -1019,8 +1017,7 @@ ScriptOrigin origin(urlString, throw NativeScriptException("Cannot find module " + canonicalPath); } - std::string base = ReplaceAll(canonicalPath, RuntimeConfig.BaseDir, ""); - std::string url = "file://" + base; + const std::string url = ReportedModuleUrl(canonicalPath); Local sourceText = ModuleInternal::WrapModuleContent(isolate, canonicalPath); auto* cacheData = ModuleInternal::LoadScriptCache(canonicalPath, ScriptCacheKind::kEsModule); diff --git a/NativeScript/runtime/ModuleInternalCallbacks.mm b/NativeScript/runtime/ModuleInternalCallbacks.mm index a828daf3..6dea2915 100644 --- a/NativeScript/runtime/ModuleInternalCallbacks.mm +++ b/NativeScript/runtime/ModuleInternalCallbacks.mm @@ -2738,7 +2738,7 @@ static void RejectAndClearInvalidatedModuleState(v8::Isolate* isolate, const std::string& absPath, const std::string& registryAbsPath) { const std::string jsonText = tns::ReadText(absPath); - const std::string url = "file://" + ReplaceAll(absPath, RuntimeConfig.BaseDir, ""); + const std::string url = ReportedModuleUrl(absPath); return CompileJsonTextAsEsModule(isolate, context, jsonText, registryAbsPath, url); } diff --git a/NativeScript/runtime/ModuleUrl.cpp b/NativeScript/runtime/ModuleUrl.cpp index e805ced5..1f145c2f 100644 --- a/NativeScript/runtime/ModuleUrl.cpp +++ b/NativeScript/runtime/ModuleUrl.cpp @@ -2,6 +2,7 @@ #include +#include "RuntimeConfig.h" #include "ada/ada.h" namespace tns { @@ -116,4 +117,44 @@ std::string NormalizeHttpModuleUrl(const std::string& input) { return IsHttpRegistryKey(input) ? input : std::string(); } +bool HasUrlScheme(const std::string& s) { + const size_t colon = s.find(':'); + if (colon == 0 || colon == std::string::npos) { + return false; + } + const size_t slash = s.find('/'); + if (slash != std::string::npos && slash < colon) { + return false; + } + for (size_t i = 0; i < colon; i++) { + const char c = s[i]; + const bool ok = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || + (c >= '0' && c <= '9') || c == '+' || c == '-' || c == '.'; + if (!ok) { + return false; + } + } + return true; +} + +std::string ReportedModuleUrl(const std::string& keyOrPath) { + if (keyOrPath.empty()) { + return "file:///app/"; + } + if (HasUrlScheme(keyOrPath)) { + const std::string http = NormalizeHttpModuleUrl(keyOrPath); + return http.empty() ? keyOrPath : http; + } + // Every occurrence, as tns::ReplaceAll removes it everywhere else. + std::string path = keyOrPath; + const std::string& baseDir = RuntimeConfig.BaseDir; + if (!baseDir.empty()) { + for (size_t pos = path.find(baseDir); pos != std::string::npos; + pos = path.find(baseDir, pos)) { + path.erase(pos, baseDir.size()); + } + } + return "file://" + path; +} + } // namespace tns diff --git a/NativeScript/runtime/ModuleUrl.h b/NativeScript/runtime/ModuleUrl.h index eb3ec7c8..359d429b 100644 --- a/NativeScript/runtime/ModuleUrl.h +++ b/NativeScript/runtime/ModuleUrl.h @@ -34,4 +34,16 @@ ModuleUrl ParseModuleUrl(const std::string& input, const std::string& base); // not an http(s) URL. std::string NormalizeHttpModuleUrl(const std::string& input); +// Whether `s` starts with a URL scheme and ':' (`node:fs`, `blob:…`, +// `http://…`) rather than being a filesystem path. +bool HasUrlScheme(const std::string& s); + +// The URL a module or script is reported under (script origin, +// import.meta.url, inspector target), from its registry key or path: an +// http(s) URL as NormalizeHttpModuleUrl spells it; any other string that +// carries a URL scheme unchanged; a filesystem path as `file://` plus the path +// with RuntimeConfig.BaseDir removed, `file:///app/` for an empty one. The only +// place a `file://` URL is built from a path. +std::string ReportedModuleUrl(const std::string& keyOrPath); + } // namespace tns diff --git a/NativeScript/runtime/Runtime.mm b/NativeScript/runtime/Runtime.mm index 1dd423f0..8d055c03 100644 --- a/NativeScript/runtime/Runtime.mm +++ b/NativeScript/runtime/Runtime.mm @@ -43,10 +43,11 @@ #include "HttpLoader.h" #include "ModuleBinding.hpp" #include "ModuleInternalCallbacks.h" -#include "napi/NapiEnv.h" +#include "ModuleUrl.h" #include "URLImpl.h" #include "URLPatternImpl.h" #include "URLSearchParamsImpl.h" +#include "napi/NapiEnv.h" using namespace v8; using namespace std; @@ -76,31 +77,7 @@ static void InitializeImportMetaObject(Local context, Local mod std::string modulePath = tns::LookupModuleKeyForModule(isolate, module); - auto hasUrlScheme = [](const std::string& s) -> bool { - if (s.empty()) return false; - size_t colonPos = s.find(':'); - if (colonPos == 0 || colonPos == std::string::npos) return false; - size_t slashPos = s.find('/'); - if (slashPos != std::string::npos && slashPos < colonPos) return false; - for (size_t i = 0; i < colonPos; i++) { - char c = s[i]; - const bool ok = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || - c == '+' || c == '-' || c == '.'; - if (!ok) return false; - } - return true; - }; - - // Compute import.meta.url. - std::string moduleUrl; - if (modulePath.empty()) { - moduleUrl = "file:///app/"; - } else if (hasUrlScheme(modulePath)) { - moduleUrl = modulePath; - } else { - std::string base = tns::ReplaceAll(modulePath, RuntimeConfig.BaseDir, ""); - moduleUrl = "file://" + base; - } + const std::string moduleUrl = tns::ReportedModuleUrl(modulePath); Local url = String::NewFromUtf8(isolate, moduleUrl.c_str(), NewStringType::kNormal).ToLocalChecked(); @@ -127,7 +104,7 @@ static void InitializeImportMetaObject(Local context, Local mod std::string dirname; if (modulePath.empty()) { dirname = "/app"; - } else if (hasUrlScheme(modulePath)) { + } else if (tns::HasUrlScheme(modulePath)) { size_t schemeEnd = modulePath.find("://"); size_t pathStart = (schemeEnd == std::string::npos) ? std::string::npos : modulePath.find('/', schemeEnd + 3); diff --git a/NativeScript/runtime/WorkerWrapper.mm b/NativeScript/runtime/WorkerWrapper.mm index 419687fc..2e6d2aa9 100644 --- a/NativeScript/runtime/WorkerWrapper.mm +++ b/NativeScript/runtime/WorkerWrapper.mm @@ -485,9 +485,7 @@ static void PostThreadEndedNotification(Isolate* mainIsolate, std::weak_ptrworkerId_, isolate, CFRunLoopGetCurrent(), url); diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index 517223e0..d62e1799 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -705,9 +705,7 @@ The registry keys modules by a canonical URL. Before the vocabulary applies, an absolute http(s) URL is spelled by the WHATWG URL parser with its authority as written, whichever way it arrives — a specifier from any importer, an import-map target, or `invalidateModules` — so `HTTP://host/a/../x.js` and -`http:/host/x.js` key as `http://host/x.js`. A `file://http://…` string is not -an http(s) URL: it keys as itself, and `import()` of it fails with -`Cannot find module` without fetching anything. The mechanism — fragment strip, +`http:/host/x.js` key as `http://host/x.js`. The mechanism — fragment strip, cache-buster param drop, param sort — is the runtime's; the *vocabulary* is server policy, supplied here: From b684e7bb9b331204172b55fa66b6aafc89ce5bde Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Thu, 26 Nov 2026 19:48:16 -0300 Subject: [PATCH 11/13] fix(runtime): never report an http(s) module URL as a file:// URL ReportedModuleUrl tested for a URL scheme before asking whether the string is an http(s) URL, so one the loader accepts with leading whitespace or C0 controls failed the scheme test and was prefixed with file://. It now spells http(s) URLs first; other inputs are reported as before. --- NativeScript/runtime/ModuleUrl.cpp | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/NativeScript/runtime/ModuleUrl.cpp b/NativeScript/runtime/ModuleUrl.cpp index 1f145c2f..62340321 100644 --- a/NativeScript/runtime/ModuleUrl.cpp +++ b/NativeScript/runtime/ModuleUrl.cpp @@ -141,9 +141,15 @@ std::string ReportedModuleUrl(const std::string& keyOrPath) { if (keyOrPath.empty()) { return "file:///app/"; } + // Before the scheme test: the loader reads strings as http(s) URLs that the + // scheme test rejects (leading whitespace), and those must never be + // prefixed with file://. + const std::string http = NormalizeHttpModuleUrl(keyOrPath); + if (!http.empty()) { + return http; + } if (HasUrlScheme(keyOrPath)) { - const std::string http = NormalizeHttpModuleUrl(keyOrPath); - return http.empty() ? keyOrPath : http; + return keyOrPath; } // Every occurrence, as tns::ReplaceAll removes it everywhere else. std::string path = keyOrPath; From 139c7a7b05e1c890dfc46b65267301e2ffef072e Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Fri, 27 Nov 2026 02:23:46 -0300 Subject: [PATCH 12/13] fix(runtime): keep a configured remote-module allowlist in force and read it exactly A security.remoteModuleAllowlist array with at least one item is now in force: every URL is allowed only when the key is absent, not an array, or an empty array. An item that is not a string, is empty, or has no exact UTF-8 form matches nothing instead of being dropped, so a list of unusable items no longer becomes allow-all. Items are converted to UTF-8 by length through the new tns::ToExactUtf8, so an embedded U+0000 no longer truncates an entry to a broader prefix, and a string with a lone surrogate is reported as unconvertible instead of being read through a NULL -UTF8String. RemoteModuleAllowlistFromConfig and RemoteUrlAllowedByAllowlist hold the policy; the release gate and the debug remoteUrlMatchesAllowlist member both use them, so the member answers what the gate would for a list of entries, including true for []. --- NativeScript/runtime/Helpers.h | 21 ++++++++ NativeScript/runtime/HttpLoader.h | 33 ++++++++---- NativeScript/runtime/HttpLoader.mm | 50 ++++++++++--------- .../runtime/ModuleInternalCallbacks.mm | 46 +++++++++-------- .../app/tests/RemoteModuleSecurityTests.js | 35 +++++++++++++ docs/ns-builtin-modules.md | 11 +++- 6 files changed, 139 insertions(+), 57 deletions(-) diff --git a/NativeScript/runtime/Helpers.h b/NativeScript/runtime/Helpers.h index bb6a7da2..f0cba0b7 100644 --- a/NativeScript/runtime/Helpers.h +++ b/NativeScript/runtime/Helpers.h @@ -6,6 +6,7 @@ #include #include #include +#include #include #include @@ -171,6 +172,26 @@ inline std::string ToString(v8::Isolate* isolate, const NSString* value) { return tns::ToString(isolate, tns::ToV8String(isolate, value)); } +// The exact UTF-8 bytes of `value`, sized by length so an embedded U+0000 is +// kept (a C-string conversion stops there); nullopt for nil or for a string +// with a lone surrogate, which has no UTF-8 spelling (-UTF8String returns NULL). +inline std::optional ToExactUtf8(const NSString* value) { + if (value == nil) { + return std::nullopt; + } + CFStringRef str = (__bridge CFStringRef)value; + const CFRange range = CFRangeMake(0, CFStringGetLength(str)); + CFIndex byteCount = 0; + if (CFStringGetBytes(str, range, kCFStringEncodingUTF8, 0, false, nullptr, 0, &byteCount) != + range.length) { + return std::nullopt; + } + std::string bytes(static_cast(byteCount), '\0'); + CFStringGetBytes(str, range, kCFStringEncodingUTF8, 0, false, + reinterpret_cast(bytes.data()), byteCount, nullptr); + return bytes; +} + inline NSString* ToNSString(const std::string& v) { return [[[NSString alloc] initWithBytes:v.c_str() length:v.length() encoding:NSUTF8StringEncoding] S_AUTORELEASE]; diff --git a/NativeScript/runtime/HttpLoader.h b/NativeScript/runtime/HttpLoader.h index a0fbd7a7..f46f4038 100644 --- a/NativeScript/runtime/HttpLoader.h +++ b/NativeScript/runtime/HttpLoader.h @@ -146,16 +146,27 @@ bool IsRemoteModulesAllowed(); // (or all URLs if the allowlist is empty). bool IsRemoteUrlAllowed(const std::string& url); -// An allowlist entry spelled the way the loader spells the URLs it fetches -// (NormalizeHttpModuleUrl), so path-scoped entries compare against resolved -// paths; an entry that is not an http(s) URL is kept verbatim. Applied once, -// when the allowlist is loaded. -std::string NormalizeRemoteModuleAllowlistEntry(const std::string& entry); - -// The allowlist rule IsRemoteUrlAllowed applies: `url`, as fetched, matches -// one of `entries` (each already normalized) by prefix, the match ending at a -// URL-component boundary. -bool RemoteUrlMatchesAllowlist(const std::string& url, - const std::vector& entries); +// The allowlist IsRemoteUrlAllowed applies once remote modules are enabled. +struct RemoteModuleAllowlist { + // False only when `security.remoteModuleAllowlist` is absent, not an array, + // or an empty array: then every URL is allowed. + bool inForce = false; + // The usable items, each spelled the way the loader spells the URLs it + // fetches (NormalizeHttpModuleUrl) so path-scoped entries compare against + // resolved paths, or kept verbatim when it is not an http(s) URL. An item + // that is not a string, is empty or has no exact UTF-8 form is not here: it + // matches nothing but still keeps the list in force. + std::vector entries; +}; + +#ifdef __OBJC__ +// The allowlist for the raw `security.remoteModuleAllowlist` config value. +RemoteModuleAllowlist RemoteModuleAllowlistFromConfig(id value); +#endif + +// Whether `url` (as fetched) passes `allowlist`: always when it is not in +// force, otherwise when one entry matches it by prefix with the match ending +// at a URL-component boundary. +bool RemoteUrlAllowedByAllowlist(const std::string& url, const RemoteModuleAllowlist& allowlist); } // namespace tns diff --git a/NativeScript/runtime/HttpLoader.mm b/NativeScript/runtime/HttpLoader.mm index 8aa33bb0..8a3f30aa 100644 --- a/NativeScript/runtime/HttpLoader.mm +++ b/NativeScript/runtime/HttpLoader.mm @@ -33,7 +33,7 @@ static inline bool StartsWith(const std::string& s, const char* prefix) { static std::once_flag s_securityConfigInitFlag; static bool s_allowRemoteModules = false; -static std::vector s_remoteModuleAllowlist; +static RemoteModuleAllowlist s_remoteModuleAllowlist; // Returns true when `url` is authorized by allowlist `entry`. // @@ -55,13 +55,34 @@ static bool RemoteUrlMatchesAllowlistEntry(const std::string& url, const std::st return next == '/' || next == '?' || next == '#'; } -std::string NormalizeRemoteModuleAllowlistEntry(const std::string& entry) { +static std::string NormalizeRemoteModuleAllowlistEntry(const std::string& entry) { const std::string url = NormalizeHttpModuleUrl(entry); return url.empty() ? entry : url; } -bool RemoteUrlMatchesAllowlist(const std::string& url, const std::vector& entries) { - for (const std::string& entry : entries) { +RemoteModuleAllowlist RemoteModuleAllowlistFromConfig(id value) { + RemoteModuleAllowlist allowlist; + if (![value isKindOfClass:[NSArray class]] || [(NSArray*)value count] == 0) { + return allowlist; + } + allowlist.inForce = true; + for (id item in (NSArray*)value) { + if (![item isKindOfClass:[NSString class]]) { + continue; + } + const std::optional entry = ToExactUtf8((NSString*)item); + if (entry.has_value() && !entry->empty()) { + allowlist.entries.push_back(NormalizeRemoteModuleAllowlistEntry(*entry)); + } + } + return allowlist; +} + +bool RemoteUrlAllowedByAllowlist(const std::string& url, const RemoteModuleAllowlist& allowlist) { + if (!allowlist.inForce) { + return true; + } + for (const std::string& entry : allowlist.entries) { if (RemoteUrlMatchesAllowlistEntry(url, entry)) { return true; } @@ -84,19 +105,7 @@ static void InitializeSecurityConfig() { s_allowRemoteModules = [allowRemote boolValue]; } - id allowlist = security[@"remoteModuleAllowlist"]; - if (allowlist && [allowlist isKindOfClass:[NSArray class]]) { - NSArray* list = (NSArray*)allowlist; - for (id item in list) { - if ([item isKindOfClass:[NSString class]]) { - NSString* str = (NSString*)item; - if (str.length > 0) { - s_remoteModuleAllowlist.push_back( - NormalizeRemoteModuleAllowlistEntry(std::string([str UTF8String]))); - } - } - } - } + s_remoteModuleAllowlist = RemoteModuleAllowlistFromConfig(security[@"remoteModuleAllowlist"]); } }); } @@ -120,12 +129,7 @@ bool IsRemoteUrlAllowed(const std::string& url) { return false; } - // If no allowlist is configured, allow all URLs (user explicitly enabled remote modules) - if (s_remoteModuleAllowlist.empty()) { - return true; - } - - return RemoteUrlMatchesAllowlist(url, s_remoteModuleAllowlist); + return RemoteUrlAllowedByAllowlist(url, s_remoteModuleAllowlist); } // ───────────────────────────────────────────────────────────── diff --git a/NativeScript/runtime/ModuleInternalCallbacks.mm b/NativeScript/runtime/ModuleInternalCallbacks.mm index 6dea2915..1fbd7362 100644 --- a/NativeScript/runtime/ModuleInternalCallbacks.mm +++ b/NativeScript/runtime/ModuleInternalCallbacks.mm @@ -4214,33 +4214,37 @@ bool BuildNsModuleBinding(v8::Local context, v8::Local // Debug-only diagnostic: the release allowlist rule, which debug builds // never apply to fetches. `url` is spelled as the loader spells the URL it - // fetches and `entries` as the allowlist is loaded. + // fetches, and `entries` goes through the same loading as the + // `security.remoteModuleAllowlist` config array. auto allowlistCb = [](const v8::FunctionCallbackInfo& info) { v8::Isolate* iso = info.GetIsolate(); v8::Local ctx = iso->GetCurrentContext(); - std::vector entries; - bool valid = info.Length() >= 2 && info[0]->IsString() && info[1]->IsArray(); - if (valid) { - v8::Local list = info[1].As(); - for (uint32_t i = 0; valid && i < list->Length(); i++) { - v8::Local item; - if (!list->Get(ctx, i).ToLocal(&item)) { - return; // the element getter threw - } - valid = item->IsString(); - if (valid) { - entries.push_back(NormalizeRemoteModuleAllowlistEntry(tns::ToString(iso, item))); + @autoreleasepool { + NSMutableArray* entries = [NSMutableArray array]; + bool valid = info.Length() >= 2 && info[0]->IsString() && info[1]->IsArray(); + if (valid) { + v8::Local list = info[1].As(); + for (uint32_t i = 0; valid && i < list->Length(); i++) { + v8::Local item; + if (!list->Get(ctx, i).ToLocal(&item)) { + return; // the element getter threw + } + valid = item->IsString(); + if (valid) { + [entries addObject:tns::ToNSString(iso, item)]; + } } } + if (!valid) { + iso->ThrowException(v8::Exception::TypeError(tns::ToV8String( + iso, "remoteUrlMatchesAllowlist expects a URL string and an array of strings"))); + return; + } + const std::string raw = tns::ToString(iso, info[0]); + const std::string url = NormalizeHttpModuleUrl(raw); + info.GetReturnValue().Set(RemoteUrlAllowedByAllowlist( + url.empty() ? raw : url, RemoteModuleAllowlistFromConfig(entries))); } - if (!valid) { - iso->ThrowException(v8::Exception::TypeError(tns::ToV8String( - iso, "remoteUrlMatchesAllowlist expects a URL string and an array of strings"))); - return; - } - const std::string raw = tns::ToString(iso, info[0]); - const std::string url = NormalizeHttpModuleUrl(raw); - info.GetReturnValue().Set(RemoteUrlMatchesAllowlist(url.empty() ? raw : url, entries)); }; v8::Local allowlistFn; if (v8::Function::New(context, allowlistCb).ToLocal(&allowlistFn)) { diff --git a/TestRunner/app/tests/RemoteModuleSecurityTests.js b/TestRunner/app/tests/RemoteModuleSecurityTests.js index 79e51d9f..71903dfd 100644 --- a/TestRunner/app/tests/RemoteModuleSecurityTests.js +++ b/TestRunner/app/tests/RemoteModuleSecurityTests.js @@ -307,6 +307,41 @@ describe("Remote Module Security", function() { ]); }); + function expectLists(url, rows) { + rows.forEach(function (row) { + var actual = matches(url, row[0]); + if (actual === undefined) { + return; + } + var label = JSON.stringify(row[0]) + " vs " + JSON.stringify(url) + ": "; + expect(label + actual).toBe(label + row[1]); + }); + } + + it("allows every URL only when the list is empty", function() { + expectLists("https://cdn.example/x.js", [ + [[], true], + [[""], false], + [["", "https://cdn.example/"], true], + [["", "https://other.example/"], false], + [["https://other.example/", "https://cdn.example/lib/"], false], + ]); + }); + + it("lets an item with no exact UTF-8 form match nothing", function() { + expectLists("https://cdn.example/x.js", [ + [["\uD800"], false], + [["\uD800", "https://cdn.example/"], true], + ]); + }); + + it("keeps an entry with an embedded U+0000 whole", function() { + var entry = "https://cdn.example\u0000/private/"; + expectLists("https://cdn.example/other.js", [[[entry], false]]); + expectLists("https://cdn.example/private/x.js", [[[entry], false]]); + expectLists(entry + "x.js", [[[entry], true]]); + }); + it("rejects arguments that are not a URL string and an array of strings", function() { var fn = require("ns:module").remoteUrlMatchesAllowlist; if (typeof fn !== "function") { diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index d62e1799..270712a2 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -623,8 +623,9 @@ works; adding them is a change to this specification first. Debug builds additionally carry `canonicalizeHttpUrlKey(url)`, a pure test diagnostic that takes a string and throws `canonicalizeHttpUrlKey expects a URL string` otherwise, and -`remoteUrlMatchesAllowlist(url, entries)`, which applies the release -`security.remoteModuleAllowlist` rule to `url` against `entries` and throws +`remoteUrlMatchesAllowlist(url, entries)`, which returns whether a release +build with `allowRemoteModules` on would fetch `url` under a +`security.remoteModuleAllowlist` of `entries` (`true` for `[]`) and throws `remoteUrlMatchesAllowlist expects a URL string and an array of strings` otherwise; release builds omit both. Missing members are simply absent — never present-but-throwing — so feature checks work. The module is registered in @@ -632,6 +633,12 @@ every build: the security boundary for remote module loading sits at the network layer (`security.allowRemoteModules` in nativescript.config, enforced by the HTTP loader), not at the module registry and not at `ns:runtime`. +A `security.remoteModuleAllowlist` array with at least one item is in force: +a URL is fetched only when an entry matches it as a prefix ending at `/`, `?`, +`#` or the end of the URL. When the key is absent, not an array, or an empty +array, every URL is allowed. An item that is not a string, is empty, or is not +valid Unicode matches nothing but still keeps the list in force. + #### Import maps and scopes `importMap` takes the WHATWG shape: From 77cc495969b0cdabf711d8e03f605a52b5f2d81d Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Fri, 27 Nov 2026 02:36:06 -0300 Subject: [PATCH 13/13] fix(runtime): read import-map strings exactly The import-map parser read keys, targets, scope keys and section names through -UTF8String, so an embedded U+0000 cut them short, and a cut-short target or scope key is broader than written. They now go through tns::ToExactUtf8 and are kept whole: a specifier key or scope key containing U+0000 matches only those exact bytes. A target containing U+0000 is rejected with a TypeError when the map is validated, since resolving it as a path or fetching it as a URL would end it there. --- .../runtime/ModuleInternalCallbacks.mm | 35 ++++++++---- TestRunner/app/tests/HttpEsmLoaderTests.js | 53 +++++++++++++++++++ docs/ns-builtin-modules.md | 1 + 3 files changed, 78 insertions(+), 11 deletions(-) diff --git a/NativeScript/runtime/ModuleInternalCallbacks.mm b/NativeScript/runtime/ModuleInternalCallbacks.mm index 1fbd7362..6b226d2a 100644 --- a/NativeScript/runtime/ModuleInternalCallbacks.mm +++ b/NativeScript/runtime/ModuleInternalCallbacks.mm @@ -896,12 +896,14 @@ static bool ParseImportMapEntries(NSDictionary* source, const std::string& secti *error = sectionLabel + ": every key must be a string"; return false; } - const char* keyUtf8 = [(NSString*)key UTF8String]; - if (keyUtf8 == nullptr) { + // NSJSONSerialization rejects lone surrogates, so a map that parsed always + // has an exact UTF-8 form; the nullopt checks keep that an error, not a crash. + const std::optional keyUtf8 = ToExactUtf8((NSString*)key); + if (!keyUtf8.has_value()) { *error = sectionLabel + ": every key must be a string"; return false; } - const std::string specifier(keyUtf8); + const std::string& specifier = *keyUtf8; if (specifier.empty()) { *error = sectionLabel + ": a specifier key must not be empty"; return false; @@ -912,16 +914,22 @@ static bool ParseImportMapEntries(NSDictionary* source, const std::string& secti *error = sectionLabel + ": the target for '" + specifier + "' must be a string"; return false; } - const char* valueUtf8 = [(NSString*)value UTF8String]; - if (valueUtf8 == nullptr) { + const std::optional valueUtf8 = ToExactUtf8((NSString*)value); + if (!valueUtf8.has_value()) { *error = sectionLabel + ": the target for '" + specifier + "' must be a string"; return false; } - const std::string target(valueUtf8); + const std::string& target = *valueUtf8; if (target.empty()) { *error = sectionLabel + ": the target for '" + specifier + "' must not be empty"; return false; } + // A target resolves as a filesystem path or is fetched as a URL, and both + // go through C-string APIs that would end it at U+0000. + if (target.find('\0') != std::string::npos) { + *error = sectionLabel + ": the target for '" + specifier + "' must not contain U+0000"; + return false; + } // A trailing-slash key maps a whole subtree, so its target must name one // too — otherwise the remainder would be pasted onto a file path. @@ -977,9 +985,10 @@ static bool ParseImportMap(const std::string& json, ParsedImportMap* out, std::s if (![section isKindOfClass:[NSString class]] || (![(NSString*)section isEqualToString:@"imports"] && ![(NSString*)section isEqualToString:@"scopes"])) { - const char* name = - [section isKindOfClass:[NSString class]] ? [(NSString*)section UTF8String] : ""; - *error = std::string("unsupported import-map section '") + (name ? name : "") + + const std::optional name = [section isKindOfClass:[NSString class]] + ? ToExactUtf8((NSString*)section) + : std::nullopt; + *error = "unsupported import-map section '" + name.value_or(std::string()) + "'; only \"imports\" and \"scopes\" are supported"; return false; } @@ -1007,8 +1016,12 @@ static bool ParseImportMap(const std::string& json, ParsedImportMap* out, std::s *error = "scopes: every scope key must be a string"; return false; } - const char* scopeUtf8 = [(NSString*)scopeKey UTF8String]; - const std::string scopePrefix(scopeUtf8 ? scopeUtf8 : ""); + const std::optional scopeUtf8 = ToExactUtf8((NSString*)scopeKey); + if (!scopeUtf8.has_value()) { + *error = "scopes: every scope key must be a string"; + return false; + } + const std::string& scopePrefix = *scopeUtf8; if (scopePrefix.empty()) { *error = "scopes: a scope key must not be empty"; return false; diff --git a/TestRunner/app/tests/HttpEsmLoaderTests.js b/TestRunner/app/tests/HttpEsmLoaderTests.js index 26986cfa..2d59a12d 100644 --- a/TestRunner/app/tests/HttpEsmLoaderTests.js +++ b/TestRunner/app/tests/HttpEsmLoaderTests.js @@ -794,6 +794,37 @@ describe("HTTP ESM Loader", function() { }).toThrowError(TypeError, /must be a string/); }); + it("rejects a target containing U+0000 and keeps the previous map", function (done) { + setMap({ imports: { "ns-nul-prev": "~/tests/esm/query-map/stripped.mjs" } }); + expect(function () { + setMap({ + imports: { + "ns-nul-target": "~/tests/esm/query-map/literal.mjs\u0000/../../x.mjs", + }, + }); + }).toThrowError(TypeError, + "configureLoader: imports: the target for 'ns-nul-target' " + + "must not contain U+0000"); + import("ns-nul-prev").then(function (ns) { + expect(ns.name).toBe("stripped"); + done(); + }).catch(function (error) { + expect("rejected: " + formatError(error)).toBe("resolved"); + done(); + }); + }); + + it("matches a specifier key containing U+0000 whole", function (done) { + setMap({ imports: { "ns-nul-key\u0000x": "~/tests/esm/query-map/literal.mjs" } }); + import("ns-nul-key").then(function () { + expect("resolved").toBe("rejected"); + done(); + }, function (error) { + expect(String((error && error.message) || error)).toContain("Cannot find module"); + done(); + }); + }); + it("rejects a non-object scope map", function () { expect(function () { setMap({ scopes: { "/a/": "not-an-object" } }); @@ -1970,6 +2001,28 @@ describe("HTTP ESM Loader", function() { }); }); + it("keeps an http(s) scope key containing U+0000 whole", function (done) { + var origin = getHostOrigin(); + if (!origin) { + pending("REPORT_BASEURL not set; skipping host HTTP tests"); + done(); + return; + } + var base = origin + "/esm/resolve/nul-scope"; + var scopes = {}; + scopes[base + "/a\u0000/b/"] = { "ns-nul-scope": base + "/target.mjs?k=nul" }; + nsModule.configureLoader({ importMap: { imports: {}, scopes: scopes } }); + importer(origin, "nul-scope/a").then(function (mod) { + return rejectionMessage(mod.load("ns-nul-scope")); + }).then(function (message) { + expect(message).toContain("not in the import map"); + done(); + }).catch(function (error) { + expect("rejected: " + formatError(error)).toBe("resolved"); + done(); + }); + }); + it("rejects an import() whose import-map target resolves to nothing", function (done) { var origin = getHostOrigin(); if (!origin) { diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index 270712a2..e9fa668f 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -704,6 +704,7 @@ Inside either section — labelled `imports` or `scope ''`: | empty specifier key | `
: a specifier key must not be empty` | | non-string target | `
: the target for '' must be a string` | | empty target | `
: the target for '' must not be empty` | +| target containing U+0000 | `
: the target for '' must not contain U+0000` | | trailing-slash key, non-trailing-slash target | `
: the target for '' must end with '/' because the specifier key does` | #### Registry canonicalization