Skip to content

fix(runtime): U+0000 in specifiers, HTTP-relative worker paths, file-only import.meta.dirname - #614

Merged
edusperoni merged 6 commits into
mainfrom
fix/loader-nul-specifiers-worker-dirname
Dec 2, 2026
Merged

edusperoni merged 6 commits into
mainfrom
fix/loader-nul-specifiers-worker-dirname

Conversation

@edusperoni

@edusperoni edusperoni commented Dec 1, 2026 •

Copy link
Copy Markdown
Collaborator

What

Three small fixes in the ES module loader:

  1. Module specifiers and package.json main are no longer read as C strings.
    • The static resolver, the dynamic import() callback and the async graph walk read the specifier through one length-exact helper (ModuleSpecifierUtf8).
    • A specifier that contains U+0000 is rejected. A static import fails to link with an Error, and import() rejects with an Error. The graph walk skips the specifier, so nothing is fetched or read from disk for it.
    • The message is Cannot resolve module specifier "<spec with \u0000 escaped>": a module specifier must not contain U+0000. It is the same in Debug and Release.
    • ModuleInternal::ResolvePathFromPackageJson (the require() of a package directory):
      • A package.json whose top level is not a JSON object is treated like invalid JSON.
      • A main that is not a string is ignored and resolution falls back to index, as Node does.
      • A main that has no exact UTF-8 form, or that contains U+0000, cannot be located. These cases end in the usual Unable to locate main entry in <package.json> error.
  2. new Worker("./x.js") / new Worker("../x.js") called from a module loaded over HTTP resolves against that module's URL.
    • The path goes through the WHATWG URL parser (ParseModuleUrl), and the worker loads from the resulting http(s) URL through the normal loader path.
    • If the result is not an http(s) URL, the constructor throws. An HTTP caller never falls back to the app root.
    • This extends NativeScript's existing caller-relative rule for relative worker paths to HTTP modules. It is not web behaviour: a browser resolves a Worker URL against the document's base URL.
  3. import.meta.dirname is defined only for file-backed modules, as in Node. For an http(s), blob: or other URL-keyed module the property is absent ("dirname" in import.meta === false). File modules keep their current value.

Why

  • Specifiers. import("./a.mjs\0junk") loaded ./a.mjs, because the specifier went through v8::String::Utf8Value and was then used as a C string. The same truncation happened in a static import and in the graph walk's prefetch.
  • package.json. ResolvePathFromPackageJson used main with no type checks. On the unfixed runtime, three of the new fixtures abort the process on a require():
    • a numeric main: -[NSPathStore2 stringByAppendingPathComponent:] raised an unrecognized-selector exception;
    • a main containing U+0000: std::string was constructed from a NULL UTF8String;
    • a top-level JSON array: objectForKey: was sent to an NSArray.
  • Workers. From http://host/src/feature/a.ts, new Worker("./w.js") loaded <app>/w.js from disk. Only file:// and / callers got caller-relative resolution; every other caller fell through to the app-root join.
  • import.meta.dirname. For a URL module the value was the key cut at its last /, even when that slash was inside the query. For example, http://host/ns/asm?path=/src/app/main.ts gave http://host/ns/asm?path=/src/app.

Behaviour changes

Case Before After
import x from "./a.mjs\0junk" (file or HTTP importer) loads ./a.mjs link fails: Error naming the U+0000 rule
import("./a.mjs\0junk") (file or HTTP importer) loads ./a.mjs promise rejects with that Error
graph walk of an HTTP module with such a static import prefetches the truncated URL nothing fetched
require() of a package whose main is not a string (e.g. 42) process abort resolves index
require() of a package whose main contains U+0000 process abort Unable to locate main entry in …/package.json
require() of a package whose package.json is a JSON array process abort Unable to locate main entry in …/package.json
require() of a package whose main is a lone surrogate ("a\ud800b") Unable to locate main entry (NSJSONSerialization rejects the file) unchanged
new Worker("./x.js") / "../x.js" from an HTTP module <app>/x.js (or <app>/../x.js) from disk the URL resolved against the module's URL, fetched over HTTP
new Worker(new URL("./x.js", import.meta.url)) from an HTTP module works unchanged
import.meta.dirname in an http(s) module URL cut at its last / property absent
import.meta.dirname in a blob: module the blob URL property absent
import.meta.dirname in a file module /app/<dir> unchanged

How it was verified

The new specs are in TestRunner/app/tests/LoaderHardeningTests.js and TestRunner/app/tests/HttpEsmLoaderTests.js. The test server gained /esm/meta/… and /esm/worker/… routes, and its JS string escaping now covers U+0000.

On the unfixed runtime (specs only):

  • Three package specs aborted the app. Each was found by skipping the previous one and rerunning: non-string main, then U+0000 main, then the array package.json.
  • With those three skipped, these specs failed:
    • both U+0000 specs from a file importer, where the decoy module was evaluated;
    • both U+0000 specs from an HTTP importer, where the truncated URL was requested once;
    • the ./ worker spec and the ../ worker spec, where the decoy at the app-root join ran and the server saw no request;
    • the HTTP import.meta.dirname spec and the blob: import.meta.dirname spec;
    • a spec for a file: worker URL from a file module, which is not part of this PR (see Not covered).
  • These new specs passed on unfixed code, as expected:
    • the lone-surrogate main spec;
    • the strengthened file-module import.meta.dirname spec;
    • new Worker(new URL("./x.js", import.meta.url)) from an HTTP module;
    • new Worker("<absolute http URL>") from a file module.

With the fixes:

Not covered

  • U+0000 in require(), createRequire() and file new Worker() paths. This PR does not change these paths.
    • Checked by reading the code, not with specs.
    • The path is cut at the NUL at its first conversion ([NSString stringWithUTF8String:x.c_str()] or ToV8String(isolate, x.c_str())), so a different file can load.
    • From an HTTP module, a ./ or ../ worker path now goes through the URL parser instead, which percent-encodes the NUL.
  • From an HTTP module, worker paths that are /-rooted or bare are unchanged. A /x path is still treated as a container-absolute file path, and bare and ~/ paths still resolve as before.
  • Deliberate deviation for HTTP importers. A browser percent-encodes U+0000 to %00 when it resolves a specifier against an http(s) base. The loader instead rejects such a specifier from every importer.
  • file: worker URLs from a file module. new Worker(new URL("./x.js", import.meta.url)) gives the constructor file:///app/…. That string is treated as a bare tns_modules name and fails with "Failed to resolve module". This is the behaviour on main and is not changed here.
  • App's own main entry. ResolveMainEntryFromPackageJson already ignores a non-string main.
    • A main containing U+0000 is unchanged and was not reproduced.
    • It passes that main to the same stringByAppendingPathComponent: / UTF8String sequence that aborted for a package main.
    • There is no spec, because it would require changing the test app's own package.json.
  • Worker constructor throw. When ./ or ../ from an HTTP module does not resolve to an http(s) URL, the constructor throws. No spec covers this branch.
  • Release run. The suite ran in Debug only; the Release configuration was compiled, not run.
    • The U+0000 error text is built the same way in both configurations, by reading the code.
    • An HTTP-relative worker loads through the same loader path as an absolute http(s) worker URL, so the Release remote-module rules apply to it unchanged.
  • Empty registry key. A module with an empty registry key still reports import.meta.url as file:///app/ and import.meta.dirname as /app.
  • Builtins. No spec observes import.meta of a builtin module.
  • import.meta.filename is not added.

@coderabbitai

coderabbitai Bot commented Dec 1, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 19 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used all 2 included reviews currently available.

Learn how review limits work.

Review configuration:

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: aa9f0b29-b936-4ecd-8b1b-0e18a6878b36
Commits

Reviewing files that changed from the base of the PR and between 8e013af and 4021b2a.

Files selected for processing: 20

  • NativeScript/runtime/ModuleInternal.mm
  • NativeScript/runtime/ModuleInternalCallbacks.mm
  • NativeScript/runtime/Runtime.mm
  • NativeScript/runtime/Worker.mm
  • TestRunner/app/tests/HttpEsmLoaderTests.js
  • TestRunner/app/tests/LoaderHardeningTests.js
  • TestRunner/app/tests/esm/relative/meta.mjs
  • TestRunner/app/tests/loaderhardening/nulDecoyDynamic.mjs
  • TestRunner/app/tests/loaderhardening/nulDecoyStatic.mjs
  • TestRunner/app/tests/loaderhardening/nulDynamicImporter.mjs
  • TestRunner/app/tests/loaderhardening/nulStaticImporter.mjs
  • TestRunner/app/tests/loaderhardening/pkgArrayJson/index.js
  • TestRunner/app/tests/loaderhardening/pkgArrayJson/package.json
  • TestRunner/app/tests/loaderhardening/pkgNonStringMain/index.js
  • TestRunner/app/tests/loaderhardening/pkgNonStringMain/package.json
  • TestRunner/app/tests/loaderhardening/pkgNulMain/index.js
  • TestRunner/app/tests/loaderhardening/pkgNulMain/package.json
  • TestRunner/app/tests/loaderhardening/pkgSurrogateMain/index.js
  • TestRunner/app/tests/loaderhardening/pkgSurrogateMain/package.json
  • TestRunnerTests/TestRunnerTests.swift
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@edusperoni
edusperoni merged commit b659f7b into main Dec 2, 2026
14 checks passed
@edusperoni
edusperoni deleted the fix/loader-nul-specifiers-worker-dirname branch December 2, 2026 12:24
edusperoni added a commit to NativeScript/android that referenced this pull request Dec 3, 2026
…#2169)

### Description

Follow-up to the previous PR in the stack. Every route by which an
absolute `http(s)` module URL enters the ES module loader now goes
through one parse: the WHATWG URL parser, with the authority kept as
written. The hand-written tolerance for malformed URL spellings is
removed. The stack's previous PR gave specifiers from an HTTP importer
the parser's spelling. Every other route used the raw string, so one
module could get two identities.

**One shared unit, `ModuleUrl.{h,cpp}`.** It holds `IsHttpRegistryKey`,
`ParseModuleUrl`, `NormalizeHttpModuleUrl` and `ReportedModuleUrl`,
which used to be static helpers spread over
`ModuleInternalCallbacks.cpp` and `HttpLoader.cpp`. `ParseModuleUrl` now
swaps only the authority inside the parser's href. Rebuilding from the
getters lost a bare trailing `?` or `#`, and the lowercased host then
replaced the written one.

**One spelling for every entry point.** `NormalizeHttpModuleUrl` spells
all of these:

- the registry key (`CanonicalizeHttpUrlKey`, `CanonicalizeRegistryKey`,
hence `invalidateModules`, `import.meta.url` and
`getLoadedModuleUrls()`);
- a specifier or import-map target from any importer;
- the `import()` HTTP branch, the graph-walk root and the synchronous
fallback fetch;
- `LoadESModule` roots, the worker entry URL and the `require()` URL
guard.

The fetched URL and the registry key derive from the same string. Each
URL is spelled at most once per key. A string that cannot be an http(s)
URL is rejected from its first character, so file paths pay nothing.

**Legacy forms are gone.** These are deleted:

- the `file://http(s)://…` unwrap;
- the collapsed-scheme repair (`RepairLegacyHttpModuleUrl` and its
callers);
- `HttpUrlEmbeddedInPath`.

A collapsed `http:/host/x` still keys as `http://host/x`, because the
URL parser reads it that way. A wrapped `file://http://…` is a `file:`
URL that names no file: `import()` rejects without fetching.
`ModuleTestServer` gained `/esm/request-stats.json`, so a spec can prove
nothing was fetched.

**One place builds the reported URL.** `ReportedModuleUrl` builds the
script origin, `import.meta.url` and the worker inspector URL. The
output is unchanged except for the worker inspector URL. That URL used
to glue `file://` onto an http(s) or other-scheme script string; it is
now that URL.

**Remote-module allowlist** (`security.remoteModuleAllowlist`):

- Entries are spelled like the URLs they gate when the allowlist is
loaded, with the written authority kept. A path-scoped entry such as
`https://cdn.example/modules/` no longer matches `…/modules/../../x.js`
or `%2e%2e` forms. An entry that is not an http(s) URL stays verbatim,
and the prefix-and-boundary rule is unchanged.
- A configured list stays in force. A non-empty array applies even when
none of its items is usable. An item that is not a string, is empty or
has no exact UTF-8 form matches nothing instead of the list falling back
to allowing every URL.
- Items are read exactly. `AppConfig` reads the array with
`optJSONArray`; `optString` would have turned `42` into `"42"`. The
items reach native code through `GetStringRegion` and an exact
UTF-16→UTF-8 conversion (`ExactUtf8.h`), not JNI modified UTF-8. U+0000
and supplementary characters therefore keep their real bytes, and a lone
surrogate is an unusable item.
- `InitializeSecurityConfig` builds the config in locals and commits it
at the end, so a failure partway through leaves remote modules disabled.
- A non-array value no longer aborts the rest of the `package.json`
read.

**Import maps.**

- An http(s) scope key is spelled like the referrer keys it is
prefix-matched against when the map is installed. It ends in `/` exactly
when it was written so. A key with dot segments, an uppercase scheme or
non-ASCII now matches.
- A dot-segment key such as `http://host/a/..` must not widen to the
prefix `http://host`, which would also match `http://host.evil/`. Only a
key written with no path at all drops the parser's trailing slash.
- Keys, targets and scope keys are read exactly. A key or scope key
containing U+0000 matches only those exact bytes. A target containing
U+0000 makes `configureLoader` throw `<section>: the target for
'<specifier>' must not contain U+0000`, and the previous map stays in
place. A lone surrogate is "not a string".

**Specifiers containing U+0000 are refused** (the specifier part of
NativeScript/ios#614). Before, the static resolver, the `import()`
callback and the graph walk read the specifier as a C string, so
`import("./a.mjs\0junk")` loaded `./a.mjs`. Now:

- a static import fails to link and `import()` rejects, with ``Cannot
resolve module specifier "<spec>": a module specifier must not contain
U+0000`` (U+0000 shown as `\u0000`);
- the graph walk skips such a specifier, so nothing is fetched.

**Java API changes (no deprecation shim):**

- `AppConfig.getRemoteModuleAllowlist()` (the `List<String>` getter) is
removed.
- `Runtime.getRemoteModuleAllowlist()` (still `String[]`) returns the
items as read, with a `null` slot for a non-string item, or `null` when
the list is not in force (absent, not an array, or empty).
- `Runtime.isRemoteUrlAllowed` forwards to the native gate, and the
separate Java matcher is removed.

Debug builds gain `ns:module.remoteUrlMatchesAllowlist(url, entries)`.
It runs the release gate's loading and matching on an explicit list, so
the rule can be tested. Release builds omit it.

#### Notes for review

- **A non-array allowlist still fails open.** When
`security.remoteModuleAllowlist` is absent, not an array or `[]`, every
URL is allowed. A string or object value is the likeliest config
mistake, and it allows every URL. This matches iOS
(NativeScript/ios#609); changing it needs a decision on both platforms.
- **Redirects are not re-checked against the allowlist.** The gate
checks the requested URL. The transport then follows same-protocol
redirects without checking the target. This is already true on `main`.
The transport PR later in this stack keeps the behaviour, and OkHttp is
configured to match it.
- **Only the specifier refusal of NativeScript/ios#614 is ported.** Not
ported:
- resolving a relative `new Worker("./x.js")` / `"../x.js"` path from an
HTTP module against the module's URL (item 2 of NativeScript/ios#614) is
not handled here;
  - the `package.json` `main` hardening;
- `import.meta.dirname` being absent for URL-keyed modules. Android
still gives the URL cut at its last `/`.
- **The authority is never canonicalized.** The host case and default
port are kept as written, as on iOS.
- **The release gate was not run end to end.** The allowlist specs use
the debug-only member, which calls the same loading and matching
functions. The `package.json` read is covered separately, through
`AppConfig.getRemoteModuleAllowlistArray()` on generated config
directories.
- **The last two commits go beyond NativeScript/ios#609.** They are the
U+0000 specifier refusal (from NativeScript/ios#614) and "keep a
dot-segment http(s) scope key from widening its scope". Whether iOS has
the same scope-key widening has not been checked.

### Does your commit message include the wording below to reference a
specific issue in this repo?

No issue.

### Related Pull Requests

Mirrors NativeScript/ios#609; the first nine commits each name the iOS
commit they port. Also ports the U+0000 specifier refusal from
NativeScript/ios#614. The allowlist "stays in force" and
exact-conversion commits port the same items of NativeScript/ios#609. On
Android they also cover the JNI boundary and `AppConfig`.

Part of a stack of six; each PR targets the branch below it:

1. #2168 `fix/http-importer-specifiers`: specifier resolution from HTTP
importers
2. #2169 `refactor/module-url-parse`: one URL parse for every http(s)
entry point (**this PR**)
3. #2170 `perf/http-module-streaming-compile`: compile large HTTP
modules off the JS thread
4. #2171 `fix/http-module-fetch-budget`: bound fetches by the graph
walk's deadline
5. #2172 `perf/http-module-transport`: persistent connections,
per-host-class caps, OkHttp transport
6. #2173 `feat/http-module-cache-controls`: HTTP module cache controls

### Does your pull request have [unit
tests](https://github.com/NativeScript/NativeScript/blob/master/running-tests.md)?

Yes.

- **Pinned first.** The first commit records what the loader does for
the URL shapes dev tooling emits. It covers registry keys with and
without a tooling-shaped vocabulary, and loads from a file module
directly and through an import-map entry. For each it pins
`import.meta.url`, `getLoadedModuleUrls()`, the request target the
server saw, and eviction by `invalidateModules`. The rest of the PR
keeps that table unchanged.
- **`testEsmHttpLoader.js`** covers:
- absolute URLs from a file module, spelled by the parser with the
authority as written;
  - that a `file://http…` URL is not unwrapped and nothing is fetched;
  - `require()` of URLs refused whatever the scheme case;
  - the bare `?`/`#` authority fix;
  - an `import()` whose map target resolves to nothing;
- http(s) scope keys: parser spelling, dot-segment keys not widening,
U+0000;
  - import-map U+0000 and lone-surrogate keys, targets and scopes;
- U+0000 specifiers from file and HTTP importers. Static and dynamic
imports are both refused, with nothing loaded or fetched.
- **`testNsModule.js`**: key spelling, the collapsed scheme,
`file://http…` not read as http, and the tooling-shaped vocabulary.
- **`testRemoteModuleSecurity.js`**:
- the `package.json` read: absent, non-array and empty lists are not in
force; null slots; U+0000 and lone surrogates kept exactly;
- the matching rule through `remoteUrlMatchesAllowlist`: boundary,
dot-segment escape, trailing slash, host compared as written, path
spelling, non-URL entries, empty list, unusable items, U+0000.

Full suite on the top of the stack (`./gradlew
runtestsAndVerifyResults`): 2074 specs, 2068 passed, 0 failed, 6 skipped
(the usual GC, native-module and environment skips), on an API 36 arm64
emulator with OkHttp in the test app, at
`feat/http-module-cache-controls` 21f87a8.

This stays a draft until the stack has been run against a real Vite dev
session on Android, which has not happened yet.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

* **New Features**
* Remote module access now supports URL allowlists, with matching that
respects URL path boundaries.
* Debug builds provide a diagnostic for checking whether a remote URL
matches an allowlist.
* **Bug Fixes**
* Improved HTTP module loading and import-map resolution, including
consistent handling of URL scopes and paths.
* Module specifiers containing invalid characters are rejected instead
of being mistaken for other modules or fetched unexpectedly.
  * HTTP URL modules are no longer accepted through `require()`.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant