Skip to content

Commit ed556e1

Browse files
committed
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.
1 parent ae45c1f commit ed556e1

4 files changed

Lines changed: 110 additions & 39 deletions

File tree

‎NativeScript/runtime/HttpLoader.mm‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
#include "Helpers.h"
1313
#include "ModuleInternal.h"
1414
#include "ModuleInternalCallbacks.h"
15+
#include "ModuleUrl.h"
1516
#include "Runtime.h"
1617
#include "RuntimeConfig.h"
1718
#include "robin_hood.h"
@@ -156,9 +157,11 @@ bool IsRemoteUrlAllowed(const std::string& url) {
156157
if (StartsWith(normalizedUrl, "file://http:/") || StartsWith(normalizedUrl, "file://https:/")) {
157158
normalizedUrl = RepairCollapsedUrlScheme(normalizedUrl.substr(strlen("file://")));
158159
}
159-
if (!(StartsWith(normalizedUrl, "http://") || StartsWith(normalizedUrl, "https://"))) {
160+
const std::string httpUrl = NormalizeHttpModuleUrl(normalizedUrl);
161+
if (httpUrl.empty()) {
160162
return normalizedUrl;
161163
}
164+
normalizedUrl = httpUrl;
162165
// Drop fragment entirely
163166
size_t hashPos = normalizedUrl.find('#');
164167
std::string noHash =

‎NativeScript/runtime/ModuleInternal.mm‎

Lines changed: 14 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
#include "Helpers.h"
1212
#include "HttpLoader.h"
1313
#include "ModuleInternalCallbacks.h" // for ResolveModuleCallback
14+
#include "ModuleUrl.h"
1415
#include "NativeScriptException.h"
1516
#include "NsBuiltinModules.h"
1617
#include "Runtime.h"
@@ -80,33 +81,20 @@ static inline bool StartsWith(const std::string& value, const char* prefix) {
8081
return value.size() >= n && value.compare(0, n, prefix) == 0;
8182
}
8283

83-
static std::string NormalizeHttpModuleUrl(const std::string& path) {
84-
if (path.empty()) {
85-
return path;
86-
}
87-
88-
std::string normalized = path;
89-
if (StartsWith(normalized, "file://http://") || StartsWith(normalized, "file://https://")) {
90-
normalized = normalized.substr(strlen("file://"));
84+
// `path` as an http(s) module URL, or empty when it names none.
85+
static std::string HttpModuleUrl(const std::string& path) {
86+
if (StartsWith(path, "file://http://") || StartsWith(path, "file://https://")) {
87+
return NormalizeHttpModuleUrl(path.substr(strlen("file://")));
9188
}
92-
93-
if (normalized.rfind("http:/", 0) == 0 && normalized.rfind("http://", 0) != 0) {
94-
normalized.insert(5, "/");
95-
} else if (normalized.rfind("https:/", 0) == 0 && normalized.rfind("https://", 0) != 0) {
96-
normalized.insert(6, "/");
97-
}
98-
99-
return normalized;
89+
return NormalizeHttpModuleUrl(path);
10090
}
10191

102-
static bool IsHttpModulePath(const std::string& path) {
103-
std::string normalized = NormalizeHttpModuleUrl(path);
104-
return StartsWith(normalized, "http://") || StartsWith(normalized, "https://");
105-
}
92+
static bool IsHttpModulePath(const std::string& path) { return !HttpModuleUrl(path).empty(); }
10693

10794
static std::string CanonicalizeModulePath(const std::string& path) {
108-
if (IsHttpModulePath(path)) {
109-
return CanonicalizeHttpUrlKey(NormalizeHttpModuleUrl(path));
95+
const std::string url = HttpModuleUrl(path);
96+
if (!url.empty()) {
97+
return CanonicalizeHttpUrlKey(url);
11098
}
11199

112100
return NormalizePath(path);
@@ -250,7 +238,7 @@ static bool IsHttpModulePath(const std::string& path) {
250238
if (IsESModule(path) || isHttpModule) {
251239
Local<Value> moduleNamespace;
252240
if (isHttpModule) {
253-
TNS_DEBUG(Esm, "run-module http-esm begin %s", NormalizeHttpModuleUrl(path).c_str());
241+
TNS_DEBUG(Esm, "run-module http-esm begin %s", HttpModuleUrl(path).c_str());
254242
}
255243
try {
256244
// The entry runs before this thread's event loop does, so its graph can
@@ -277,7 +265,7 @@ throw NativeScriptException(
277265
"console for the matching [esm][evaluate][promise-timeout] entry.");
278266
}
279267
if (isHttpModule) {
280-
TNS_DEBUG(Esm, "run-module http-esm ok %s", NormalizeHttpModuleUrl(path).c_str());
268+
TNS_DEBUG(Esm, "run-module http-esm ok %s", HttpModuleUrl(path).c_str());
281269
}
282270
return;
283271
}
@@ -534,7 +522,7 @@ throw NativeScriptException(
534522
try {
535523
// Guard: URL-based modules must be loaded via dynamic import() in dev HTTP ESM mode.
536524
moduleName = tns::ToString(isolate, info[0]);
537-
if (moduleName.rfind("http://", 0) == 0 || moduleName.rfind("https://", 0) == 0) {
525+
if (!NormalizeHttpModuleUrl(moduleName).empty()) {
538526
std::string msg = std::string("NativeScript: require() of URL module is not supported: ") +
539527
moduleName + ". Use dynamic import() instead.";
540528
throw NativeScriptException(msg.c_str());
@@ -1491,7 +1479,7 @@ throw NativeScriptException("Module evaluation interrupted by isolate terminatio
14911479
const ModuleEvaluationOptions& options) {
14921480
bool isHttpModule = IsHttpModulePath(path);
14931481
std::string canonicalPath = CanonicalizeModulePath(path);
1494-
std::string requestPath = isHttpModule ? NormalizeHttpModuleUrl(path) : canonicalPath;
1482+
std::string requestPath = isHttpModule ? HttpModuleUrl(path) : canonicalPath;
14951483
auto context = isolate->GetCurrentContext();
14961484
auto* registryPtr = ModuleRegistryFor(isolate);
14971485
if (registryPtr == nullptr) {

‎NativeScript/runtime/ModuleInternalCallbacks.mm‎

Lines changed: 16 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -779,7 +779,7 @@ static bool ShouldTraceRegistryKey(const std::string& rawKey, const std::string&
779779
const char* classification = "path";
780780
bool traceEvenWithoutChange = false;
781781
782-
if (IsHttpRegistryKey(key) || StartsWith(key, "file://http://") ||
782+
if (!NormalizeHttpModuleUrl(key).empty() || StartsWith(key, "file://http://") ||
783783
StartsWith(key, "file://https://")) {
784784
registryKey = CanonicalizeHttpUrlKey(key);
785785
classification = "http";
@@ -815,12 +815,14 @@ static bool ShouldTraceRegistryKey(const std::string& rawKey, const std::string&
815815
816816
v8::MaybeLocal<v8::Module> LoadHttpModuleForUrl(v8::Isolate* isolate,
817817
v8::Local<v8::Context> context,
818-
const std::string& requestedUrl) {
818+
const std::string& requestedUrlArg) {
819819
auto* moduleState = ModuleLoaderStateFor(isolate);
820820
if (moduleState == nullptr) {
821821
return v8::MaybeLocal<v8::Module>();
822822
}
823823
auto& registry = moduleState->registry;
824+
const std::string normalizedUrl = NormalizeHttpModuleUrl(requestedUrlArg);
825+
const std::string& requestedUrl = normalizedUrl.empty() ? requestedUrlArg : normalizedUrl;
824826
const std::string registryKey = CanonicalizeHttpUrlKey(requestedUrl);
825827
826828
TNS_DEBUG(Esm, "[http-esm][load][begin] request=%s key=%s", requestedUrl.c_str(),
@@ -1722,9 +1724,10 @@ static ModuleResolution ResolveSpecifierToPath(
17221724
}
17231725
}
17241726
1725-
if (IsHttpRegistryKey(spec)) {
1727+
const std::string httpUrl = NormalizeHttpModuleUrl(spec);
1728+
if (!httpUrl.empty()) {
17261729
result.kind = ModuleResolution::Kind::kHttp;
1727-
result.url = spec;
1730+
result.url = httpUrl;
17281731
return result;
17291732
}
17301733
@@ -2207,9 +2210,10 @@ static void AsyncGraphEnqueue(const std::shared_ptr<AsyncGraphLoad>& load,
22072210
static ModuleResolution ResolutionForRoot(const std::string& root) {
22082211
ModuleResolution resolution;
22092212
resolution.specifier = root;
2210-
if (IsHttpRegistryKey(root)) {
2213+
const std::string httpUrl = NormalizeHttpModuleUrl(root);
2214+
if (!httpUrl.empty()) {
22112215
resolution.kind = ModuleResolution::Kind::kHttp;
2212-
resolution.url = root;
2216+
resolution.url = httpUrl;
22132217
} else if (IsRegularFile(root)) {
22142218
resolution.kind = ModuleResolution::Kind::kFile;
22152219
resolution.path = root;
@@ -3071,7 +3075,7 @@ static void FinishHttpDynamicImport(v8::Isolate* isolate, v8::Local<v8::Context>
30713075
// app path the registry keys by, or no scope would match it.
30723076
const std::string resourceName(*resourceUtf8);
30733077
const std::string resourceUrl = RepairCollapsedUrlScheme(resourceName);
3074-
if (ParseModuleUrl(resourceUrl, std::string()).http) {
3078+
if (!NormalizeHttpModuleUrl(resourceUrl).empty()) {
30753079
dynamicReferrerKey = CanonicalizeRegistryKey(resourceUrl);
30763080
} else {
30773081
const ModuleResolution referrer =
@@ -3091,7 +3095,7 @@ static void FinishHttpDynamicImport(v8::Isolate* isolate, v8::Local<v8::Context>
30913095
// A file importer's query/fragment never names part of a file, so it is
30923096
// dropped up front; an absolute http(s) specifier keeps it as identity. For
30933097
// an HTTP importer the seam resolves the specifier as a URL, query included.
3094-
const bool isHttpLike = IsHttpRegistryKey(normalizedSpec);
3098+
const bool isHttpLike = !NormalizeHttpModuleUrl(normalizedSpec).empty();
30953099
if (!isHttpLike && !importerIsHttp) {
30963100
size_t qpos = normalizedSpec.find_first_of("?#");
30973101
if (qpos != std::string::npos) {
@@ -3121,9 +3125,9 @@ static void FinishHttpDynamicImport(v8::Isolate* isolate, v8::Local<v8::Context>
31213125
TNS_DEBUG(Esm, "[dyn-import][import-map] rewrite: %s -> %s", rawSpec.c_str(),
31223126
normalizedSpec.c_str());
31233127
}
3124-
// An HTTP importer's relative, root-relative and scheme-relative imports
3125-
// continue as the absolute URL the seam resolved, through the HTTP path.
3126-
if (importerIsHttp && dynamicResolution.kind == ModuleResolution::Kind::kHttp &&
3128+
// Whatever resolves to an http(s) URL continues as the URL the resolver
3129+
// spelled, through the HTTP path.
3130+
if (dynamicResolution.kind == ModuleResolution::Kind::kHttp &&
31273131
dynamicResolution.url != normalizedSpec) {
31283132
normalizedSpec = dynamicResolution.url;
31293133
specifier = tns::ToV8String(isolate, normalizedSpec.c_str());
@@ -3478,7 +3482,7 @@ static void FinishHttpDynamicImport(v8::Isolate* isolate, v8::Local<v8::Context>
34783482
34793483
// If spec is an HTTP(S) URL, try HTTP fetch+compile directly
34803484
// Security: HttpFetchModule gates remote module access centrally.
3481-
if (!normalizedSpec.empty() && IsHttpRegistryKey(normalizedSpec)) {
3485+
if (dynamicResolution.kind == ModuleResolution::Kind::kHttp) {
34823486
TNS_DEBUG(Esm, "[dyn-import][http-loader] trying URL %s", normalizedSpec.c_str());
34833487
std::string key = CanonicalizeHttpUrlKey(normalizedSpec);
34843488
// Volatile pattern check: if the URL matches any configured volatile

‎TestRunner/app/tests/HttpEsmLoaderTests.js‎

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2296,6 +2296,68 @@ describe("HTTP ESM Loader", function() {
22962296
});
22972297
});
22982298
});
2299+
2300+
describe("absolute http(s) URLs from a file module", function () {
2301+
var nsModule = require("ns:module");
2302+
2303+
afterEach(function () {
2304+
nsModule.configureLoader({ importMap: { imports: {} } });
2305+
});
2306+
2307+
it("are spelled by the URL parser, keeping the authority as written", function (done) {
2308+
var origin = getHostOrigin();
2309+
if (!origin) {
2310+
pending("REPORT_BASEURL not set; skipping host HTTP tests");
2311+
done();
2312+
return;
2313+
}
2314+
var hostport = origin.replace(/^http:\/\//, "");
2315+
var base = origin + "/esm/resolve/file-abs";
2316+
nsModule.configureLoader({
2317+
importMap: { imports: { "ns-file-abs-mapped": base + "/mapped/../mapped.mjs" } },
2318+
});
2319+
Promise.all([
2320+
import("HTTP://" + hostport + "/esm/resolve/file-abs/upper.mjs"),
2321+
import("http:/" + hostport + "/esm/resolve/file-abs/collapsed.mjs?k=1"),
2322+
import(base + "/sub/../dots.mjs"),
2323+
import(base + "/mödule.mjs"),
2324+
import("ns-file-abs-mapped"),
2325+
]).then(function (mods) {
2326+
expect(mods.map(function (m) { return m.url; })).toEqual([
2327+
base + "/upper.mjs",
2328+
base + "/collapsed.mjs?k=1",
2329+
base + "/dots.mjs",
2330+
base + "/m%C3%B6dule.mjs",
2331+
base + "/mapped.mjs",
2332+
]);
2333+
expect(mods.map(function (m) { return m.path + "?" + m.query; })).toEqual([
2334+
"/esm/resolve/file-abs/upper.mjs?",
2335+
"/esm/resolve/file-abs/collapsed.mjs?k=1",
2336+
"/esm/resolve/file-abs/dots.mjs?",
2337+
"/esm/resolve/file-abs/m%C3%B6dule.mjs?",
2338+
"/esm/resolve/file-abs/mapped.mjs?",
2339+
]);
2340+
nsModule.invalidateModules(["HTTP://" + hostport + "/esm/resolve/file-abs/upper.mjs"]);
2341+
expect(nsModule.getLoadedModuleUrls()).not.toContain(base + "/upper.mjs");
2342+
done();
2343+
}).catch(function (error) {
2344+
expect("rejected: " + formatError(error)).toBe("resolved");
2345+
done();
2346+
});
2347+
});
2348+
2349+
it("are refused by require() whatever their scheme's case", function () {
2350+
["http://h/x.js", "HTTP://h/x.js"].forEach(function (url) {
2351+
var message = "";
2352+
try {
2353+
require(url);
2354+
} catch (e) {
2355+
message = String((e && e.message) || e);
2356+
}
2357+
expect(message).toContain("require() of URL module is not supported: " + url);
2358+
});
2359+
});
2360+
});
22992361
});
23002362

23012363
// Focused, deterministic coverage for the native HTTP canonical-key function.
@@ -2445,6 +2507,20 @@ describe("HTTP canonical key (ns:module canonicalizeHttpUrlKey)", function () {
24452507
"https://cdn.example.com/lib.js?token=abc");
24462508
});
24472509

2510+
it("spells a URL the way the URL parser does, authority aside", function () {
2511+
checkKey("HTTP://h/x", "http://h/x");
2512+
checkKey("http:h/x", "http://h/x");
2513+
checkKey(" http://h/x", "http://h/x");
2514+
checkKey("http://h", "http://h/");
2515+
checkKey("http://h?x", "http://h/?x");
2516+
checkKey("http://h/a/../b.js", "http://h/b.js");
2517+
checkKey("http://h/%2e%2e/b.js", "http://h/b.js");
2518+
checkKey("http://h\\x\\y.js", "http://h/x/y.js");
2519+
checkKey("http://h/mödule.js", "http://h/m%C3%B6dule.js");
2520+
checkKey("http://h/a b.js?q=a b", "http://h/a%20b.js?q=a%20b");
2521+
checkKey("http://H:80/x?", "http://H:80/x?");
2522+
});
2523+
24482524
it("keeps the URLs dev tooling emits as written", function () {
24492525
TOOLING_URLS.forEach(function (row) {
24502526
checkKey(row[0], row[1]);

0 commit comments

Comments
 (0)