Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

fix(workers): reject dynamic imports in service workers

ldm09d62c0b6b926
diff --git a/moli-renderer-v8/src/worker/module_runtime.rs b/moli-renderer-v8/src/worker/module_runtime.rs
index 82fc7bfb3..a6e807973 100644
--- a/moli-renderer-v8/src/worker/module_runtime.rs
+++ b/moli-renderer-v8/src/worker/module_runtime.rs
@@ -3110,6 +3110,22 @@ fn queue_worker_dynamic_import<'s>(
) -> Option<v8::Local<'s, v8::Promise>> {
let resolver = v8::PromiseResolver::new(scope)?;
let promise = resolver.get_promise(scope);
+ // HostLoadImportedModule forbids dynamic imports in service workers,
+ // including modules already present in the static graph. Reject before
+ // resolving the specifier or scheduling any graph fetch.
+ if super::global_scope::get_worker_state(scope).is_some_and(|state| {
+ matches!(
+ state.borrow().global_kind,
+ super::thread::WorkerGlobalKind::Service { .. }
+ )
+ }) {
+ reject_worker_dynamic_import_resolver(
+ scope,
+ resolver,
+ "import() is disallowed on ServiceWorkerGlobalScope.",
+ );
+ return Some(promise);
+ }
let context = scope.get_current_context();
let specifier = specifier.to_rust_string_lossy(scope);
let attributes = worker_import_attributes_key(scope, import_attributes);
diff --git a/moli-renderer-v8/src/worker/thread/tests/modules/specifiers.rs b/moli-renderer-v8/src/worker/thread/tests/modules/specifiers.rs
index 775c648f7..2cf4d344e 100644
--- a/moli-renderer-v8/src/worker/thread/tests/modules/specifiers.rs
+++ b/moli-renderer-v8/src/worker/thread/tests/modules/specifiers.rs
@@ -169,3 +169,61 @@ async fn worker_dynamic_import_rejects_bare_dependencies_as_type_errors_without_
handle.terminate_and_join();
server.assert_no_more_requests();
}
+
+const IMPORT_PROBE: &str = include_str!(concat!(
+ env!("CARGO_MANIFEST_DIR"),
+ "/tests/fixtures/service-worker-dynamic-import.js"
+));
+
+#[tokio::test]
+async fn service_worker_dynamic_import_rejects_cached_and_uncached_modules_without_fetching() {
+ ensure_v8();
+ for kind in [WorkerScriptKind::Classic, WorkerScriptKind::Module] {
+ let mut server = SpecifierServer::start().await;
+ let static_import = match kind {
+ WorkerScriptKind::Classic => "importScripts('./cached.js');",
+ WorkerScriptKind::Module => "import './cached.js';",
+ };
+ let source = format!(
+ r#"{static_import}
+{IMPORT_PROBE}
+serviceWorkerDynamicImportProbe().then(result => console.log(JSON.stringify(result)));
+"#
+ );
+ let mut handle = spawn_test_worker_with_options(
+ service_worker_module_options(source, format!("{}/worker/sw.js", server.url))
+ .with_script_kind(kind),
+ );
+ server
+ .respond(
+ "/worker/cached.js",
+ "200 OK",
+ "text/javascript",
+ "self.staticScriptRuns = (self.staticScriptRuns || 0) + 1;",
+ )
+ .await;
+ loop {
+ match timeout(TIMEOUT, handle.recv()).await.unwrap().unwrap() {
+ WorkerToParentMessage::ServiceWorkerImportedScriptLoaded { .. }
+ | WorkerToParentMessage::SubresourceNetwork(_)
+ | WorkerToParentMessage::PendingSubresourceFetch(_)
+ | WorkerToParentMessage::SubresourceContinue(_) => {}
+ WorkerToParentMessage::Console(message) => {
+ let result: serde_json::Value =
+ serde_json::from_str(message.message.strip_prefix("log: ").unwrap())
+ .unwrap();
+ assert_eq!(
+ result["failures"],
+ serde_json::json!([]),
+ "{kind:?}: {result}"
+ );
+ assert_eq!(result["checks"], 37, "{kind:?}: {result}");
+ break;
+ }
+ other => panic!("expected caught import rejection, got {other:?}"),
+ }
+ }
+ handle.terminate_and_join();
+ server.assert_no_more_requests();
+ }
+}
diff --git a/moli-renderer-v8/tests/fixtures/service-worker-dynamic-import.js b/moli-renderer-v8/tests/fixtures/service-worker-dynamic-import.js
new file mode 100644
index 000000000..9d8203c33
--- /dev/null
+++ b/moli-renderer-v8/tests/fixtures/service-worker-dynamic-import.js
@@ -0,0 +1,58 @@
+async function serviceWorkerDynamicImportProbe() {
+ const result = {checks: 0, failures: []};
+ const check = (name, actual, expected) => {
+ result.checks++;
+ if (actual !== expected) result.failures.push({name, actual, expected});
+ };
+ const NativeTypeError = TypeError;
+ // The restriction belongs to the native global, not its exposed constructor.
+ self.ServiceWorkerGlobalScope = undefined;
+ check('static script executed once', self.staticScriptRuns, 1);
+ const actions = [
+ ['cached script', () => import('./cached.js')],
+ ['uncached script', () => import('./unfetched.js')],
+ ['JSON', () => import('./unfetched.json', {with: {type: 'json'}})],
+ ['CSS', () => import('./unfetched.css', {with: {type: 'css'}})],
+ ['data script', () => import('data:text/javascript,self.dynamicScriptRan=true;export default 1')],
+ ['data JSON', () => import('data:application/json,%7B%22answer%22%3A42%7D', {with: {type: 'json'}})],
+ ['source import', () => import.source('./unfetched.wasm')],
+ ['data source import', () => import.source('data:application/wasm;base64,AGFzbQEAAAA=')],
+ ['Function', () => Function('return import("./function.js")')()],
+ ['eval', () => eval('import("./eval.js")')],
+ ];
+ for (const [label, action] of actions) {
+ let synchronous = true;
+ try {
+ const promise = action();
+ check(label + ': Promise', promise instanceof Promise, true);
+ const settled = promise.then(
+ () => { result.failures.push({name: label + ': import fulfilled'}); },
+ error => {
+ check(label + ': asynchronous rejection', synchronous, false);
+ check(label + ': intrinsic TypeError', Object.getPrototypeOf(error), NativeTypeError.prototype);
+ }
+ );
+ synchronous = false;
+ await settled;
+ } catch (error) {
+ result.failures.push({name: label + ': synchronous exception', error: String(error)});
+ }
+ }
+ check('dynamic script never executed', self.dynamicScriptRan, undefined);
+ check('cached script not reexecuted', self.staticScriptRuns, 1);
+
+ const sentinel = {};
+ let specifierConversions = 0;
+ await import({toString() { specifierConversions++; throw sentinel; }}).then(
+ () => result.failures.push({name: 'specifier conversion fulfilled'}),
+ error => check('specifier exception preserved', error, sentinel)
+ );
+ check('specifier converted once', specifierConversions, 1);
+ let optionReads = 0;
+ await import('./unfetched.js', {get with() { optionReads++; throw sentinel; }}).then(
+ () => result.failures.push({name: 'options conversion fulfilled'}),
+ error => check('options exception preserved', error, sentinel)
+ );
+ check('options read once', optionReads, 1);
+ return result;
+}