Repository navigation
refactor(runtime): one URL parse for every http(s) module entry point - #2169
edusperoni wants to merge 13 commits into
Conversation
|
No actionable comments were generated in the recent review. Walkthrough
Merge Risk:
|
…er URL (#2168) ### Description A module loaded over `http(s)` now resolves the specifiers it imports the way a browser does, for static `import` and `import()` alike, and it can no longer reach the app's filesystem implicitly. **Resolution follows the HTML module-specifier rules, through the WHATWG URL parser** (ada, the parser behind `new URL()`): - Only `/`, `./` and `../` prefixes are relative (`//host/x` is a `/` form). Anything else is an absolute URL if it parses as one, and a bare specifier otherwise. So `.x`, `.` and `..` are bare. - Dot segments and `\` resolve as in a browser, and the scheme is lowercased, so `HTTP://host/x` is an http URL. - The authority (userinfo, host, port) keeps the spelling the importer's URL, or the specifier, wrote. Dev tooling compares the module URLs the runtime reports against the origin it was configured with, verbatim. - The query is kept: `import('./x.js?v=1')` and `import('./x.js?v=2')` are two modules, as they are for a static import. **No implicit filesystem fallback from an HTTP module.** The shared resolver (graph walk, static resolve callback, `import()` callback) refuses these before anything is fetched or probed on disk: - a relative, root-relative or scheme-relative specifier that does not form an `http(s)` URL against the importer's URL; - an unmapped bare specifier, instead of falling back to `<app root>/<spec>`; - `~/x`. The errors name the specifier, the importer and what to use instead, e.g.: ``` Cannot resolve module specifier "lodash" imported from http://host/src/app.js: it is not in the import map (bare specifiers from an HTTP module must be mapped). ``` An unmapped specifier with another scheme (`data:`, `foo:bar`, `file:/x`) fails as `Cannot find module` without a disk lookup. Still allowed from an HTTP module: `ns:`/`node:` builtins, absolute `http(s)` URLs, an explicit `file:///…` URL, `blob:nativescript/…` URLs, and anything the import map maps. A mapped target is never refused, and a relative or root-relative target resolves against the importer's URL. `createRequire(<file path>)` stays the explicit way for an HTTP module to reach on-disk modules. **An import-map entry keyed by a module's own URL** never changes how that module's imports resolve. An HTTP module mapped to a file stays an HTTP importer, and a file module whose `file:///app/…` URL (or a prefix of it) is a map key stays a file importer. `docs/ns-builtin-modules.md` gains a "Specifier resolution" section for HTTP importers. #### Notes for review - **Import-map lookup of a query, from a file module.** On Android, a file module's static `import 'pkg?x'` and its `import('pkg?x')` both look `pkg?x` up in the map as written. The map is consulted before the query is dropped for the on-disk path, which is already how `main` works. A new spec pins it, and the docs state it. On iOS after NativeScript/ios#586, `import()` from a file module drops the query before the lookup, while a static import does not. The two platforms therefore differ for `import()` from a file module. This is one of the cross-platform decisions tracked in #2020; this PR doesn't change it. Note that #2020's description of the Android side predates this check. - File modules resolve exactly as before. ### Does your commit message include the wording below to reference a specific issue in this repo? No issue. ### Related Pull Requests Mirrors NativeScript/ios#586 (code, specs and the docs section). Part of a stack of six; each PR targets the branch below it: 1. #2168 `fix/http-importer-specifiers`: specifier resolution from HTTP importers (**this PR**, base `main`) 2. #2169 `refactor/module-url-parse`: one URL parse for every http(s) entry point 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. 21 new specs in `testEsmHttpLoader.js`, served by new `ModuleTestServer` routes and `esm/http-importer/`, `esm/self-mapped-*/` and `esm/query-map/` fixtures: - `./`, `../`, root- and scheme-relative `import()` load the URLs a browser computes, and the query is part of the module's identity. - Unmapped static and dynamic bare imports, `~/` and an other-scheme `import()` are refused. Same-named fixtures exist on disk, and an evaluation flag in each proves nothing was read. - Builtins, an explicit `file://` URL, import-map entries (any target form, including a relative one) and `blob:nativescript` URLs still load. - A module whose own URL is a map key (HTTP mapped to a file; a file module's exact and prefix entries) keeps its importer kind. - `.x`, `.` and `..` are refused as bare, statically and from `import()`. - Every spelling of one URL is one module, from `import()` and from a static import. Dot segments, `\` and an uppercase scheme normalize as the URL parser does. An importer served from a non-canonically spelled origin keeps that spelling in what it resolves. - A file module looks a static import's and an `import()`'s query up in the map as written. 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** * HTTP(S) modules now resolve relative and root-absolute imports against their URL, while import maps can rewrite specifiers and provide URL-relative targets. * Import resolution now handles built-in modules, file and blob URLs, and URL normalization consistently. * **Bug Fixes** * Unmapped bare and `~/` imports from HTTP modules are rejected with clearer errors instead of being treated as file paths. * File-based modules retain file-based resolution when their own URL is mapped. * **Documentation** * Clarified import-map behavior and documented HTTP module specifier resolution. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
Records what the loader does today for the URL shapes dev servers emit, both as registry keys (with and without a tooling-shaped canonicalization vocabulary) and as loaded modules reached from a file module directly and through an import-map entry: import.meta.url, getLoadedModuleUrls(), the request target the server saw, and eviction by invalidateModules. Ports NativeScript/ios@3fcad404 (part of NativeScript/ios#609).
IsHttpRegistryKey, ParseModuleUrl and the written-authority rule move out of ModuleInternalCallbacks.cpp into ModuleUrl, which also gains NormalizeHttpModuleUrl: the spelling the loader gives an absolute http(s) module URL, falling back to the input itself for an HTTP-prefixed string the URL parser rejects. HttpLoader's string repair of the same name, which the next commits retire, becomes RepairLegacyHttpModuleUrl. ParseModuleUrl now rebuilds the written-authority href by replacing only the authority inside the parser's href. Rebuilding from the pathname, search and hash getters lost a bare trailing '?' or '#', so the re-parse check failed and the parser's lowercased host replaced the written one. Ports NativeScript/ios@ae45c1ff (part of NativeScript/ios#609).
…rser Every route by which an absolute http(s) URL enters the loader now classifies and spells it with NormalizeHttpModuleUrl: the registry key (CanonicalizeHttpUrlKey and CanonicalizeRegistryKey, hence invalidateModules, import.meta.url and getLoadedModuleUrls), a specifier or import-map target from any importer, the dynamic import()'s HTTP branch, the graph-walk root, 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. From a file module, HTTP://h/x and http:/h/x are now http URLs as they already were from an HTTP module, dot segments resolve before the fetch, and characters the parser percent-encodes are encoded in the key. The authority keeps its written spelling. An HTTP-prefixed string the parser rejects stays an HTTP URL in its raw spelling. Ports NativeScript/ios@ed556e1c (part of NativeScript/ios#609).
Nothing feeds the loader a file://http(s):// wrapper, a collapsed http:/ scheme or a URL embedded in a joined path any more, so the wrapper unwrap in CanonicalizeHttpUrlKey, the string repair HttpLoader exported for IsHttpModulePath, CanonicalizeRegistryKey and the worker entry, the resolver's collapsed-specifier repair and HttpUrlEmbeddedInPath all go. A collapsed http:/host still keys as http://host because the URL parser reads it that way; a wrapped file://http://... is a file: URL that names no file, so import() of it rejects without fetching. The fixture server counts the requests it receives per target and reports them at /esm/request-stats.json, so a spec can prove nothing was fetched. Ports NativeScript/ios@28850ec1 (part of NativeScript/ios#609).
…y gate The allowlist compares fetched URLs, which the loader now spells with the URL parser (dot segments resolved, characters such as non-ASCII percent-encoded). Each security.remoteModuleAllowlist entry is spelled the same way once, when the allowlist is loaded, with the written authority kept; an entry that is not an http(s) URL stays verbatim. The prefix-and-boundary rule is unchanged. The rule is factored into RemoteUrlMatchesAllowlist, which IsRemoteUrlAllowed applies, and debuggable builds expose it on ns:module as remoteUrlMatchesAllowlist(url, entries) so it can be tested; release builds omit the member. Ports NativeScript/ios@e79bf93d (part of NativeScript/ios#609).
…eys they match A scope key matches the importing module's registry key by plain prefix, and http(s) registry keys are spelled by the URL parser, so a scope written with dot segments or a non-ASCII segment matched nothing. An http(s) scope key is now spelled the same way when the map is installed, ending in '/' exactly when it was written so; other scope keys (app paths) and imports keys stay as written. Ports NativeScript/ios@0d282683 (part of NativeScript/ios#609).
NormalizeHttpModuleUrl rejects a string that cannot be an http(s) URL from its first character instead of attempting a parse, so file paths pay nothing for it. ParseModuleUrl returns the parser's href unchanged when the written authority already matches it, skipping the rebuild and its re-parse. CanonicalizeHttpUrlKey splits into the spelling step and CanonicalizeNormalizedHttpUrlKey, which applies the vocabulary to an already spelled URL. CanonicalizeRegistryKey, the graph walk (enqueue, fetch completion, root), the dynamic-import HTTP branch, LoadESModule and LoadHttpModuleForUrl, whose callers pass resolved URLs, spell a URL at most once. Ports NativeScript/ios@02e939dd (part of NativeScript/ios#609).
Script origins of classic scripts, file ES modules and JSON modules, import.meta.url and the worker inspector URL each built their own file:// URL from a path. ReportedModuleUrl in ModuleUrl now does it for all of them: an http(s) URL in the loader's spelling, tested first so a string the loader reads as an http(s) URL is never prefixed with file://; any other string that carries a scheme unchanged; otherwise file:// plus the absolute path (file:///app/ when empty). The outputs are unchanged except the worker inspector URL, which for an http(s) script is now the normalized URL and for any other scheme-carrying script is the script string itself rather than a file:// prefix glued onto it. The docs no longer describe the file://http... string, which is not a form the loader accepts. Ports NativeScript/ios@e6b5bf02 and NativeScript/ios@b684e7bb (part of NativeScript/ios#609). Android reports file URLs with the absolute path, so there is no base-directory stripping.
…read it exactly A non-empty security.remoteModuleAllowlist array stays in force 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 falling back to allowing every URL. Only an absent, non-array or empty allowlist allows every URL. AppConfig reads the array with optJSONArray and keeps each item as-is, null for a non-string item; optString would turn 42 into "42" and null into "null". A non-array value no longer aborts the rest of the package.json read. The items reach the native gate through GetStringRegion and an exact UTF-16 to UTF-8 conversion instead of JNI modified UTF-8, so U+0000 and supplementary characters 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 part way leaves remote modules disabled. Runtime.isRemoteUrlAllowed forwards to the native gate; the separate Java matcher is removed. ns:module.remoteUrlMatchesAllowlist (debug only) runs the same rule on an explicit list.
The import-map parser read keys, targets, scope keys and section names through Utf8Value, so an embedded U+0000 cut them short, and a cut-short target or scope key is broader than written. They now go through an exact UTF-16 to UTF-8 conversion and are kept whole: a specifier key or scope key containing U+0000 matches only those exact bytes. A target containing U+0000 is rejected with a TypeError when the map is validated, since resolving it as a path or fetching it as a URL would end it there. V8's JSON parser accepts lone surrogates, which have no UTF-8 form; a key, target or scope key holding one is rejected as not a string.
The static resolver, the import() callback and the graph walk read a specifier through Utf8Value as a C string, so everything after a U+0000 was dropped and a different module loaded. They now read it sized by length, and a specifier containing U+0000 is refused from every importer: the static resolver throws and import() rejects with an Error reading `Cannot resolve module specifier "<spec>": a module specifier must not contain U+0000`, U+0000 shown as the text \u0000. The graph walk skips such a specifier and leaves the refusal to the resolver at link time; nothing is fetched. The test server escapes U+0000 in the JS string literals it generates.
…scope An import-map scope key such as `http://host/a/..` parses to `http://host/`. Dropping the parser's trailing slash whenever the written key lacked one turned that into the prefix `http://host`, which also matches referrers on `http://host.evil/`; `http://host/a/.` likewise matched `/ab/...`. Only a key written with no path at all now loses the parser's slash.
309dfd4 to
5837321
Compare
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 holdsIsHttpRegistryKey,ParseModuleUrl,NormalizeHttpModuleUrlandReportedModuleUrl, which used to be static helpers spread overModuleInternalCallbacks.cppandHttpLoader.cpp.ParseModuleUrlnow 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.
NormalizeHttpModuleUrlspells all of these:CanonicalizeHttpUrlKey,CanonicalizeRegistryKey, henceinvalidateModules,import.meta.urlandgetLoadedModuleUrls());import()HTTP branch, the graph-walk root and the synchronous fallback fetch;LoadESModuleroots, the worker entry URL and therequire()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:
file://http(s)://…unwrap;RepairLegacyHttpModuleUrland its callers);HttpUrlEmbeddedInPath.A collapsed
http:/host/xstill keys ashttp://host/x, because the URL parser reads it that way. A wrappedfile://http://…is afile:URL that names no file:import()rejects without fetching.ModuleTestServergained/esm/request-stats.json, so a spec can prove nothing was fetched.One place builds the reported URL.
ReportedModuleUrlbuilds the script origin,import.meta.urland the worker inspector URL. The output is unchanged except for the worker inspector URL. That URL used to gluefile://onto an http(s) or other-scheme script string; it is now that URL.Remote-module allowlist (
security.remoteModuleAllowlist):https://cdn.example/modules/no longer matches…/modules/../../x.jsor%2e%2eforms. An entry that is not an http(s) URL stays verbatim, and the prefix-and-boundary rule is unchanged.AppConfigreads the array withoptJSONArray;optStringwould have turned42into"42". The items reach native code throughGetStringRegionand 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.InitializeSecurityConfigbuilds the config in locals and commits it at the end, so a failure partway through leaves remote modules disabled.package.jsonread.Import maps.
/exactly when it was written so. A key with dot segments, an uppercase scheme or non-ASCII now matches.http://host/a/..must not widen to the prefixhttp://host, which would also matchhttp://host.evil/. Only a key written with no path at all drops the parser's trailing slash.configureLoaderthrow<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, soimport("./a.mjs\0junk")loaded./a.mjs. Now:import()rejects, withCannot resolve module specifier "<spec>": a module specifier must not contain U+0000(U+0000 shown as\u0000);Java API changes (no deprecation shim):
AppConfig.getRemoteModuleAllowlist()(theList<String>getter) is removed.Runtime.getRemoteModuleAllowlist()(stillString[]) returns the items as read, with anullslot for a non-string item, ornullwhen the list is not in force (absent, not an array, or empty).Runtime.isRemoteUrlAllowedforwards 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
security.remoteModuleAllowlistis 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 (refactor(runtime): one URL parse for every http(s) module entry point ios#609); changing it needs a decision on both platforms.main. The transport PR later in this stack keeps the behaviour, and OkHttp is configured to match it.new Worker("./x.js")/"../x.js"path from an HTTP module against the module's URL (item 2 of fix(runtime): U+0000 in specifiers, HTTP-relative worker paths, file-only import.meta.dirname ios#614) is not handled here;package.jsonmainhardening;import.meta.dirnamebeing absent for URL-keyed modules. Android still gives the URL cut at its last/.package.jsonread is covered separately, throughAppConfig.getRemoteModuleAllowlistArray()on generated config directories.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:
fix/http-importer-specifiers: specifier resolution from HTTP importersrefactor/module-url-parse: one URL parse for every http(s) entry point (this PR)perf/http-module-streaming-compile: compile large HTTP modules off the JS threadfix/http-module-fetch-budget: bound fetches by the graph walk's deadlineperf/http-module-transport: persistent connections, per-host-class caps, OkHttp transportfeat/http-module-cache-controls: HTTP module cache controlsDoes your pull request have unit tests?
Yes.
import.meta.url,getLoadedModuleUrls(), the request target the server saw, and eviction byinvalidateModules. The rest of the PR keeps that table unchanged.testEsmHttpLoader.jscovers:file://http…URL is not unwrapped and nothing is fetched;require()of URLs refused whatever the scheme case;?/#authority fix;import()whose map target resolves to nothing;testNsModule.js: key spelling, the collapsed scheme,file://http…not read as http, and the tooling-shaped vocabulary.testRemoteModuleSecurity.js:package.jsonread: absent, non-array and empty lists are not in force; null slots; U+0000 and lone surrogates kept exactly;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, atfeat/http-module-cache-controls21f87a8.This stays a draft until the stack has been run against a real Vite dev session on Android, which has not happened yet.
Summary by CodeRabbit
require().