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 7c9a9d5f..f46f4038 100644 --- a/NativeScript/runtime/HttpLoader.h +++ b/NativeScript/runtime/HttpLoader.h @@ -58,13 +58,8 @@ 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); +// 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. @@ -151,4 +146,27 @@ bool IsRemoteModulesAllowed(); // (or all URLs if the allowlist is empty). bool IsRemoteUrlAllowed(const std::string& url); +// 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 533da2a9..8a3f30aa 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" @@ -32,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`. // @@ -54,6 +55,41 @@ static bool RemoteUrlMatchesAllowlistEntry(const std::string& url, const std::st return next == '/' || next == '?' || next == '#'; } +static std::string NormalizeRemoteModuleAllowlistEntry(const std::string& entry) { + const std::string url = NormalizeHttpModuleUrl(entry); + return url.empty() ? entry : url; +} + +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; + } + } + return false; +} + static void InitializeSecurityConfig() { std::call_once(s_securityConfigInitFlag, []() { @autoreleasepool { @@ -69,18 +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(std::string([str UTF8String])); - } - } - } - } + s_remoteModuleAllowlist = RemoteModuleAllowlistFromConfig(security[@"remoteModuleAllowlist"]); } }); } @@ -104,18 +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; - } - - for (const std::string& entry : s_remoteModuleAllowlist) { - if (RemoteUrlMatchesAllowlistEntry(url, entry)) { - return true; - } - } - - return false; + return RemoteUrlAllowedByAllowlist(url, s_remoteModuleAllowlist); } // ───────────────────────────────────────────────────────────── @@ -127,38 +141,15 @@ 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) { + const std::string normalizedUrl = NormalizeHttpModuleUrl(url); + return normalizedUrl.empty() ? url : CanonicalizeNormalizedHttpUrlKey(normalizedUrl); } -std::string CanonicalizeHttpUrlKey(const std::string& url) { +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(); - // 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://"))); - } - if (!(StartsWith(normalizedUrl, "http://") || StartsWith(normalizedUrl, "https://"))) { - return normalizedUrl; - } // 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..f957a3e6 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" @@ -75,38 +76,14 @@ 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 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://")); - } - - 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; -} - static bool IsHttpModulePath(const std::string& path) { - std::string normalized = NormalizeHttpModuleUrl(path); - return StartsWith(normalized, "http://") || StartsWith(normalized, "https://"); + return !NormalizeHttpModuleUrl(path).empty(); } static std::string CanonicalizeModulePath(const std::string& path) { - if (IsHttpModulePath(path)) { - return CanonicalizeHttpUrlKey(NormalizeHttpModuleUrl(path)); + const std::string url = NormalizeHttpModuleUrl(path); + if (!url.empty()) { + return CanonicalizeNormalizedHttpUrlKey(url); } return NormalizePath(path); @@ -534,7 +511,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()); @@ -986,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); @@ -1042,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); @@ -1489,9 +1463,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 f0211dd0..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); @@ -236,6 +238,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 a5f1895c..6b226d2a 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); @@ -778,23 +765,21 @@ 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 (IsHttpRegistryKey(key) || StartsWith(key, "file://http://") || - StartsWith(key, "file://https://")) { - registryKey = CanonicalizeHttpUrlKey(key); + // 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. + const std::string httpUrl = NormalizeHttpModuleUrl(key); + if (!httpUrl.empty()) { + registryKey = CanonicalizeNormalizedHttpUrlKey(httpUrl); classification = "http"; } else if (StartsWith(key, "file://")) { registryKey = NormalizePath(FileURLToPath(key)); @@ -834,7 +819,7 @@ static bool ShouldTraceRegistryKey(const std::string& rawKey, const std::string& return v8::MaybeLocal(); } auto& registry = moduleState->registry; - 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()); @@ -911,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; @@ -927,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. @@ -951,6 +944,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) { @@ -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; @@ -1023,7 +1036,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)); } } } @@ -1560,85 +1573,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 @@ -1682,28 +1616,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 @@ -1726,10 +1638,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()); @@ -1814,9 +1723,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; } @@ -1939,14 +1849,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"); @@ -2084,7 +1986,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) { @@ -2206,10 +2108,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; } @@ -2299,9 +2202,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; @@ -2316,10 +2220,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); @@ -2329,7 +2236,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); } @@ -2845,7 +2751,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); } @@ -3162,10 +3068,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); - const auto parsedResource = ada::parse(resourceUrl, nullptr); - if (parsedResource && HasHttpScheme(*parsedResource)) { - dynamicReferrerKey = CanonicalizeRegistryKey(resourceUrl); + if (!NormalizeHttpModuleUrl(resourceName).empty()) { + dynamicReferrerKey = CanonicalizeRegistryKey(resourceName); } else { const ModuleResolution referrer = ResolveSpecifierToPath(resourceName, std::string(), ImportMapLookup::kSkip); @@ -3184,7 +3088,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) { @@ -3214,9 +3118,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()); @@ -3571,9 +3475,9 @@ 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); + 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 @@ -3758,12 +3662,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)))) @@ -3834,9 +3738,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 @@ -4323,6 +4224,51 @@ 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` 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(); + @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))); + } + }; + 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/ModuleUrl.cpp b/NativeScript/runtime/ModuleUrl.cpp new file mode 100644 index 00000000..62340321 --- /dev/null +++ b/NativeScript/runtime/ModuleUrl.cpp @@ -0,0 +1,166 @@ +#include "ModuleUrl.h" + +#include + +#include "RuntimeConfig.h" +#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; + } + 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 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; + } + return result; +} + +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(); + } + 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/"; + } + // 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)) { + return keyOrPath; + } + // 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 new file mode 100644 index 00000000..359d429b --- /dev/null +++ b/NativeScript/runtime/ModuleUrl.h @@ -0,0 +1,49 @@ +#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); + +// 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 b19b0b7c..2e6d2aa9 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,7 @@ static void PostThreadEndedNotification(Isolate* mainIsolate, std::weak_ptrworkerId_, isolate, CFRunLoopGetCurrent(), url); 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 ad4511f4..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" } }); @@ -1433,14 +1464,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()); }); @@ -1934,6 +1966,110 @@ 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("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) { + 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(); + 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) { @@ -2172,6 +2308,195 @@ 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(); + }); + }); + }); + + 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 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 = ""; + 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. @@ -2184,6 +2509,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 +2518,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") { @@ -2216,26 +2612,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 () { @@ -2249,6 +2638,54 @@ 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("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("\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"); + 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]); + }); + }); + }); + + 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/RemoteModuleSecurityTests.js b/TestRunner/app/tests/RemoteModuleSecurityTests.js index a926ff93..71903dfd 100644 --- a/TestRunner/app/tests/RemoteModuleSecurityTests.js +++ b/TestRunner/app/tests/RemoteModuleSecurityTests.js @@ -227,6 +227,135 @@ 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], + ]); + }); + + 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") { + 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/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"; diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index 35bc4ee9..e9fa668f 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -622,13 +622,23 @@ 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 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 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: @@ -657,7 +667,10 @@ 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 +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 global mapping for one subtree and fall through to it everywhere else. The @@ -691,11 +704,16 @@ 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 -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`. The mechanism — fragment strip, cache-buster param drop, param sort — is the runtime's; the *vocabulary* is server policy, supplied here: @@ -986,8 +1004,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 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. } 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 */,