mirror of
https://github.com/lexmount/moli.git
synced 2026-11-23 16:02:35 +00:00
fix(script): report dynamic inline errors in the document realm
Extracted from development commit bc8259d5fd.
Adapted to the target branch APIs. Validated with cargo fmt --all, full workspace Clippy (-D warnings), and cargo nextest run --no-fail-fast before committing.
This commit is contained in:
@@ -2002,6 +2002,17 @@ fn execute_committed_inline_classic_script(
|
||||
committed: crate::host::CommittedInlineClassicScript,
|
||||
) {
|
||||
let (node, host_script_handle, source) = committed.into_parts();
|
||||
// An inserted script executes in its Document's main world, including
|
||||
// when a child or isolated world performed the insertion.
|
||||
let default_context = unsafe { &*host_ptr }
|
||||
.page_default_context(scope)
|
||||
.expect("top-level inline script execution requires the page main-world context");
|
||||
let scope = &mut v8::ContextScope::new(scope, default_context);
|
||||
let script_url = runtime.document.url().clone();
|
||||
let base_url = runtime
|
||||
.dom_host
|
||||
.document_base_url_for_handle(runtime.dom_host.document_handle())
|
||||
.unwrap_or_else(|| script_url.clone());
|
||||
let nonce =
|
||||
crate::host::script_element_nonce_for_csp(&runtime.dom_host, node).map(str::to_owned);
|
||||
let request = crate::content_security_policy::ContentSecurityPolicyScriptElementRequest {
|
||||
@@ -2014,19 +2025,25 @@ fn execute_committed_inline_classic_script(
|
||||
) else {
|
||||
return;
|
||||
};
|
||||
let Some(source) = v8::String::new(scope, &source) else {
|
||||
return;
|
||||
};
|
||||
let Some(script) = v8::Script::compile(scope, source, None) else {
|
||||
return;
|
||||
};
|
||||
// Parse errors are reported by running the classic script too. Keep
|
||||
// currentScript set through both compilation and synchronous error reporting,
|
||||
// and contain the exception so the inserting DOM operation can continue.
|
||||
unsafe { &mut *host_ptr }.push_current_inline_script(node);
|
||||
let run_result = crate::script_execution::execute_compiled_script(scope, script);
|
||||
let run_result = crate::script_vm::execute_source_text_on_current_stack(
|
||||
scope,
|
||||
&source,
|
||||
Some(&script_url),
|
||||
Some(&base_url),
|
||||
0,
|
||||
nonce.as_deref(),
|
||||
true,
|
||||
);
|
||||
unsafe { &mut *host_ptr }.pop_current_inline_script(node);
|
||||
if run_result.is_some() {
|
||||
let _ = runtime.enqueue_script_event_lifecycle_work(
|
||||
crate::host::ScriptEventKind::Load,
|
||||
&host_script_handle,
|
||||
if let Err(error) = run_result {
|
||||
debug!(
|
||||
host_script_handle,
|
||||
%error,
|
||||
"dynamic inline classic script execution failed"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
use super::*;
|
||||
|
||||
const DYNAMIC_INLINE_ERRORS: &str = include_str!(concat!(
|
||||
env!("CARGO_MANIFEST_DIR"),
|
||||
"/tests/fixtures/dynamic-inline-errors.js"
|
||||
));
|
||||
|
||||
#[test]
|
||||
fn main_dynamic_inline_script_errors_are_synchronous_and_restore_current_script() {
|
||||
for borrow_child_insertion in [false, true] {
|
||||
let mut vm = new_parsed_test_vm(
|
||||
"https://inline-errors.test/page.html",
|
||||
"<!doctype html><body></body>",
|
||||
);
|
||||
let result: serde_json::Value = serde_json::from_str(
|
||||
&vm.eval(&format!(
|
||||
"JSON.stringify(({DYNAMIC_INLINE_ERRORS})({borrow_child_insertion}))"
|
||||
))
|
||||
.expect("inserted script exceptions must not escape the DOM operation"),
|
||||
)
|
||||
.unwrap();
|
||||
let expected_events = serde_json::json!([
|
||||
"outer:outer",
|
||||
"error:syntax",
|
||||
"returned:syntax:outer",
|
||||
"error:runtime",
|
||||
"recovery:recovery",
|
||||
"handler-restored:runtime",
|
||||
"returned:runtime:outer",
|
||||
"error:value",
|
||||
"returned:value:outer",
|
||||
"success:success",
|
||||
"returned:success:outer",
|
||||
"error:null",
|
||||
"shadow-returned:outer",
|
||||
"returned:null"
|
||||
]);
|
||||
assert_eq!(result["events"], expected_events, "{result}");
|
||||
assert_eq!(
|
||||
result["errors"],
|
||||
serde_json::json!([
|
||||
["SyntaxError", "syntax", true, true],
|
||||
["TypeError", "runtime", true, true],
|
||||
["marker", "value", true, true],
|
||||
["SyntaxError", null, true, true]
|
||||
]),
|
||||
"borrow_child_insertion={borrow_child_insertion}: {result}"
|
||||
);
|
||||
assert_eq!(result["elementEvents"], serde_json::json!([]));
|
||||
let mut after_cleanup = expected_events.as_array().unwrap().clone();
|
||||
after_cleanup.extend(std::iter::repeat_n(serde_json::json!("microtask:null"), 4));
|
||||
assert_eq!(
|
||||
vm.eval("JSON.stringify(__dynamicInlineProbe.events)")
|
||||
.unwrap(),
|
||||
serde_json::to_string(&after_cleanup).unwrap(),
|
||||
"error-handler microtasks must wait for the inserting script to finish"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn main_dynamic_inline_script_errors_from_isolated_world_use_document_realm() {
|
||||
let mut vm = new_parsed_test_vm(
|
||||
"https://inline-errors.test/page.html",
|
||||
"<!doctype html><body></body>",
|
||||
);
|
||||
vm.exec(
|
||||
r#"
|
||||
globalThis.inlineErrors = [];
|
||||
window.onerror = (message, source, line, column, error) => {
|
||||
inlineErrors.push([error.name, error instanceof Error, document.currentScript.id]);
|
||||
return true;
|
||||
};
|
||||
"#,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
let isolated = vm
|
||||
.create_isolated_world("inline-script-insertion", false)
|
||||
.unwrap();
|
||||
let result = vm
|
||||
.eval_in_isolated_context(
|
||||
isolated,
|
||||
r#"
|
||||
(() => {
|
||||
globalThis.executedInline = false;
|
||||
for (const [id, source] of [
|
||||
['syntax', '{'],
|
||||
['runtime', "globalThis.executedInline = true; throw new TypeError('test')"],
|
||||
]) {
|
||||
const script = document.createElement('script');
|
||||
script.id = id;
|
||||
script.textContent = source;
|
||||
document.body.appendChild(script);
|
||||
}
|
||||
return String(executedInline) + ':' + String(document.currentScript);
|
||||
})()
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(result, "false:null");
|
||||
assert_eq!(vm.eval("String(executedInline)").unwrap(), "true");
|
||||
assert_eq!(
|
||||
vm.eval("JSON.stringify(inlineErrors)").unwrap(),
|
||||
r#"[["SyntaxError",true,"syntax"],["TypeError",true,"runtime"]]"#
|
||||
);
|
||||
}
|
||||
@@ -2444,3 +2444,5 @@ mod hyperlink_audit_owner;
|
||||
|
||||
mod fetch_referrer;
|
||||
mod sqlite_web_storage;
|
||||
|
||||
mod dynamic_inline_scripts;
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
function runDynamicInlineErrors(borrowChildInsertion) {
|
||||
const events = [];
|
||||
const errors = [];
|
||||
const elementEvents = [];
|
||||
const marker = {};
|
||||
let insert = (parent, script) => parent.appendChild(script);
|
||||
if (borrowChildInsertion) {
|
||||
const frame = document.createElement('iframe');
|
||||
document.body.appendChild(frame);
|
||||
frame.contentWindow.onerror = () => { events.push('wrong Window'); return true; };
|
||||
insert = frame.contentWindow.Function('parent', 'script',
|
||||
'return Node.prototype.appendChild.call(parent, script)');
|
||||
}
|
||||
const current = () => document.currentScript && document.currentScript.id;
|
||||
const makeScript = (id, source) => {
|
||||
const script = document.createElement('script');
|
||||
script.id = id;
|
||||
script.textContent = source;
|
||||
script.onload = () => elementEvents.push(id + ':load');
|
||||
script.onerror = () => elementEvents.push(id + ':error');
|
||||
return script;
|
||||
};
|
||||
window.onerror = (message, source, line, column, error) => {
|
||||
const id = current();
|
||||
events.push('error:' + id);
|
||||
errors.push([
|
||||
error === marker ? 'marker' : error.name,
|
||||
id,
|
||||
error === marker || error instanceof Error,
|
||||
line > 0 && column > 0,
|
||||
]);
|
||||
if (id === 'runtime') {
|
||||
insert(document.body, makeScript('recovery',
|
||||
"__dynamicInlineProbe.events.push('recovery:' + document.currentScript.id)"));
|
||||
events.push('handler-restored:' + current());
|
||||
}
|
||||
Promise.resolve().then(() => events.push('microtask:' + current()));
|
||||
return true;
|
||||
};
|
||||
globalThis.__dynamicInlineProbe = {events, errors, elementEvents, marker, runOuter() {
|
||||
events.push('outer:' + current());
|
||||
for (const [id, source] of [
|
||||
['syntax', '{'],
|
||||
['runtime', "throw new TypeError('inline runtime')"],
|
||||
['value', 'throw __dynamicInlineProbe.marker'],
|
||||
['success', "__dynamicInlineProbe.events.push('success:' + document.currentScript.id)"],
|
||||
]) {
|
||||
const script = makeScript(id, source);
|
||||
try {
|
||||
insert(document.body, script);
|
||||
events.push('returned:' + id + ':' + current());
|
||||
script.remove();
|
||||
insert(document.body, script);
|
||||
} catch (error) {
|
||||
events.push('escaped:' + error.name);
|
||||
}
|
||||
}
|
||||
const host = document.createElement('div');
|
||||
document.body.appendChild(host);
|
||||
insert(host.attachShadow({mode: 'open'}), makeScript('shadow', '{'));
|
||||
events.push('shadow-returned:' + current());
|
||||
}};
|
||||
insert(document.body, makeScript('outer', '__dynamicInlineProbe.runOuter()'));
|
||||
events.push('returned:' + current());
|
||||
return {events, errors, elementEvents};
|
||||
}
|
||||
Reference in New Issue
Block a user