diff --git a/NativeScript/runtime/ModuleInternal.mm b/NativeScript/runtime/ModuleInternal.mm index f957a3e63..4e4da9445 100644 --- a/NativeScript/runtime/ModuleInternal.mm +++ b/NativeScript/runtime/ModuleInternal.mm @@ -1840,15 +1840,21 @@ throw NativeScriptException( return std::string(); } - NSDictionary* dic = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]; - if (dic == nil) { + id json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]; + if (![json isKindOfClass:[NSDictionary class]]) { error = true; return std::string(); } - NSString* main = [dic objectForKey:@"main"]; - if (main == nil) { - main = @"index"; // Fallback to "index" if no main field found + // As in Node, a `main` that is not a string is ignored. + id mainValue = [(NSDictionary*)json objectForKey:@"main"]; + NSString* main = [mainValue isKindOfClass:[NSString class]] ? (NSString*)mainValue : @"index"; + // The lookups below go through C strings, which would end the path at + // U+0000; a lone surrogate has no UTF-8 form at all. + const std::optional mainUtf8 = tns::ToExactUtf8(main); + if (!mainUtf8.has_value() || mainUtf8->find('\0') != std::string::npos) { + error = true; + return std::string(); } NSString* baseDir = [packageJsonStr stringByDeletingLastPathComponent]; diff --git a/NativeScript/runtime/ModuleInternalCallbacks.mm b/NativeScript/runtime/ModuleInternalCallbacks.mm index 5edc8820c..0f741e769 100644 --- a/NativeScript/runtime/ModuleInternalCallbacks.mm +++ b/NativeScript/runtime/ModuleInternalCallbacks.mm @@ -1607,6 +1607,30 @@ static UrlSpecifier ResolveModuleSpecifierAgainstUrl(const std::string& spec, reason; } +// A specifier's exact UTF-8, or nullopt when it contains U+0000: the path and +// URL APIs behind resolution read C strings and would load whatever precedes it. +static std::optional ModuleSpecifierUtf8(v8::Isolate* isolate, + v8::Local specifier) { + std::string spec = tns::ToString(isolate, specifier); + if (spec.find('\0') != std::string::npos) { + return std::nullopt; + } + return spec; +} + +static std::string NulSpecifierMessage(v8::Isolate* isolate, v8::Local specifier) { + std::string shown; + for (char c : tns::ToString(isolate, specifier)) { + if (c == '\0') { + shown += "\\u0000"; + } else { + shown += c; + } + } + return "Cannot resolve module specifier \"" + shown + + "\": a module specifier must not contain U+0000"; +} + static bool IsRegularFile(const std::string& p) { std::string normalized = NormalizePath(p); struct stat st; @@ -1907,9 +1931,9 @@ static void AsyncGraphWalkModuleRequests(const std::shared_ptr& if (request.IsEmpty()) { continue; } - v8::Local specV8 = request->GetSpecifier(); - v8::String::Utf8Value specUtf8(isolate, specV8); - if (!*specUtf8) { + // A specifier holding U+0000 is left for the resolver to refuse at link. + const std::optional spec = ModuleSpecifierUtf8(isolate, request->GetSpecifier()); + if (!spec.has_value()) { continue; } // Builtins are served by the resolver from the builtin registry, and an @@ -1919,7 +1943,7 @@ static void AsyncGraphWalkModuleRequests(const std::shared_ptr& // message. An unmapped bare specifier's subtree is therefore not // discovered here; any HTTP edge inside it is pathological and lands on // the synchronous anomaly guard. - const ModuleResolution resolution = ResolveSpecifierToPath(*specUtf8, moduleKey); + const ModuleResolution resolution = ResolveSpecifierToPath(*spec, moduleKey); if (resolution.kind == ModuleResolution::Kind::kBuiltin || resolution.kind == ModuleResolution::Kind::kUnresolved) { continue; @@ -2753,8 +2777,13 @@ static void RejectAndClearInvalidatedModuleState(v8::Isolate* isolate, } auto& registry = moduleState->registry; - v8::String::Utf8Value specUtf8(isolate, specifier); - const std::string rawSpec = *specUtf8 ? *specUtf8 : ""; + const std::optional spec = ModuleSpecifierUtf8(isolate, specifier); + if (!spec.has_value()) { + isolate->ThrowException( + v8::Exception::Error(tns::ToV8String(isolate, NulSpecifierMessage(isolate, specifier)))); + return v8::MaybeLocal(); + } + const std::string& rawSpec = *spec; if (rawSpec.empty()) { return v8::MaybeLocal(); } @@ -2987,12 +3016,23 @@ static void FinishHttpDynamicImport(v8::Isolate* isolate, v8::Local auto& registry = moduleState->registry; auto& modulesInFlight = moduleState->modulesInFlight; auto& httpDynamicWaiters = moduleState->httpDynamicWaiters; - // Diagnostic: log every dynamic import attempt. - v8::String::Utf8Value specUtf8(isolate, specifier); - const char* cSpec = (*specUtf8) ? *specUtf8 : ""; - NSString* specStr = [NSString stringWithUTF8String:cSpec]; + const std::optional specUtf8 = ModuleSpecifierUtf8(isolate, specifier); + if (!specUtf8.has_value()) { + v8::EscapableHandleScope nulScope(isolate); + v8::Local nulResolver; + if (!v8::Promise::Resolver::New(context).ToLocal(&nulResolver)) { + return v8::MaybeLocal(); + } + nulResolver + ->Reject(context, v8::Exception::Error( + tns::ToV8String(isolate, NulSpecifierMessage(isolate, specifier)))) + .FromMaybe(false); + return nulScope.Escape(nulResolver->GetPromise()); + } + std::string rawSpec = *specUtf8; + NSString* specStr = tns::ToNSString(rawSpec); if (tns::LogCategoryEnabled(tns::LogCategory::Esm)) { - TNS_DEBUG(Esm, "[dyn-import] → %s", cSpec); + TNS_DEBUG(Esm, "[dyn-import] → %s", rawSpec.c_str()); // Also log the referrer resource when available to correlate origin of dynamic imports v8::Local resName = resource_name; if (!resName.IsEmpty() && resName->IsString()) { @@ -3002,8 +3042,6 @@ static void FinishHttpDynamicImport(v8::Isolate* isolate, v8::Local } } } - std::string rawSpec = cSpec ? std::string(cSpec) : std::string(); - // Builtin modules never reach the loader below; the namespace comes straight // from the realm's synthetic module. if (NsBuiltinModules::IsBuiltinScheme(rawSpec)) { diff --git a/NativeScript/runtime/Runtime.mm b/NativeScript/runtime/Runtime.mm index 8d055c036..899954681 100644 --- a/NativeScript/runtime/Runtime.mm +++ b/NativeScript/runtime/Runtime.mm @@ -88,40 +88,17 @@ static void InitializeImportMetaObject(Local context, Local mod url) .Check(); - // Compute import.meta.dirname. - // - // Spec (Node.js): `import.meta.dirname` is the OS-path of the - // directory containing the module — equivalent to `path.dirname( - // fileURLToPath(import.meta.url))`. It only makes sense for modules - // backed by the local filesystem. - // - // For URL-backed modules (HTTP, blob, etc.) there is no - // filesystem directory. We return the URL with the final segment - // stripped — a best-effort answer that's stable across cycles and - // useful for log lines / source maps. Consumers that genuinely need - // a filesystem path should already be guarding on `meta.url`'s - // scheme before using `meta.dirname`. + // As in Node, import.meta.dirname exists only for a module loaded from the + // filesystem: path.dirname(fileURLToPath(import.meta.url)), taken from the + // same base-stripped path the url reports. A module whose key carries a URL + // scheme (http(s), blob:, builtins) has no directory and gets no property. + if (tns::HasUrlScheme(modulePath)) { + return; + } std::string dirname; if (modulePath.empty()) { dirname = "/app"; - } else if (tns::HasUrlScheme(modulePath)) { - size_t schemeEnd = modulePath.find("://"); - size_t pathStart = - (schemeEnd == std::string::npos) ? std::string::npos : modulePath.find('/', schemeEnd + 3); - size_t lastSlash = modulePath.find_last_of('/'); - if (pathStart != std::string::npos && lastSlash != std::string::npos && lastSlash > pathStart) { - dirname = modulePath.substr(0, lastSlash); - } else { - // No path beyond the host (`http://host`) or scheme without `//` - // (`node:fs`, `blob:abc`). Keep the identity intact. - dirname = modulePath; - } } else { - // Derived from the same base-stripped path `import.meta.url` reports, so - // the documented equivalence holds: dirname is - // `path.dirname(fileURLToPath(import.meta.url))`. Taking it from the raw - // path instead reported a container-absolute directory for a module whose - // url said `file:///app/…`. const std::string appRelative = tns::ReplaceAll(modulePath, RuntimeConfig.BaseDir, ""); size_t lastSlash = appRelative.find_last_of("/\\"); if (lastSlash != std::string::npos && lastSlash > 0) { diff --git a/NativeScript/runtime/Worker.mm b/NativeScript/runtime/Worker.mm index d42239943..ed1073813 100644 --- a/NativeScript/runtime/Worker.mm +++ b/NativeScript/runtime/Worker.mm @@ -10,6 +10,7 @@ #include "Helpers.h" #include "ModuleBinding.hpp" #include "ModuleInternalCallbacks.h" +#include "ModuleUrl.h" #include "NativeScriptException.h" #include "ObjectManager.h" #include "Runtime.h" @@ -384,35 +385,47 @@ throw NativeScriptException( // Relative worker paths are resolved against the calling module's directory, // matching the Android runtime and the legacy JSC iOS runtime. If no file is // found there, fall back to app-root-relative resolution, which is what this - // runtime historically did. + // runtime historically did. A module loaded over HTTP resolves them against + // its URL instead and never reaches the app root. if (workerPath.rfind("./", 0) == 0 || workerPath.rfind("../", 0) == 0) { + std::string callerScript; Local stack = StackTrace::CurrentStackTrace(isolate, 1); if (!stack.IsEmpty() && stack->GetFrameCount() > 0) { Local scriptName = stack->GetFrame(isolate, 0)->GetScriptName(); if (!scriptName.IsEmpty()) { - std::string callerScript = ToString(isolate, scriptName); - const std::string filePrefix = "file://"; - if (callerScript.rfind(filePrefix, 0) == 0) { - callerScript = callerScript.substr(filePrefix.size()); - } - // Script origins are relative to the app bundle root (BaseDir) - if (!callerScript.empty() && callerScript[0] == '/' && - callerScript.rfind(RuntimeConfig.BaseDir, 0) != 0) { - callerScript = RuntimeConfig.BaseDir + callerScript; - } - if (!callerScript.empty() && callerScript[0] == '/') { - NSString* callerDir = [[NSString stringWithUTF8String:callerScript.c_str()] - stringByDeletingLastPathComponent]; - NSString* candidate = [[callerDir - stringByAppendingPathComponent:[NSString stringWithUTF8String:workerPath.c_str()]] - stringByStandardizingPath]; - if (tns::Exists([candidate fileSystemRepresentation]) || - tns::Exists( - [[candidate stringByAppendingPathExtension:@"js"] fileSystemRepresentation]) || - tns::Exists([[candidate stringByAppendingPathComponent:@"index.js"] - fileSystemRepresentation])) { - workerPath = [candidate UTF8String]; - } + callerScript = ToString(isolate, scriptName); + } + } + + if (IsHttpRegistryKey(callerScript)) { + const ModuleUrl resolved = ParseModuleUrl(workerPath, callerScript); + if (!resolved.parsed || !resolved.http) { + throw NativeScriptException("Cannot resolve worker path \"" + workerPath + + "\" against the calling module's URL " + callerScript); + } + workerPath = resolved.href; + } else if (!callerScript.empty()) { + const std::string filePrefix = "file://"; + if (callerScript.rfind(filePrefix, 0) == 0) { + callerScript = callerScript.substr(filePrefix.size()); + } + // Script origins are relative to the app bundle root (BaseDir) + if (!callerScript.empty() && callerScript[0] == '/' && + callerScript.rfind(RuntimeConfig.BaseDir, 0) != 0) { + callerScript = RuntimeConfig.BaseDir + callerScript; + } + if (!callerScript.empty() && callerScript[0] == '/') { + NSString* callerDir = [[NSString stringWithUTF8String:callerScript.c_str()] + stringByDeletingLastPathComponent]; + NSString* candidate = [[callerDir + stringByAppendingPathComponent:[NSString stringWithUTF8String:workerPath.c_str()]] + stringByStandardizingPath]; + if (tns::Exists([candidate fileSystemRepresentation]) || + tns::Exists( + [[candidate stringByAppendingPathExtension:@"js"] fileSystemRepresentation]) || + tns::Exists([[candidate stringByAppendingPathComponent:@"index.js"] + fileSystemRepresentation])) { + workerPath = [candidate UTF8String]; } } } diff --git a/TestRunner/app/tests/HttpEsmLoaderTests.js b/TestRunner/app/tests/HttpEsmLoaderTests.js index d51be7cbd..d636e1bcf 100644 --- a/TestRunner/app/tests/HttpEsmLoaderTests.js +++ b/TestRunner/app/tests/HttpEsmLoaderTests.js @@ -1276,9 +1276,8 @@ describe("HTTP ESM Loader", function() { expect(typeof module.metaUrl).toBe("string"); expect(module.metaUrl.indexOf("file://")).toBe(0); expect(module.metaUrl).toContain("tests/esm/relative/meta.mjs"); - expect(typeof module.metaDirname).toBe("string"); - expect(module.metaDirname).toContain("tests/esm/relative"); - expect(module.metaDirname).not.toContain("meta.mjs"); + expect(module.metaHasDirname).toBe(true); + expect(module.metaDirname).toBe("/app/tests/esm/relative"); done(); }).catch(function(error) { expect("rejected: " + formatError(error)).toBe("resolved"); @@ -1286,6 +1285,62 @@ describe("HTTP ESM Loader", function() { }); }); + it("gives an HTTP module no import.meta.dirname, even with a '/' in its query", + function(done) { + var origin = getHostOrigin(); + if (!origin) { + pending("REPORT_BASEURL not set; skipping host HTTP tests"); + done(); + return; + } + var url = origin + "/esm/meta/asm?path=/src/app/main.ts"; + import(url).then(function(module) { + expect(module.url).toBe(url); + expect(module.hasDirname).toBe(false); + expect(module.dirname).toBeUndefined(); + done(); + }).catch(function(error) { + expect("rejected: " + formatError(error)).toBe("resolved"); + done(); + }); + }); + + it("gives a blob: module no import.meta.dirname", function(done) { + // The bare test realm has no Blob; createObjectURL needs an + // instance carrying `type`, and the loader only calls `.text()`. + var previousBlob = globalThis.Blob; + globalThis.Blob = function Blob(parts, options) { + this._text = (parts || []).join(""); + this.type = (options && options.type) || ""; + }; + globalThis.Blob.prototype.text = function () { + return Promise.resolve(this._text); + }; + var url = URL.createObjectURL( + new Blob(["export const hasDirname = \"dirname\" in import.meta;\n" + + "export const url = import.meta.url;\n"], + { type: "text/javascript" }), + { ext: ".mjs" }); + function cleanUp() { + URL.revokeObjectURL(url); + if (typeof previousBlob === "undefined") { + delete globalThis.Blob; + } else { + globalThis.Blob = previousBlob; + } + } + import(url).then(function(module) { + cleanUp(); + expect(module.url).toBe(url); + expect(module.hasDirname).toBe(false); + done(); + }).catch(function(error) { + cleanUp(); + expect("rejected: " + formatError(error)).toBe("resolved"); + done(); + }); + }); + it("returns one module identity for repeated JSON imports", function(done) { var spec = "~/tests/esm/identity.json"; Promise.all([import(spec), import(spec)]).then(function(results) { @@ -1642,6 +1697,199 @@ describe("HTTP ESM Loader", function() { }); }); + function requestCount(origin, target) { + return import(origin + "/esm/request-stats.json?target=" + + encodeURIComponent(target)).then(function (m) { + return m.default.count; + }); + } + + // A browser would percent-encode U+0000 against an http(s) base; the + // loader refuses it from every importer alike. + describe("with a specifier containing U+0000", function () { + var rule = "a module specifier must not contain U+0000"; + + it("rejects an import() without fetching anything", function (done) { + var origin = getHostOrigin(); + if (!origin) { + pending("REPORT_BASEURL not set; skipping host HTTP tests"); + done(); + return; + } + withTimeout(importer(origin, "nul-dynamic").then(function (mod) { + return rejectionMessage(mod.load("./target.mjs\u0000junk")); + }).then(function (message) { + expect(message).toContain(rule); + expect(message.indexOf("\u0000")).toBe(-1); + return Promise.all([ + requestCount(origin, "/esm/resolve/nul-dynamic/target.mjs"), + requestCount(origin, "/esm/resolve/nul-dynamic/target.mjs%00junk"), + ]); + }), 10000, "nul-dynamic").then(function (counts) { + expect(counts).toEqual([0, 0]); + done(); + }).catch(function (error) { + expect("rejected: " + formatError(error)).toBe("resolved"); + done(); + }); + }, 15000); + + it("fails a static import without fetching anything", function (done) { + var origin = getHostOrigin(); + if (!origin) { + pending("REPORT_BASEURL not set; skipping host HTTP tests"); + done(); + return; + } + var spec = "./nul-static/target.mjs\u0000junk"; + withTimeout(rejectionMessage(import(origin + "/esm/resolve/static.mjs?spec=" + + encodeURIComponent(spec))) + .then(function (message) { + expect(message).toContain(rule); + expect(message.indexOf("\u0000")).toBe(-1); + return Promise.all([ + requestCount(origin, "/esm/resolve/nul-static/target.mjs"), + requestCount(origin, "/esm/resolve/nul-static/target.mjs%00junk"), + ]); + }), 10000, "nul-static").then(function (counts) { + expect(counts).toEqual([0, 0]); + done(); + }).catch(function (error) { + expect("rejected: " + formatError(error)).toBe("resolved"); + done(); + }); + }, 15000); + }); + + // NativeScript resolves a relative Worker path against the calling + // module rather than a document base URL; for a module loaded over + // HTTP that is the module's URL. The decoys sit where the app-root + // join would land, so the spec fails loudly if that join is taken. + describe("new Worker() with a relative path from an HTTP module", function () { + var decoyName = "nsHttpRelWorkerDecoy.js"; + var bundle = NSBundle.mainBundle.resourcePath; + var decoyPaths = [bundle + "/app/" + decoyName, bundle + "/" + decoyName]; + + beforeEach(function () { + var data = NSString.stringWithString("postMessage({ source: \"decoy\" });\n") + .dataUsingEncoding(NSUTF8StringEncoding); + decoyPaths.forEach(function (p) { + NSFileManager.defaultManager.createFileAtPathContentsAttributes(p, data, null); + }); + }); + + afterEach(function () { + decoyPaths.forEach(function (p) { + if (NSFileManager.defaultManager.fileExistsAtPath(p)) { + NSFileManager.defaultManager.removeItemAtPathError(p); + } + }); + }); + + function firstMessage(worker) { + return new Promise(function (resolve, reject) { + var timer = setTimeout(function () { + worker.terminate(); + reject(new Error("no message from the worker")); + }, 10000); + worker.onmessage = function (msg) { + clearTimeout(timer); + worker.terminate(); + resolve(msg.data); + }; + worker.onerror = function (e) { + clearTimeout(timer); + worker.terminate(); + reject(new Error(String((e && e.message) || e))); + return true; + }; + }); + } + + function spawner(origin, dir) { + return import(origin + "/esm/worker/" + dir + "/spawner.mjs"); + } + + it("loads './x.js' from next to the module", function (done) { + var origin = getHostOrigin(); + if (!origin) { + pending("REPORT_BASEURL not set; skipping host HTTP tests"); + done(); + return; + } + var served = "/esm/worker/dot/sub/" + decoyName; + spawner(origin, "dot/sub").then(function (mod) { + return firstMessage(mod.spawn("./" + decoyName)); + }).then(function (data) { + expect(data).toEqual({ source: "http", path: served }); + return requestCount(origin, served); + }).then(function (count) { + expect(count).toBe(1); + done(); + }).catch(function (error) { + expect("rejected: " + formatError(error)).toBe("resolved"); + done(); + }); + }, 20000); + + it("loads '../x.js' from the module's parent path", function (done) { + var origin = getHostOrigin(); + if (!origin) { + pending("REPORT_BASEURL not set; skipping host HTTP tests"); + done(); + return; + } + var served = "/esm/worker/dotdot/" + decoyName; + spawner(origin, "dotdot/sub").then(function (mod) { + return firstMessage(mod.spawn("../" + decoyName)); + }).then(function (data) { + expect(data).toEqual({ source: "http", path: served }); + return requestCount(origin, served); + }).then(function (count) { + expect(count).toBe(1); + done(); + }).catch(function (error) { + expect("rejected: " + formatError(error)).toBe("resolved"); + done(); + }); + }, 20000); + + it("loads new URL('./x.js', import.meta.url) over HTTP", function (done) { + var origin = getHostOrigin(); + if (!origin) { + pending("REPORT_BASEURL not set; skipping host HTTP tests"); + done(); + return; + } + spawner(origin, "url-form").then(function (mod) { + return firstMessage(mod.spawnUrl("./" + decoyName)); + }).then(function (data) { + expect(data).toEqual({ source: "http", path: "/esm/worker/url-form/" + decoyName }); + done(); + }).catch(function (error) { + expect("rejected: " + formatError(error)).toBe("resolved"); + done(); + }); + }, 20000); + + it("loads an absolute http(s) URL given by a file module", function (done) { + var origin = getHostOrigin(); + if (!origin) { + pending("REPORT_BASEURL not set; skipping host HTTP tests"); + done(); + return; + } + var served = "/esm/worker/absolute/" + decoyName; + firstMessage(new Worker(origin + served)).then(function (data) { + expect(data).toEqual({ source: "http", path: served }); + done(); + }).catch(function (error) { + expect("rejected: " + formatError(error)).toBe("resolved"); + done(); + }); + }, 20000); + }); + // The fixture is written at run time: a colon in a checked-in file // name cannot be checked out on Windows. describe("with a module at the app root named like an other-scheme URL", function () { diff --git a/TestRunner/app/tests/LoaderHardeningTests.js b/TestRunner/app/tests/LoaderHardeningTests.js index 57c4bf66c..1f775e442 100644 --- a/TestRunner/app/tests/LoaderHardeningTests.js +++ b/TestRunner/app/tests/LoaderHardeningTests.js @@ -105,6 +105,85 @@ describe("loader hardening", function () { }); }); + function rejectionOf(promise) { + return promise.then(function () { + return null; + }, function (e) { + return e; + }); + } + + // Path and URL APIs read a specifier as a C string, so everything after a + // U+0000 would be dropped and a different module loaded. + describe("module specifiers containing U+0000", function () { + var rule = "a module specifier must not contain U+0000"; + + it("fail a static import from a file module, loading nothing", function (done) { + rejectionOf(import("~/tests/loaderhardening/nulStaticImporter.mjs")).then(function (e) { + expect(e instanceof Error).toBe(true); + var message = String((e && e.message) || e); + expect(message).toContain(rule); + expect(message.indexOf("\u0000")).toBe(-1); + expect(globalThis.__nsNulDecoyStaticEvaluated).toBeUndefined(); + done(); + }); + }); + + it("reject an import() from a file module, loading nothing", function (done) { + import("~/tests/loaderhardening/nulDynamicImporter.mjs").then(function (mod) { + return Promise.all([ + rejectionOf(mod.load("./nulDecoyDynamic.mjs\u0000junk")), + rejectionOf(mod.load("./nulDecoyDynamic.mjs?v=1\u0000junk")), + ]); + }).then(function (errors) { + errors.forEach(function (e) { + expect(e instanceof Error).toBe(true); + var message = String((e && e.message) || e); + expect(message).toContain(rule); + expect(message.indexOf("\u0000")).toBe(-1); + }); + expect(globalThis.__nsNulDecoyDynamicEvaluated).toBeUndefined(); + done(); + }).catch(function (e) { + expect("rejected: " + String((e && e.message) || e)).toBe("resolved"); + done(); + }); + }); + }); + + describe("package.json main", function () { + var unlocatable = "Unable to locate main entry in "; + + it("falls back to index when main is not a string", function () { + var req = require("ns:module").createRequire(fixtures + "/"); + expect(req("./pkgNonStringMain").entry).toBe("index"); + }); + + it("cannot locate a main holding a lone surrogate", function () { + var req = require("ns:module").createRequire(fixtures + "/"); + expect(messageOf(function () { + req("./pkgSurrogateMain"); + })).toContain(unlocatable + fixtures + "/pkgSurrogateMain/package.json"); + expect(globalThis.__nsPkgSurrogateMainIndexLoaded).toBeUndefined(); + }); + + it("cannot locate a main containing U+0000", function () { + var req = require("ns:module").createRequire(fixtures + "/"); + expect(messageOf(function () { + req("./pkgNulMain"); + })).toContain(unlocatable + fixtures + "/pkgNulMain/package.json"); + expect(globalThis.__nsPkgNulMainIndexLoaded).toBeUndefined(); + }); + + it("cannot locate the main of a package.json that is not an object", function () { + var req = require("ns:module").createRequire(fixtures + "/"); + expect(messageOf(function () { + req("./pkgArrayJson"); + })).toContain(unlocatable + fixtures + "/pkgArrayJson/package.json"); + expect(globalThis.__nsPkgArrayJsonIndexLoaded).toBeUndefined(); + }); + }); + // configureLoader's deadline is validated in ns-module.js; the native // binding re-validates so the boundary holds on its own. describe("pumping deadline", function () { diff --git a/TestRunner/app/tests/esm/relative/meta.mjs b/TestRunner/app/tests/esm/relative/meta.mjs index 780535f7c..277bfd8b5 100644 --- a/TestRunner/app/tests/esm/relative/meta.mjs +++ b/TestRunner/app/tests/esm/relative/meta.mjs @@ -1,2 +1,3 @@ export const metaUrl = import.meta.url; export const metaDirname = import.meta.dirname; +export const metaHasDirname = "dirname" in import.meta; diff --git a/TestRunner/app/tests/loaderhardening/nulDecoyDynamic.mjs b/TestRunner/app/tests/loaderhardening/nulDecoyDynamic.mjs new file mode 100644 index 000000000..ba7324c08 --- /dev/null +++ b/TestRunner/app/tests/loaderhardening/nulDecoyDynamic.mjs @@ -0,0 +1,3 @@ +globalThis.__nsNulDecoyDynamicEvaluated = true; + +export const decoy = "nul-decoy-dynamic"; diff --git a/TestRunner/app/tests/loaderhardening/nulDecoyStatic.mjs b/TestRunner/app/tests/loaderhardening/nulDecoyStatic.mjs new file mode 100644 index 000000000..de9952582 --- /dev/null +++ b/TestRunner/app/tests/loaderhardening/nulDecoyStatic.mjs @@ -0,0 +1,3 @@ +globalThis.__nsNulDecoyStaticEvaluated = true; + +export const decoy = "nul-decoy-static"; diff --git a/TestRunner/app/tests/loaderhardening/nulDynamicImporter.mjs b/TestRunner/app/tests/loaderhardening/nulDynamicImporter.mjs new file mode 100644 index 000000000..0712d2d4b --- /dev/null +++ b/TestRunner/app/tests/loaderhardening/nulDynamicImporter.mjs @@ -0,0 +1,3 @@ +export function load(spec) { + return import(spec); +} diff --git a/TestRunner/app/tests/loaderhardening/nulStaticImporter.mjs b/TestRunner/app/tests/loaderhardening/nulStaticImporter.mjs new file mode 100644 index 000000000..50e6f0200 --- /dev/null +++ b/TestRunner/app/tests/loaderhardening/nulStaticImporter.mjs @@ -0,0 +1,3 @@ +import { decoy } from "./nulDecoyStatic.mjs\u0000junk"; + +export const value = decoy; diff --git a/TestRunner/app/tests/loaderhardening/pkgArrayJson/index.js b/TestRunner/app/tests/loaderhardening/pkgArrayJson/index.js new file mode 100644 index 000000000..a189670d9 --- /dev/null +++ b/TestRunner/app/tests/loaderhardening/pkgArrayJson/index.js @@ -0,0 +1,2 @@ +globalThis.__nsPkgArrayJsonIndexLoaded = true; +module.exports = { entry: "index" }; diff --git a/TestRunner/app/tests/loaderhardening/pkgArrayJson/package.json b/TestRunner/app/tests/loaderhardening/pkgArrayJson/package.json new file mode 100644 index 000000000..c14f95fc6 --- /dev/null +++ b/TestRunner/app/tests/loaderhardening/pkgArrayJson/package.json @@ -0,0 +1 @@ +["index.js"] diff --git a/TestRunner/app/tests/loaderhardening/pkgNonStringMain/index.js b/TestRunner/app/tests/loaderhardening/pkgNonStringMain/index.js new file mode 100644 index 000000000..7887debac --- /dev/null +++ b/TestRunner/app/tests/loaderhardening/pkgNonStringMain/index.js @@ -0,0 +1 @@ +module.exports = { entry: "index" }; diff --git a/TestRunner/app/tests/loaderhardening/pkgNonStringMain/package.json b/TestRunner/app/tests/loaderhardening/pkgNonStringMain/package.json new file mode 100644 index 000000000..a1e4eb0fe --- /dev/null +++ b/TestRunner/app/tests/loaderhardening/pkgNonStringMain/package.json @@ -0,0 +1,4 @@ +{ + "name": "pkg-non-string-main", + "main": 42 +} diff --git a/TestRunner/app/tests/loaderhardening/pkgNulMain/index.js b/TestRunner/app/tests/loaderhardening/pkgNulMain/index.js new file mode 100644 index 000000000..ca04f388c --- /dev/null +++ b/TestRunner/app/tests/loaderhardening/pkgNulMain/index.js @@ -0,0 +1,2 @@ +globalThis.__nsPkgNulMainIndexLoaded = true; +module.exports = { entry: "index" }; diff --git a/TestRunner/app/tests/loaderhardening/pkgNulMain/package.json b/TestRunner/app/tests/loaderhardening/pkgNulMain/package.json new file mode 100644 index 000000000..ce6339108 --- /dev/null +++ b/TestRunner/app/tests/loaderhardening/pkgNulMain/package.json @@ -0,0 +1,4 @@ +{ + "name": "pkg-nul-main", + "main": "index\u0000x" +} diff --git a/TestRunner/app/tests/loaderhardening/pkgSurrogateMain/index.js b/TestRunner/app/tests/loaderhardening/pkgSurrogateMain/index.js new file mode 100644 index 000000000..3ea64183c --- /dev/null +++ b/TestRunner/app/tests/loaderhardening/pkgSurrogateMain/index.js @@ -0,0 +1,2 @@ +globalThis.__nsPkgSurrogateMainIndexLoaded = true; +module.exports = { entry: "index" }; diff --git a/TestRunner/app/tests/loaderhardening/pkgSurrogateMain/package.json b/TestRunner/app/tests/loaderhardening/pkgSurrogateMain/package.json new file mode 100644 index 000000000..6ec5ecc14 --- /dev/null +++ b/TestRunner/app/tests/loaderhardening/pkgSurrogateMain/package.json @@ -0,0 +1,4 @@ +{ + "name": "pkg-surrogate-main", + "main": "a\ud800b" +} diff --git a/TestRunnerTests/TestRunnerTests.swift b/TestRunnerTests/TestRunnerTests.swift index e0d93b90d..2f99bf8f7 100644 --- a/TestRunnerTests/TestRunnerTests.swift +++ b/TestRunnerTests/TestRunnerTests.swift @@ -41,6 +41,7 @@ class TestRunnerTests: XCTestCase { .replacingOccurrences(of: "\"", with: "\\\"") .replacingOccurrences(of: "\n", with: "\\n") .replacingOccurrences(of: "\r", with: "\\r") + .replacingOccurrences(of: "\u{0}", with: "\\u0000") } // Progress beacon from the in-app Jasmine reporter (fire-and-forget): @@ -157,6 +158,36 @@ class TestRunnerTests: XCTestCase { return } + // Reports the import.meta of a module whose URL may carry a + // query, as dev servers' module endpoints do. + if path.hasPrefix("/esm/meta/") { + let body = "export const hasDirname = \"dirname\" in import.meta;\n" + + "export const dirname = import.meta.dirname;\n" + + "export const url = import.meta.url;\n" + startResponse("200 OK", [("Content-Type", "application/javascript; charset=utf-8")]) + sendBody(body.data(using: .utf8) ?? Data()) + return + } + + // ── Workers created by an HTTP module ── + // `…/spawner.mjs` constructs the Worker itself, so the module + // is the innermost frame at construction; any other path is a + // worker entry that posts back the path it was served from. + if path.hasPrefix("/esm/worker/") { + let body: String + if path.hasSuffix("/spawner.mjs") { + body = "export function spawn(spec) { return new Worker(spec); }\n" + + "export function spawnUrl(spec) {\n" + + " return new Worker(new URL(spec, import.meta.url));\n" + + "}\n" + } else { + body = "postMessage({ source: \"http\", path: \"\(jsStringLiteral(path))\" });\n" + } + startResponse("200 OK", [("Content-Type", "application/javascript; charset=utf-8")]) + sendBody(body.data(using: .utf8) ?? Data()) + return + } + // ── MIME-gate routes ────────────────────────────── if path == "/esm/html-fallback.mjs" { // The SPA-fallback shape: an unknown path answered with the