Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions NativeScript/runtime/Helpers.h
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
#include <cstdint>
#include <cstdio>
#include <functional>
#include <optional>
#include <string>
#include <vector>

Expand Down Expand Up @@ -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<std::string> 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<size_t>(byteCount), '\0');
CFStringGetBytes(str, range, kCFStringEncodingUTF8, 0, false,
reinterpret_cast<UInt8*>(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];
Expand Down
32 changes: 25 additions & 7 deletions NativeScript/runtime/HttpLoader.h
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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<std::string> 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
95 changes: 43 additions & 52 deletions NativeScript/runtime/HttpLoader.mm
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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<std::string> s_remoteModuleAllowlist;
static RemoteModuleAllowlist s_remoteModuleAllowlist;

// Returns true when `url` is authorized by allowlist `entry`.
//
Expand All @@ -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<std::string> 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 {
Expand All @@ -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"]);
}
});
}
Expand All @@ -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);
}

// ─────────────────────────────────────────────────────────────
Expand All @@ -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 =
Expand Down
50 changes: 13 additions & 37 deletions NativeScript/runtime/ModuleInternal.mm
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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());
Expand Down Expand Up @@ -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<v8::String> sourceText = ModuleInternal::WrapModuleContent(isolate, canonicalPath);
Expand Down Expand Up @@ -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<v8::String> sourceText = ModuleInternal::WrapModuleContent(isolate, canonicalPath);
auto* cacheData = ModuleInternal::LoadScriptCache(canonicalPath, ScriptCacheKind::kEsModule);
Expand Down Expand Up @@ -1489,9 +1463,11 @@ throw NativeScriptException("Module evaluation interrupted by isolate terminatio

Local<Value> 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) {
Expand Down
4 changes: 4 additions & 0 deletions NativeScript/runtime/ModuleInternalCallbacks.h
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,8 @@ v8::MaybeLocal<v8::Module> 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<v8::Module> LoadHttpModuleForUrl(
v8::Isolate* isolate, v8::Local<v8::Context> context,
const std::string& requestedUrl);
Expand Down Expand Up @@ -236,6 +238,8 @@ void SetVolatilePatterns(const std::vector<std::string>& 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
Expand Down
Loading
Loading