Skip to content

The headless browser for AI agents and web scraping

fix: harden security boundaries

SGavrl04418a558519
diff --git a/Cargo.lock b/Cargo.lock
index fc8d9243..829a13ab 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1995,6 +1995,7 @@ dependencies = [
"async-trait",
"encoding_rs",
"futures-util",
+ "psl",
"rcgen",
"reqwest",
"serde",
diff --git a/Dockerfile b/Dockerfile
index 7455030a..dd0d8600 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -62,11 +62,9 @@ EXPOSE 9222
# Bind to 0.0.0.0 *inside the container*: a container-loopback bind is
# unreachable through `-p`, so this is required for the port to work at all.
-# It is not a licence to expose the port — publish to host loopback
-# (`-p 127.0.0.1:9222:9222`) unless something in front of it enforces auth.
+# It is not a licence to expose the port. Non-loopback binds require
+# OBSCURA_CDP_TOKEN; publish to host loopback as an additional boundary.
# The native binary still defaults to 127.0.0.1.
#
-# The CDP control plane has no authentication: anything that can reach this
-# port can drive the browser. Network isolation is the control.
ENTRYPOINT ["/obscura"]
CMD ["serve", "--port", "9222", "--host", "0.0.0.0"]
diff --git a/README.md b/README.md
index 897792fb..925d9a86 100644
--- a/README.md
+++ b/README.md
@@ -192,7 +192,9 @@ usable on common LTS servers with glibc 2.35+.
### Docker
```bash
-docker run -d --name obscura -p 127.0.0.1:9222:9222 h4ckf0r0day/obscura
+docker run -d --name obscura -p 127.0.0.1:9222:9222 \
+ -e OBSCURA_CDP_TOKEN="$(openssl rand -hex 32)" \
+ h4ckf0r0day/obscura
```
Image on [Docker Hub](https://hub.docker.com/r/h4ckf0r0day/obscura). Multi-stage build on `distroless/cc:nonroot` — no shell, no package manager, runs as uid 65532, ~57 MB compressed. A mounted `--storage-dir` must be writable by uid 65532. Publish to host loopback as above; `-p 9222:9222` exposes the port on every interface.
diff --git a/crates/obscura-browser/src/context.rs b/crates/obscura-browser/src/context.rs
index bbf710b6..ccbede2f 100644
--- a/crates/obscura-browser/src/context.rs
+++ b/crates/obscura-browser/src/context.rs
@@ -160,7 +160,7 @@ impl BrowserContext {
pub fn isolated_copy(&self, id: String, persistent: bool) -> Self {
let cookie_jar = Arc::new(CookieJar::new());
if persistent {
- cookie_jar.set_cookies_from_cdp(self.cookie_jar.get_all_cookies());
+ cookie_jar.copy_from(&self.cookie_jar);
}
let mut client = ObscuraHttpClient::with_full_options(
@@ -260,6 +260,10 @@ mod tests {
assert_eq!(persistent.cookie_jar.get_all_cookies().len(), 1);
assert!(incognito.cookie_jar.get_all_cookies().is_empty());
+ assert!(persistent
+ .cookie_jar
+ .get_cookie_header(&url::Url::parse("https://sub.example.com").unwrap())
+ .is_empty());
persistent.cookie_jar.clear();
persistent.http_client.set_user_agent("Changed-UA/2.0").await;
diff --git a/crates/obscura-browser/src/page.rs b/crates/obscura-browser/src/page.rs
index 9fa2a325..2fa428ee 100644
--- a/crates/obscura-browser/src/page.rs
+++ b/crates/obscura-browser/src/page.rs
@@ -164,31 +164,6 @@ fn navigation_referrer(source: &Url, target: &Url) -> String {
origin
}
-/// Escape a value for safe inclusion inside a JavaScript template
-/// literal. The previous implementation only escaped `\`, `` ` `` and
-/// `${`; that left U+2028 / U+2029 (the JS-specific line terminators)
-/// and other control characters as breakout vectors. Done at the
-/// callsite means future tweaks come back to one function.
-fn escape_for_js_template_literal(input: &str) -> String {
- let mut out = String::with_capacity(input.len());
- for ch in input.chars() {
- match ch {
- '\\' => out.push_str("\\\\"),
- '`' => out.push_str("\\`"),
- '$' => out.push_str("\\$"),
- '\u{2028}' => out.push_str("\\u2028"),
- '\u{2029}' => out.push_str("\\u2029"),
- '\u{0000}' => out.push_str("\\0"),
- '\r' => out.push_str("\\r"),
- c if (c as u32) < 0x20 => {
- out.push_str(&format!("\\u{:04x}", c as u32));
- }
- c => out.push(c),
- }
- }
- out
-}
-
#[derive(Debug, Clone)]
pub struct NetworkEvent {
pub request_id: String,
@@ -448,6 +423,33 @@ fn materialize_stylesheet_graph(
Some(output)
}
+fn stylesheet_graph_is_origin_clean(
+ key: &str,
+ sheets: &std::collections::HashMap<String, LoadedStylesheet>,
+ aliases: &std::collections::HashMap<String, String>,
+ active: &mut std::collections::HashSet<String>,
+ document_url: &Url,
+) -> bool {
+ let actual_key = aliases.get(key).map(String::as_str).unwrap_or(key);
+ if !active.insert(actual_key.to_string()) {
+ return true;
+ }
+ let Some(sheet) = sheets.get(actual_key) else {
+ active.remove(actual_key);
+ return true;
+ };
+ let clean = sheet.response_url.origin() == document_url.origin()
+ && sheet.imports.iter().all(|import| {
+ let Ok(import_url) = sheet.response_url.join(&import.url) else {
+ return true;
+ };
+ let (import_key, _) = canonical_stylesheet_url(import_url);
+ stylesheet_graph_is_origin_clean(&import_key, sheets, aliases, active, document_url)
+ });
+ active.remove(actual_key);
+ clean
+}
+
/// Preserve the URL base of a fetched stylesheet after it is materialized as
/// inline CSS. Relative `url(...)` values resolve against the stylesheet's
/// URL in browsers, not the document URL; failing to rebase them drops common
@@ -963,92 +965,36 @@ fn parse_import_url(stmt: &str) -> Option<StylesheetImport> {
})
}
-/// Materialize a fetched linked sheet immediately after its source `<link>`.
-///
-/// Keeping each sheet at its document position matters when linked and inline
-/// author sheets are interleaved. Appending one aggregate `<style>` to `<head>`
-/// makes every external rule later than every inline rule, which changes the
-/// CSS cascade even when the external fetches themselves complete in order.
-/// The synthetic style retains the link's effective media query so the same
-/// fetched bytes can enter print layout without leaking into screen layout.
-fn materialize_linked_stylesheet_script(link_index: usize, css: &str) -> String {
- let escaped_css = escape_for_js_template_literal(css);
+/// Attach CSSOM state and dispatch load for a host-fetched linked sheet.
+/// Fetched bytes live in native DOM state, never in a synthetic `<style>` that
+/// page script could read.
+fn register_linked_stylesheet_script(link_index: usize, response_url: &str) -> String {
+ let response_url = serde_json::to_string(response_url).unwrap_or_else(|_| "null".to_string());
format!(
r#"(function() {{
var links = document.querySelectorAll('link[rel~="stylesheet"]');
var link = links[{link_index}];
- if (!link || !link.parentNode) return;
- var style = null;
- function effectiveMedia() {{
- // Until the generic Element shim reflects HTMLLinkElement.media,
- // `this.media = "all"` creates an own property while the parsed
- // media="print" attribute remains unchanged.
- if (Object.prototype.hasOwnProperty.call(link, 'media')) {{
- return String(link.media || '');
- }}
- return link.getAttribute('media') || '';
- }}
+ if (!link) return;
function syncSheet() {{
- if (!style) {{
- style = document.createElement('style');
- style.setAttribute('data-obscura-external-stylesheets', '');
- style.textContent = `{escaped_css}`;
- globalThis.__obscura_registerLinkedStylesheet(link, style);
- }}
- var enabled = link.parentNode
- && !link.disabled
- && !link.hasAttribute('disabled');
- if (!enabled) {{
- if (style && style.parentNode) style.parentNode.removeChild(style);
- return;
+ if (Object.prototype.hasOwnProperty.call(link, 'media')) {{
+ var media = String(link.media || '');
+ if (media) link.setAttribute('media', media);
+ else link.removeAttribute('media');
}}
- var media = effectiveMedia().trim();
- if (media) style.setAttribute('media', media);
- else style.removeAttribute('media');
- if (!style.parentNode) {{
- link.parentNode.insertBefore(style, link.nextSibling);
+ if (Object.prototype.hasOwnProperty.call(link, 'disabled')) {{
+ if (link.disabled) link.setAttribute('disabled', '');
+ else link.removeAttribute('disabled');
}}
}}
- // A non-matching sheet still loads and fires its event. Its handler
- // may then make the sheet applicable (the common
- // media=print/onload="this.media='all'" async-CSS pattern).
syncSheet();
+ globalThis.__obscura_registerLinkedStylesheet(link, {response_url});
try {{ link.dispatchEvent(new Event('load')); }}
finally {{ syncSheet(); }}
}})()"#
)
}
-/// Materialize one fetched `@import` immediately before its source inline
-/// `<style>`. Imported rules precede the importing sheet in the author cascade,
-/// and inherit the source sheet's own media condition in addition to the
-/// import rule's media wrapper.
-fn materialize_inline_import_script(style_index: usize, css: &str) -> String {
- let escaped_css = escape_for_js_template_literal(css);
- format!(
- r#"(function() {{
- var styles = document.querySelectorAll('style');
- var source = null;
- var authorIndex = -1;
- for (var i = 0; i < styles.length; i++) {{
- var candidate = styles[i];
- if (candidate.hasAttribute('data-obscura-external-stylesheets')
- || candidate.hasAttribute('data-obscura-inline-import')) continue;
- authorIndex++;
- if (authorIndex === {style_index}) {{ source = candidate; break; }}
- }}
- if (!source || !source.parentNode) return;
- var imported = document.createElement('style');
- imported.setAttribute('data-obscura-inline-import', '');
- var media = source.getAttribute('media') || '';
- if (media.trim()) imported.setAttribute('media', media);
- imported.textContent = `{escaped_css}`;
- source.parentNode.insertBefore(imported, source);
- }})()"#
- )
-}
-
/// Discover linked author sheets in document order.
///
/// Media queries control whether a loaded sheet participates in the cascade;
@@ -1074,22 +1020,13 @@ fn linked_stylesheet_requests(dom: &DomTree) -> Vec<(usize, String)> {
links
}
-/// Discover fetchable `@import` rules in inline author sheets. The source
-/// index excludes Obscura's own materialized sheets so it remains stable while
-/// imports are inserted before their source nodes.
+/// Discover fetchable `@import` rules in inline author sheets.
fn inline_stylesheet_import_requests(dom: &DomTree) -> Vec<(usize, StylesheetImport)> {
let style_ids = dom.query_selector_all("style").unwrap_or_default();
let mut imports = Vec::new();
let mut author_index = 0usize;
for style_id in style_ids {
- let Some(node) = dom.get_node(style_id) else {
- continue;
- };
- if node
- .get_attribute("data-obscura-external-stylesheets")
- .is_some()
- || node.get_attribute("data-obscura-inline-import").is_some()
- {
+ if dom.get_node(style_id).is_none() {
continue;
}
let (style_imports, _) = split_css_imports(&dom.text_content(style_id));
@@ -1900,7 +1837,7 @@ impl Page {
}
}
- async fn fetch_stylesheets(&mut self) -> Vec<(AuthorStylesheetTarget, String)> {
+ async fn fetch_stylesheets(&mut self) -> Vec<(AuthorStylesheetTarget, String, bool, String)> {
let (all_links, inline_imports) = match &self.js {
Some(js) => js
.with_dom(|dom| {
@@ -2104,6 +2041,15 @@ impl Page {
roots
.into_iter()
.filter_map(|(target, key, media)| {
+ let actual_key = aliases.get(&key).map(String::as_str).unwrap_or(&key);
+ let response_url = sheets.get(actual_key)?.response_url.to_string();
+ let origin_clean = stylesheet_graph_is_origin_clean(
+ &key,
+ &sheets,
+ &aliases,
+ &mut std::collections::HashSet::new(),
+ &document_url,
+ );
materialize_stylesheet_graph(
&key,
&sheets,
@@ -2115,7 +2061,7 @@ impl Page {
Some(media) => format!("@media {media} {{\n{css}\n}}\n"),
None => css,
};
- (target, css)
+ (target, css, origin_clean, response_url)
})
})
.collect()
@@ -3393,38 +3339,44 @@ impl Page {
self.init_js();
let author_stylesheets = self.fetch_stylesheets().await;
- // Inject CSS as a global so getComputedStyle and any CSS-aware shim
- // can read it. Has to happen before scripts run, regardless of
- // waitUntil, so handlers that read window.__obscura_css see it.
+ // Install fetched CSS in native DOM state. Cross-origin bytes must not
+ // become observable through a synthetic style element or page global.
if !author_stylesheets.is_empty() {
if let Some(js) = &mut self.js {
- let combined_css = author_stylesheets
- .iter()
- .map(|(_, css)| css.as_str())
- .collect::<Vec<_>>()
- .join("\n");
- // Use the thorough template-literal escape that
- // covers U+2028 / U+2029 and other control chars.
- // The previous escaper only handled `, \, and ${,
- // letting attacker-controlled CSS containing a raw
- // U+2028 break out of the template literal and run
- // arbitrary JS in the page's V8 realm.
- let escaped = escape_for_js_template_literal(&combined_css);
- let code = format!("globalThis.__obscura_css = `{}`;", escaped);
- let _ = js.execute_script("<css>", &code);
- for (target, css) in &author_stylesheets {
- let code = match target {
- AuthorStylesheetTarget::Linked(link_index) => {
- materialize_linked_stylesheet_script(*link_index, css)
- }
- AuthorStylesheetTarget::InlineImport(style_index) => {
- materialize_inline_import_script(*style_index, css)
+ js.with_dom(|dom| {
+ let links = dom
+ .query_selector_all("link[rel~=\"stylesheet\"]")
+ .unwrap_or_default();
+ let styles = dom.query_selector_all("style").unwrap_or_default();
+ for (target, css, origin_clean, _) in &author_stylesheets {
+ let owner = match target {
+ AuthorStylesheetTarget::Linked(index) => links.get(*index),
+ AuthorStylesheetTarget::InlineImport(index) => styles.get(*index),
+ };
+ if let Some(owner) = owner {
+ dom.append_external_stylesheet(*owner, css.clone(), *origin_clean);
}
- };
- let _ = js.execute_script("<fetch_stylesheets>", &code);
+ }
+ });
+ for (target, _, _, response_url) in &author_stylesheets {
+ if let AuthorStylesheetTarget::Linked(link_index) = target {
+ let _ = js.execute_script(
+ "<fetch_stylesheets>",
+ &register_linked_stylesheet_script(*link_index, response_url),
+ );
+ }
}
}
}
+ // Static registration is complete before page script runs. Remove the
+ // temporary host bridge even when the document had no initial sheets;
+ // dynamic loads use the closure-private function directly.
+ if let Some(js) = &mut self.js {
+ let _ = js.execute_script(
+ "<fetch_stylesheets-cleanup>",
+ "delete globalThis.__obscura_registerLinkedStylesheet",
+ );
+ }
self.document_timeline_origin = std::time::Instant::now();
#[cfg(feature = "render")]
if let Some(js) = &self.js {
@@ -3691,6 +3643,9 @@ impl Page {
}
}
}
+ for sheet in dom.external_stylesheets().values() {
+ sources.extend(sheet.sources.iter().map(ToString::to_string));
+ }
sources
})
.unwrap_or_default();
@@ -4761,18 +4716,41 @@ impl Drop for Page {
#[cfg(test)]
mod tests {
use super::{
- css_resource_urls, linked_stylesheet_requests, materialize_linked_stylesheet_script,
- materialize_stylesheet_graph, navigation_chain_limit_from_env_value, navigation_referrer,
+ css_resource_urls, linked_stylesheet_requests, materialize_stylesheet_graph,
+ navigation_chain_limit_from_env_value, navigation_referrer,
navigation_timeout_from_env_value, parse_import_url, rebase_css_urls,
- script_response_is_executable, split_css_imports, truncate_on_char_boundary,
- url_matches_cdp_pattern, LoadedStylesheet, PendingFrameWork, StylesheetImport,
- DEFAULT_NAVIGATION_CHAIN_LIMIT,
+ register_linked_stylesheet_script, script_response_is_executable, split_css_imports,
+ stylesheet_graph_is_origin_clean, truncate_on_char_boundary, url_matches_cdp_pattern,
+ LoadedStylesheet, PendingFrameWork, StylesheetImport, DEFAULT_NAVIGATION_CHAIN_LIMIT,
};
#[cfg(feature = "render")]
use super::remaining_settle_resource_warmup_ms;
use base64::Engine as _;
use obscura_dom::parse_html;
+ fn install_linked_stylesheet(
+ runtime: &mut obscura_js::runtime::ObscuraJsRuntime,
+ index: usize,
+ css: &str,
+ origin_clean: bool,
+ response_url: &str,
+ ) {
+ runtime
+ .with_dom(|dom| {
+ let links = dom
+ .query_selector_all(r#"link[rel~="stylesheet"]"#)
+ .expect("valid selector");
+ dom.replace_external_stylesheet(links[index], css.to_string(), origin_clean)
+ })
+ .expect("live DOM");
+ runtime
+ .execute_script(
+ "<linked-sheet>",
+ &register_linked_stylesheet_script(index, response_url),
+ )
+ .expect("register linked sheet");
+ }
+
#[test]
fn navigation_timeout_environment_default_remains_thirty_seconds() {
assert_eq!(
@@ -5337,10 +5315,18 @@ mod tests {
.as_ref()
.unwrap()
.with_dom(|dom| {
- dom.query_selector_all("style[data-obscura-external-stylesheets]")
+ dom.query_selector_all(r#"link[rel~="stylesheet"]"#)
.unwrap()
.into_iter()
- .map(|nid| dom.text_content(nid))
+ .map(|nid| {
+ dom.external_stylesheet(nid)
+ .expect("loaded linked sheet")
+ .sources
+ .iter()
+ .map(|source| source.as_ref())
+ .collect::<Vec<_>>()
+ .join("\n")
+ })
.collect::<Vec<_>>()
})
.unwrap();
@@ -5430,24 +5416,32 @@ mod tests {
.unwrap()
.into_iter()
.map(|nid| {
- let node = dom.get_node(nid).unwrap();
(
- node.get_attribute("data-obscura-inline-import").is_some(),
- node.get_attribute("media").map(str::to_string),
+ dom.external_stylesheet(nid)
+ .map(|sheet| {
+ sheet
+ .sources
+ .iter()
+ .map(|source| source.as_ref())
+ .collect::<Vec<_>>()
+ .join("\n")
+ })
+ .unwrap_or_default(),
dom.text_content(nid),
)
})
.collect::<Vec<_>>()
})
.unwrap();
- assert_eq!(styles.len(), 3);
- assert!(styles[0].0 && styles[0].2.contains(".imported-a"));
- assert!(styles[1].0 && styles[1].2.contains(".imported-b"));
- assert!(!styles[2].0 && styles[2].2.contains(".local"));
- assert_eq!(styles[0].1.as_deref(), Some("screen, print"));
- assert_eq!(styles[1].1.as_deref(), Some("screen, print"));
- assert!(styles[0].2.starts_with("@media print {\n"));
- assert!(styles[1].2.starts_with("@media print {\n"));
+ assert_eq!(
+ styles.len(),
+ 1,
+ "imports must not create observable style nodes"
+ );
+ assert!(styles[0].0.contains(".imported-a"));
+ assert!(styles[0].0.contains(".imported-b"));
+ assert!(styles[0].0.starts_with("@media print {\n"));
+ assert!(styles[0].1.contains(".local"));
#[cfg(feature = "render")]
{
@@ -8645,6 +8639,46 @@ mod tests {
assert!(materialized.ends_with(".root{color:red}"));
}
+ #[test]
+ fn cross_origin_import_taints_the_materialized_stylesheet_cssom() {
+ let document_url = url::Url::parse("https://example.test/page").unwrap();
+ let root_url = url::Url::parse("https://example.test/root.css").unwrap();
+ let imported_url = url::Url::parse("https://cdn.test/imported.css").unwrap();
+ let sheets = std::collections::HashMap::from([
+ (
+ root_url.to_string(),
+ LoadedStylesheet {
+ response_url: root_url.clone(),
+ imports: vec![StylesheetImport {
+ url: imported_url.to_string(),
+ media: None,
+ }],
+ rules: String::new(),
+ },
+ ),
+ (
+ imported_url.to_string(),
+ LoadedStylesheet {
+ response_url: imported_url.clone(),
+ imports: Vec::new(),
+ rules: ".secret{}".to_string(),
+ },
+ ),
+ ]);
+ let aliases = std::collections::HashMap::from([
+ (root_url.to_string(), root_url.to_string()),
+ (imported_url.to_string(), imported_url.to_string()),
+ ]);
+
+ assert!(!stylesheet_graph_is_origin_clean(
+ root_url.as_str(),
+ &sheets,
+ &aliases,
+ &mut std::collections::HashSet::new(),
+ &document_url,
+ ));
+ }
+
#[test]
fn stylesheet_asset_urls_keep_the_importing_sheets_base() {
let base = url::Url::parse("https://example.com/css/theme/app.css").unwrap();
@@ -8715,12 +8749,13 @@ mod tests {
let mut runtime = obscura_js::runtime::ObscuraJsRuntime::new();
runtime.set_dom(dom);
runtime.run_page_init();
- runtime
- .execute_script(
- "<async-sheet>",
- &materialize_linked_stylesheet_script(0, ".target{color:red}"),
- )
- .expect("load and materialize async linked sheet");
+ install_linked_stylesheet(
+ &mut runtime,
+ 0,
+ ".target{color:red}",
+ true,
+ "https://example.com/style.css",
+ );
let state = runtime
.with_dom(|dom| {
@@ -8728,13 +8763,11 @@ mod tests {
.query_selector("#async")
.expect("valid selector")
.expect("async link");
- let styles = dom
- .query_selector_all("style[data-obscura-external-stylesheets]")
- .expect("valid selector");
(
dom.get_node(link)
.and_then(|node| node.get_attribute("data-loaded").map(str::to_owned)),
- styles.first().map(|&nid| dom.text_content(nid)),
+ dom.external_stylesheet(link)
+ .and_then(|sheet| sheet.sources.first().map(ToString::to_string)),
)
})
.expect("live DOM");
@@ -8762,12 +8795,13 @@ mod tests {
let mut runtime = obscura_js::runtime::ObscuraJsRuntime::new();
runtime.set_dom(dom);
runtime.run_page_init();
- runtime
- .execute_script(
- "<print-sheet>",
- &materialize_linked_stylesheet_script(0, "body{display:none}"),
- )
- .expect("finish print linked sheet load");
+ install_linked_stylesheet(
+ &mut runtime,
+ 0,
+ "body{display:none}",
+ true,
+ "https://example.com/style.css",
+ );
let state = runtime
.with_dom(|dom| {
@@ -8778,12 +8812,8 @@ mod tests {
(
dom.get_node(link)
.and_then(|node| node.get_attribute("data-loaded").map(str::to_owned)),
- dom.query_selector("style[data-obscura-external-stylesheets]")
- .expect("valid selector")
- .and_then(|style| {
- dom.get_node(style)
- .and_then(|node| node.get_attribute("media").map(str::to_owned))
- }),
+ dom.get_node(link)
+ .and_then(|node| node.get_attribute("media").map(str::to_owned)),
)
})
.expect("live DOM");
@@ -8813,21 +8843,20 @@ mod tests {
runtime.set_dom(dom);
runtime.set_url("https://example.test/products/widget");
runtime.run_page_init();
- runtime
- .execute_script(
- "<same-origin-sheet>",
- &materialize_linked_stylesheet_script(
- 0,
- ".app { color: red } .wide { width: 20px }",
- ),
- )
- .expect("materialize same-origin linked sheet");
- runtime
- .execute_script(
- "<cross-origin-sheet>",
- &materialize_linked_stylesheet_script(1, ".secret { color: purple }"),
- )
- .expect("materialize cross-origin linked sheet");
+ install_linked_stylesheet(
+ &mut runtime,
+ 0,
+ ".app { color: red } .wide { width: 20px }",
+ true,
+ "https://example.test/assets/app.css",
+ );
+ install_linked_stylesheet(
+ &mut runtime,
+ 1,
+ ".secret { color: purple }",
+ false,
+ "https://cdn.example.test/theme.css",
+ );
let result = runtime
.evaluate(
@@ -8840,6 +8869,10 @@ mod tests {
const sameSheet = same.sheet;
const sameRules = sameSheet.cssRules;
const crossSheet = cross.sheet;
+ // Public-looking implementation fields must not be able to
+ // bypass the closure-private origin decision.
+ crossSheet._originClean = true;
+ crossSheet._sourceText = '.forged { color: red }';
const security = [];
for (const operation of [
() => crossSheet.cssRules,
@@ -8852,9 +8885,6 @@ mod tests {
catch (error) { security.push(error && error.name); }
}
sameSheet.insertRule('.added { height: 9px }', sameRules.length);
- const source = document.querySelector(
- 'style[data-obscura-external-stylesheets]'
- );
return {
stableList: list === document.styleSheets,
length: list.length,
@@ -8866,11 +8896,11 @@ mod tests {
title: sameSheet.title,
rulesIdentity: sameSheet.cssRules === sameRules,
rules: Array.from(sameRules, rule => rule.selectorText),
- sourceUpdated: source.textContent.includes('.added'),
+ bridgeTextHidden: !document.documentElement.textContent.includes('.secret')
+ && !document.querySelector('style[data-obscura-external-stylesheets]'),
crossOwner: crossSheet.ownerNode === cross,
crossHref: crossSheet.href,
- bridgeSheetsHidden: same.nextSibling.sheet === null
- && cross.nextSibling.sheet === null,
+ privateRulesHidden: crossSheet._rules.length === 0,
security,
};
})()
@@ -8890,10 +8920,10 @@ mod tests {
"title": "app",
"rulesIdentity": true,
"rules": [".app", ".wide", ".added"],
- "sourceUpdated": true,
+ "bridgeTextHidden": true,
"crossOwner": true,
"crossHref": "https://cdn.example.test/theme.css",
- "bridgeSheetsHidden": true,
+ "privateRulesHidden": true,
"security": ["SecurityError", "SecurityError", "SecurityError",
"SecurityError", "SecurityError"],
})
@@ -8912,25 +8942,38 @@ mod tests {
let mut runtime = obscura_js::runtime::ObscuraJsRuntime::new();
runtime.set_dom(dom);
runtime.run_page_init();
- runtime
- .execute_script(
- "<first-sheet>",
- &materialize_linked_stylesheet_script(0, ".target{height:10px}"),
- )
- .expect("materialize first linked sheet");
- runtime
- .execute_script(
- "<second-sheet>",
- &materialize_linked_stylesheet_script(1, ".target{height:30px}"),
- )
- .expect("materialize second linked sheet");
+ install_linked_stylesheet(
+ &mut runtime,
+ 0,
+ ".target{height:10px}",
+ true,
+ "https://example.com/first.css",
+ );
+ install_linked_stylesheet(
+ &mut runtime,
+ 1,
+ ".target{height:30px}",
+ true,
+ "https://example.com/second.css",
+ );
let sheet_text = runtime
.with_dom(|dom| {
- dom.query_selector_all("style")
- .expect("valid selector")
+ dom.descendants(dom.document())
.into_iter()
- .map(|nid| dom.text_content(nid))
+ .flat_map(|nid| {
+ let mut sources: Vec<String> = dom
+ .external_stylesheet(nid)
+ .map(|sheet| sheet.sources.iter().map(ToString::to_string).collect())
+ .unwrap_or_default();
+ if dom.get_node(nid).is_some_and(|node| {
+ node.as_element()
+ .is_some_and(|element| element.local.as_ref() == "style")
+ }) {
+ sources.push(dom.text_content(nid));
+ }
+ sources
+ })
.collect::<Vec<_>>()
})
.expect("live DOM");
diff --git a/crates/obscura-cdp/src/cookie_params.rs b/crates/obscura-cdp/src/cookie_params.rs
index 46272e0f..c7a42176 100644
--- a/crates/obscura-cdp/src/cookie_params.rs
+++ b/crates/obscura-cdp/src/cookie_params.rs
@@ -3,7 +3,12 @@ use serde_json::Value;
const DEFAULT_COOKIE_PATH: &str = "/";
-pub fn parse_cdp_cookie(value: &Value) -> Option<CookieInfo> {
+pub struct ParsedCookie {
+ pub cookie: CookieInfo,
+ pub host_only: bool,
+}
+
+pub fn parse_cdp_cookie(value: &Value) -> Option<ParsedCookie> {
let name = value.get("name").and_then(|v| v.as_str())?.to_string();
let cookie_value = value
.get("value")
@@ -16,11 +21,10 @@ pub fn parse_cdp_cookie(value: &Value) -> Option<CookieInfo> {
.and_then(|v| v.as_str())
.and_then(|u| url::Url::parse(u).ok());
- let domain = value
- .get("domain")
- .and_then(|v| v.as_str())
- .map(|s| s.to_string())
- .or_else(|| url_parsed.as_ref().and_then(|u| u.host_str().map(|h| h.to_string())))
+ let explicit_domain = value.get("domain").and_then(|v| v.as_str());
+ let domain = explicit_domain
+ .map(str::to_string)
+ .or_else(|| url_parsed.as_ref().and_then(|u| u.host_str().map(str::to_string)))
.unwrap_or_default();
if domain.is_empty() {
@@ -47,15 +51,18 @@ pub fn parse_cdp_cookie(value: &Value) -> Option<CookieInfo> {
.to_string();
let expires = value.get("expires").and_then(|v| v.as_f64()).map(|f| f as i64);
- Some(CookieInfo {
- name,
- value: cookie_value,
- domain,
- path,
- secure,
- http_only,
- same_site,
- expires,
+ Some(ParsedCookie {
+ cookie: CookieInfo {
+ name,
+ value: cookie_value,
+ domain,
+ path,
+ secure,
+ http_only,
+ same_site,
+ expires,
+ },
+ host_only: explicit_domain.is_none(),
})
}
@@ -109,7 +116,9 @@ mod tests {
"sameSite": "Strict",
"expires": 1_900_000_000.0,
});
- let c = parse_cdp_cookie(&v).unwrap();
+ let parsed = parse_cdp_cookie(&v).unwrap();
+ let c = parsed.cookie;
+ assert!(!parsed.host_only);
assert_eq!(c.name, "session");
assert_eq!(c.value, "abc");
assert_eq!(c.domain, ".example.com");
@@ -131,9 +140,20 @@ mod tests {
"value": "xyz",
"url": "https://api.example.com/v1/things",
});
- let c = parse_cdp_cookie(&v).unwrap();
+ let parsed = parse_cdp_cookie(&v).unwrap();
+ let c = parsed.cookie;
+ assert!(parsed.host_only);
assert_eq!(c.domain, "api.example.com");
assert_eq!(c.path, "/v1");
+
+ let jar = obscura_net::CookieJar::new();
+ jar.set_cookies_from_cdp_with_scope([(c, parsed.host_only)]);
+ assert!(jar
+ .get_cookie_header(&url::Url::parse("https://api.example.com/v1/item").unwrap())
+ .contains("tok=xyz"));
+ assert!(jar
+ .get_cookie_header(&url::Url::parse("https://sub.api.example.com/v1/item").unwrap())
+ .is_empty());
}
#[test]
@@ -145,7 +165,7 @@ mod tests {
"url": "https://api.example.com/v1/things",
"path": "/v1/things",
});
- let c = parse_cdp_cookie(&v).unwrap();
+ let c = parse_cdp_cookie(&v).unwrap().cookie;
assert_eq!(c.path, "/v1/things");
}
@@ -162,7 +182,7 @@ mod tests {
"value": "v",
"domain": "example.com",
});
- let c = parse_cdp_cookie(&v).unwrap();
+ let c = parse_cdp_cookie(&v).unwrap().cookie;
assert_eq!(c.path, "/");
}
diff --git a/crates/obscura-cdp/src/domains/network.rs b/crates/obscura-cdp/src/domains/network.rs
index fc5c9109..1973609d 100644
--- a/crates/obscura-cdp/src/domains/network.rs
+++ b/crates/obscura-cdp/src/domains/network.rs
@@ -70,13 +70,18 @@ pub async fn handle(
"setCookie" => {
let cookie = parse_cdp_cookie(params)
.ok_or("setCookie: missing required name/domain (or url)")?;
- cookie_jar_for(ctx, session_id).set_cookies_from_cdp(vec![cookie]);
+ cookie_jar_for(ctx, session_id)
+ .set_cookies_from_cdp_with_scope([(cookie.cookie, cookie.host_only)]);
Ok(json!({ "success": true }))
}
"setCookies" => {
if let Some(cookies) = params.get("cookies").and_then(|v| v.as_array()) {
let parsed: Vec<_> = cookies.iter().filter_map(parse_cdp_cookie).collect();
- cookie_jar_for(ctx, session_id).set_cookies_from_cdp(parsed);
+ cookie_jar_for(ctx, session_id).set_cookies_from_cdp_with_scope(
+ parsed
+ .into_iter()
+ .map(|cookie| (cookie.cookie, cookie.host_only)),
+ );
}
Ok(json!({}))
}
diff --git a/crates/obscura-cdp/src/domains/runtime.rs b/crates/obscura-cdp/src/domains/runtime.rs
index 94f43df5..eac29aec 100644
--- a/crates/obscura-cdp/src/domains/runtime.rs
+++ b/crates/obscura-cdp/src/domains/runtime.rs
@@ -394,7 +394,7 @@ pub async fn handle(
if (arguments.length !== 1) return;\
try {{\
const payload = typeof arg === 'string' ? arg : String(arg);\
- Deno.core.ops.op_binding_called('{name}', payload);\
+ globalThis.__obscura_binding_called('{name}', payload);\
}} catch (e) {{ /* swallow: binding must not throw into page */ }}\
}};",
name = name,
diff --git a/crates/obscura-cdp/src/domains/storage.rs b/crates/obscura-cdp/src/domains/storage.rs
index 4ffcab68..4d8acb12 100644
--- a/crates/obscura-cdp/src/domains/storage.rs
+++ b/crates/obscura-cdp/src/domains/storage.rs
@@ -36,7 +36,11 @@ pub async fn handle(
"setCookies" => {
if let Some(cookies) = params.get("cookies").and_then(|v| v.as_array()) {
let parsed: Vec<_> = cookies.iter().filter_map(parse_cdp_cookie).collect();
- cookie_jar_for(ctx, params, session_id)?.set_cookies_from_cdp(parsed);
+ cookie_jar_for(ctx, params, session_id)?.set_cookies_from_cdp_with_scope(
+ parsed
+ .into_iter()
+ .map(|cookie| (cookie.cookie, cookie.host_only)),
+ );
}
Ok(json!({}))
}
diff --git a/crates/obscura-cdp/src/server.rs b/crates/obscura-cdp/src/server.rs
index ca99f8df..b877d199 100644
--- a/crates/obscura-cdp/src/server.rs
+++ b/crates/obscura-cdp/src/server.rs
@@ -50,6 +50,121 @@ const SHUTDOWN_DRAIN_MS: u64 = 3_000;
const CONNECTION_LIMIT_RESPONSE: &str = "HTTP/1.1 503 Service Unavailable\r\n\
Content-Length: 0\r\nConnection: close\r\n\
X-Obscura-Reason: max-connections\r\n\r\n";
+
+fn control_token_from_env() -> anyhow::Result<Option<String>> {
+ let token = std::env::var("OBSCURA_CDP_TOKEN")
+ .ok()
+ .filter(|value| !value.is_empty());
+ if token.as_ref().is_some_and(|value| value.len() < 32) {
+ anyhow::bail!("OBSCURA_CDP_TOKEN must be at least 32 bytes");
+ }
+ Ok(token)
+}
+
+fn constant_time_eq(left: &str, right: &str) -> bool {
+ if left.len() != right.len() {
+ return false;
+ }
+ left.bytes()
+ .zip(right.bytes())
+ .fold(0u8, |difference, (left, right)| difference | (left ^ right))
+ == 0
+}
+
+fn header_value<'a>(head: &'a str, name: &str) -> Option<&'a str> {
+ head.split("\r\n")
+ .skip(1)
+ .take_while(|line| !line.is_empty())
+ .filter_map(|line| line.split_once(':'))
+ .find(|(header, _)| header.eq_ignore_ascii_case(name))
+ .map(|(_, value)| value.trim())
+}
+
+fn bearer_authorized(head: &str, expected: Option<&str>) -> bool {
+ match expected {
+ None => true,
+ Some(expected) => header_value(head, "authorization")
+ .and_then(|value| value.strip_prefix("Bearer "))
+ .is_some_and(|provided| constant_time_eq(provided, expected)),
+ }
+}
+
+fn host_matches_bind(host_header: &str, bind_ip: std::net::IpAddr, port: u16) -> bool {
+ if bind_ip.is_unspecified() {
+ return true;
+ }
+ let Ok(url) = url::Url::parse(&format!("http://{host_header}/")) else {
+ return false;
+ };
+ if url.port_or_known_default() != Some(port) {
+ return false;
+ }
+ match (url.host(), bind_ip) {
+ (Some(url::Host::Ipv4(address)), std::net::IpAddr::V4(bind)) => {
+ address == bind || (bind.is_loopback() && address.is_loopback())
+ }
+ (Some(url::Host::Ipv6(address)), std::net::IpAddr::V6(bind)) => {
+ address == bind || (bind.is_loopback() && address.is_loopback())
+ }
+ (Some(url::Host::Ipv4(address)), std::net::IpAddr::V6(bind)) => {
+ bind.is_loopback() && address.is_loopback()
+ }
+ (Some(url::Host::Ipv6(address)), std::net::IpAddr::V4(bind)) => {
+ bind.is_loopback() && address.is_loopback()
+ }
+ (Some(url::Host::Domain(domain)), _) => {
+ bind_ip.is_loopback() && domain.eq_ignore_ascii_case("localhost")
+ }
+ (None, _) => false,
+ }
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+enum ControlRefusal {
+ BrowserOrigin,
+ ForeignHost,
+ Unauthorized,
+ OversizedHead,
+}
+
+fn control_refusal(
+ head: &str,
+ bind_ip: std::net::IpAddr,
+ port: u16,
+ auth_token: Option<&str>,
+) -> Option<ControlRefusal> {
+ if header_value(head, "origin").is_some() {
+ return Some(ControlRefusal::BrowserOrigin);
+ }
+ if !header_value(head, "host").is_some_and(|host| host_matches_bind(host, bind_ip, port)) {
+ return Some(ControlRefusal::ForeignHost);
+ }
+ if !bearer_authorized(head, auth_token) {
+ return Some(ControlRefusal::Unauthorized);
+ }
+ None
+}
+
+fn refuse_control_connection(mut stream: std::net::TcpStream, refusal: ControlRefusal) {
+ use std::io::Write;
+ let (status, reason) = match refusal {
+ ControlRefusal::Unauthorized => ("401 Unauthorized", "authentication required"),
+ ControlRefusal::OversizedHead => (
+ "431 Request Header Fields Too Large",
+ "request head too large",
+ ),
+ ControlRefusal::BrowserOrigin | ControlRefusal::ForeignHost => {
+ ("403 Forbidden", "request refused")
+ }
+ };
+ let body = format!("{{\"error\":\"{reason}\"}}");
+ let response = format!(
+ "HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
+ body.len()
+ );
+ let _ = stream.write_all(response.as_bytes());
+ let _ = stream.flush();
+}
use crate::types::CdpRequest;
struct CdpMessage {
@@ -173,6 +288,12 @@ pub async fn start_with_serve_options_and_limit(
.parse()
.map_err(|e| anyhow::anyhow!("invalid --host '{}': {}", host, e))?;
let addr = SocketAddr::new(ip, port);
+ let auth_token = control_token_from_env()?;
+ if !ip.is_loopback() && auth_token.is_none() {
+ anyhow::bail!(
+ "refusing to expose CDP without authentication; set OBSCURA_CDP_TOKEN to at least 32 bytes"
+ );
+ }
// Issue #62: the HTTP control plane (/json/version, /json) must remain
// reachable even while V8 JS evaluation blocks the tokio LocalSet thread.
@@ -197,6 +318,9 @@ pub async fn start_with_serve_options_and_limit(
if allow_file_access {
info!("file:// navigation enabled (--allow-file-access). Do not expose this port to untrusted networks.");
}
+ if auth_token.is_some() {
+ info!("CDP bearer authentication enabled");
+ }
let (ws_tx, mut ws_rx) = mpsc::channel::<std::net::TcpStream>(MAX_PENDING_WS_HANDOFFS);
@@ -226,6 +350,7 @@ pub async fn start_with_serve_options_and_limit(
// above any real connect rate, so the kernel backlog cannot overflow
// under a connection burst.
let accept_flag = shutdown_flag.clone();
+ let accept_auth_token = auth_token.clone();
std::thread::Builder::new()
.name("obscura-cdp-accept".into())
.spawn(move || {
@@ -281,8 +406,18 @@ pub async fn start_with_serve_options_and_limit(
match peek_request_head(&stream) {
PeekStatus::NotReady => pending.push((stream, since)),
PeekStatus::Closed => {}
+ PeekStatus::Oversized => {
+ refuse_control_connection(stream, ControlRefusal::OversizedHead);
+ }
PeekStatus::Head(head) => {
- if let Err(e) = accept_dispatch(stream, port, &ws_tx, &head) {
+ if let Err(e) = accept_dispatch(
+ stream,
+ ip,
+ port,
+ accept_auth_token.as_deref(),
+ &ws_tx,
+ &head,
+ ) {
if !format!("{}", e).contains("close") {
error!("Accept dispatch error: {}", e);
}
@@ -725,6 +860,9 @@ enum PeekStatus {
NotReady,
/// Peer went away without sending a full head.
Closed,
+ /// The header terminator did not fit in the bounded peek buffer. Refuse it;
+ /// security-sensitive headers could otherwise be hidden beyond the cap.
+ Oversized,
/// A classifiable request head.
Head(String),
}
@@ -747,11 +885,13 @@ fn peek_request_head(stream: &std::net::TcpStream) -> PeekStatus {
if n >= 4 && head[..4] != *b"GET " {
return PeekStatus::Head(String::from_utf8_lossy(head).into_owned());
}
- // A head that overflows the peek buffer is classified with what arrived,
- // matching the pre-polling behavior for oversized headers.
- let complete = n == HTTP_PEEK_BUF || head.windows(4).any(|w| w == b"\r\n\r\n");
+ let complete = head.windows(4).any(|w| w == b"\r\n\r\n");
if !complete {
- return PeekStatus::NotReady;
+ return if n == HTTP_PEEK_BUF {
+ PeekStatus::Oversized
+ } else {
+ PeekStatus::NotReady
+ };
}
PeekStatus::Head(String::from_utf8_lossy(head).into_owned())
}
@@ -765,10 +905,16 @@ fn peek_request_head(stream: &std::net::TcpStream) -> PeekStatus {
/// - WebSocket: forward to the LocalSet for CDP processing.
fn accept_dispatch(
stream: std::net::TcpStream,
+ bind_ip: std::net::IpAddr,
port: u16,
+ auth_token: Option<&str>,
ws_tx: &mpsc::Sender<std::net::TcpStream>,
head: &str,
) -> anyhow::Result<()> {
+ if let Some(refusal) = control_refusal(head, bind_ip, port, auth_token) {
+ refuse_control_connection(stream, refusal);
+ return Ok(());
+ }
let endpoint = if head.contains("/json/version") {
Some("version")
} else if head.contains("/json/list") || head.contains("/json\r\n") || head.contains("/json HTTP") {
@@ -1835,8 +1981,8 @@ async fn handle_connection_ws(
#[cfg(test)]
mod tests {
use super::{
- handle_fetch_resolution, is_navigate_method, merge_cookie_delta, parse_cdp_headers,
- websocket_authority,
+ bearer_authorized, control_refusal, handle_fetch_resolution, is_navigate_method,
+ merge_cookie_delta, parse_cdp_headers, websocket_authority, ControlRefusal,
};
#[cfg(feature = "render")]
use super::{pump_and_forward_screencast_frames, pump_live_page_event_loop};
@@ -1844,6 +1990,54 @@ mod tests {
use serde_json::json;
use std::collections::HashMap;
+ fn native_head(host: &str) -> String {
+ format!(
+ "GET /devtools/browser HTTP/1.1\r\nHost: {host}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\r\n"
+ )
+ }
+
+ #[test]
+ fn native_loopback_cdp_request_is_allowed() {
+ let head = native_head("127.0.0.1:9222");
+ assert_eq!(
+ control_refusal(&head, "127.0.0.1".parse().unwrap(), 9222, None),
+ None
+ );
+ }
+
+ #[test]
+ fn browser_origin_and_rebound_host_are_refused() {
+ let with_origin = native_head("127.0.0.1:9222").replace(
+ "Upgrade: websocket",
+ "Origin: https://evil.example\r\nUpgrade: websocket",
+ );
+ assert_eq!(
+ control_refusal(&with_origin, "127.0.0.1".parse().unwrap(), 9222, None),
+ Some(ControlRefusal::BrowserOrigin)
+ );
+ assert_eq!(
+ control_refusal(
+ &native_head("rebind.example:9222"),
+ "127.0.0.1".parse().unwrap(),
+ 9222,
+ None,
+ ),
+ Some(ControlRefusal::ForeignHost)
+ );
+ }
+
+ #[test]
+ fn configured_cdp_token_is_mandatory() {
+ let token = "01234567890123456789012345678901";
+ let mut head = native_head("127.0.0.1:9222");
+ assert!(!bearer_authorized(&head, Some(token)));
+ head = head.replace(
+ "Upgrade: websocket",
+ &format!("Authorization: Bearer {token}\r\nUpgrade: websocket"),
+ );
+ assert!(bearer_authorized(&head, Some(token)));
+ }
+
#[test]
fn discovery_uses_the_client_facing_http_authority() {
let request = "GET /json/version HTTP/1.1\r\nhOsT: cdp.example.test:9222\r\n\r\n";
diff --git a/crates/obscura-cli/src/main.rs b/crates/obscura-cli/src/main.rs
index 16ebe9c2..183ba2e3 100644
--- a/crates/obscura-cli/src/main.rs
+++ b/crates/obscura-cli/src/main.rs
@@ -330,8 +330,23 @@ fn effective_v8_flags(user: Option<&str>) -> String {
}
}
+const CLI_STACK_BYTES: usize = 512 * 1024 * 1024;
+
+fn main() -> anyhow::Result<()> {
+ std::thread::Builder::new()
+ .name("obscura-main".to_string())
+ // V8 derives its stack guard from the current native thread. Deep but
+ // valid hostile documents can otherwise exhaust the platform's small
+ // default stack while the page realm is initialized. This reserves
+ // address space; pages are committed only as the stack is used.
+ .stack_size(CLI_STACK_BYTES)
+ .spawn(run_cli)?
+ .join()
+ .map_err(|_| anyhow::anyhow!("obscura main thread panicked"))?
+}
+
#[tokio::main(flavor = "current_thread")]
-async fn main() -> anyhow::Result<()> {
+async fn run_cli() -> anyhow::Result<()> {
let args = Args::parse();
// Pin the process timezone before V8/ICU reads it. V8 sources the zone for
diff --git a/crates/obscura-dom/src/tree.rs b/crates/obscura-dom/src/tree.rs
index 6ce4f4ab..c9f87985 100644
--- a/crates/obscura-dom/src/tree.rs
+++ b/crates/obscura-dom/src/tree.rs
@@ -2,6 +2,7 @@ use html5ever::{LocalName, Namespace, Prefix, QualName};
use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use std::fmt;
+use std::sync::Arc;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct NodeId(pub(crate) u32);
@@ -248,6 +249,17 @@ pub struct DomTree {
inner: RefCell<DomTreeInner>,
}
+/// Host-fetched author CSS kept outside the page-visible DOM.
+///
+/// A linked stylesheet may participate in rendering even when the response is
+/// not origin-clean. Keeping those bytes here prevents a synthetic `<style>`
+/// node from exposing them through ordinary DOM APIs.
+#[derive(Clone, Debug, Default)]
+pub struct ExternalStylesheet {
+ pub sources: Vec<Arc<str>>,
+ pub origin_clean: bool,
+}
+
/// Live control state is separate from content attributes and serialization.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct FormControlState {
@@ -262,6 +274,7 @@ pub(crate) struct DomTreeInner {
pub(crate) document: NodeId,
pub(crate) id_index: HashMap<String, NodeId>,
form_controls: HashMap<NodeId, FormControlState>,
+ external_stylesheets: HashMap<NodeId, ExternalStylesheet>,
/// Shadow roots are arena nodes with their own child list. They are kept
/// outside the ordinary parent links so light-tree traversal never crosses
/// into a shadow tree by accident.
@@ -294,6 +307,7 @@ impl DomTree {
document: NodeId(0),
id_index: HashMap::new(),
form_controls: HashMap::new(),
+ external_stylesheets: HashMap::new(),
shadow_roots: HashMap::new(),
shadow_roots_by_host: HashMap::new(),
allow_declarative_shadow_roots: false,
@@ -306,6 +320,78 @@ impl DomTree {
self.inner.borrow().document
}
+ pub fn replace_external_stylesheet(
+ &self,
+ owner: NodeId,
+ source: String,
+ origin_clean: bool,
+ ) -> bool {
+ let mut inner = self.inner.borrow_mut();
+ if inner
+ .nodes
+ .get(owner.index())
+ .and_then(Option::as_ref)
+ .is_none()
+ {
+ return false;
+ }
+ inner.external_stylesheets.insert(
+ owner,
+ ExternalStylesheet {
+ sources: vec![Arc::from(source)],
+ origin_clean,
+ },
+ );
+ true
+ }
+
+ pub fn append_external_stylesheet(
+ &self,
+ owner: NodeId,
+ source: String,
+ origin_clean: bool,
+ ) -> bool {
+ let mut inner = self.inner.borrow_mut();
+ if inner
+ .nodes
+ .get(owner.index())
+ .and_then(Option::as_ref)
+ .is_none()
+ {
+ return false;
+ }
+ let sheet = inner
+ .external_stylesheets
+ .entry(owner)
+ .or_insert_with(|| ExternalStylesheet {
+ sources: Vec::new(),
+ origin_clean: true,
+ });
+ sheet.sources.push(Arc::from(source));
+ sheet.origin_clean &= origin_clean;
+ true
+ }
+
+ pub fn remove_external_stylesheet(&self, owner: NodeId) -> bool {
+ self.inner
+ .borrow_mut()
+ .external_stylesheets
+ .remove(&owner)
+ .is_some()
+ }
+
+ pub fn external_stylesheet(&self, owner: NodeId) -> Option<ExternalStylesheet> {
+ self.inner
+ .borrow()
+ .external_stylesheets
+ .get(&owner)
+ .cloned()
+ }
+
+ pub fn external_stylesheets(&self) -> HashMap<NodeId, ExternalStylesheet> {
+ self.inner.borrow().external_stylesheets.clone()
+ }
+
pub fn form_control_state(&self, node: NodeId) -> Option<FormControlState> {
self.inner.borrow().form_controls.get(&node).cloned()
}
diff --git a/crates/obscura-js/js/bootstrap.js b/crates/obscura-js/js/bootstrap.js
index 324208d0..b2dea1b0 100644
--- a/crates/obscura-js/js/bootstrap.js
+++ b/crates/obscura-js/js/bootstrap.js
@@ -1,6 +1,12 @@
"use strict";
(function () {
+// deno_core installs its privileged bridge in the page's V8 context. Capture
+// it in this private bootstrap closure. The host removes the public global
+// after deno_core finishes binding ops and before any page script runs. All
+// browser APIs below close over this reference.
+const __obscuraCore = globalThis.Deno.core;
+
// Pre-declare all internal globals as non-enumerable so they are invisible
// to Object.keys(window) / for-in enumeration. Must run before any var
// declarations or property assignments below: once a property is defined
@@ -71,11 +77,21 @@
// Handoff for child frame realms. deno_core binds ops into the main context
// only, so a realm restored from the snapshot arrives with its own empty
-// `Deno.core.ops`. The host reads this to take the main realm's bound op table
+// private core reference. The host reads this to take the main realm's bound op table
// and to find each new realm's own table to fill, then deletes the global in
// the same step, so page script never sees it (see runtime.rs
// `take_ops_handoff` / `share_ops_with_realm`).
-globalThis.__obscura_core_handoff = Deno.core;
+globalThis.__obscura_core_handoff = __obscuraCore;
+
+// Runtime.addBinding installs a named page function which forwards through
+// this narrow bridge. Calling it grants no capability beyond calling the
+// installed binding itself; the full op table remains unreachable.
+Object.defineProperty(globalThis, "__obscura_binding_called", {
+ value: (name, payload) => __obscuraCore.ops.op_binding_called(String(name), String(payload)),
+ writable: false,
+ enumerable: false,
+ configurable: false,
+});
globalThis.__obscura_errors = [];
@@ -123,7 +139,7 @@ const _DOM_TREE_MUTATION_COMMANDS = new Set([
let _realmFrameId = 0;
const _dom = (cmd, a1, a2) => {
- const result = Deno.core.ops.op_dom(cmd, String(a1 ?? ""), String(a2 ?? ""), _realmFrameId);
+ const result = __obscuraCore.ops.op_dom(cmd, String(a1 ?? ""), String(a2 ?? ""), _realmFrameId);
if (_DOM_MUTATION_COMMANDS.has(cmd)) {
_domMutationEpoch++;
// Resize observation is tied to rendering-invalidating DOM work. The
@@ -319,15 +335,15 @@ function _decodeDataScriptUrl(url) {
// native per-document state so it survives wrapper churn, fragment parsing,
// moves, and cloneNode().
globalThis.__markParserScripts = function(nids) {
- for (const nid of nids || []) Deno.core.ops.op_script_mark_started(+nid);
+ for (const nid of nids || []) __obscuraCore.ops.op_script_mark_started(+nid);
};
async function __fetchDynClassicScript(task) {
let body;
if (task.url.startsWith('data:')) {
body = _decodeDataScriptUrl(task.url);
} else {
- const raw = await Deno.core.ops.op_fetch_url(
- task.url, "GET", "{}", new Uint8Array(0), task.pageOrigin, "no-cors", "same-origin"
+ const raw = await __obscuraCore.ops.op_fetch_url(
+ task.url, "GET", "{}", new Uint8Array(0), task.pageOrigin, "no-cors", "same-origin", true
);
const parsed = JSON.parse(raw);
// The HTML script-fetch algorithm treats an unsuccessful HTTP response
@@ -441,28 +457,16 @@ function _linkedStylesheetHref(link, explicitHref) {
return raw ? _resolveResourceUrl(String(raw)) : "";
}
-function _linkedStylesheetIsOriginClean(href) {
- try {
- const documentUrl = new URL(globalThis.document?.URL || globalThis.location?.href || "about:blank");
- const stylesheetUrl = new URL(href, documentUrl.href);
- return stylesheetUrl.origin === documentUrl.origin;
- } catch(e) {
- // An unresolved relative URL in an about:blank-style synthetic document
- // has no distinct remote origin and is safe to expose.
- return !/^[a-z][a-z0-9+.-]*:/i.test(String(href || ""));
- }
-}
-
-function _registerLinkedStylesheet(link, sourceNode, explicitHref) {
- if (!link || !sourceNode) return null;
+function _registerLinkedStylesheet(link, explicitHref) {
+ if (!link) return null;
const href = _linkedStylesheetHref(link, explicitHref);
- _linkedStylesheetNodes.set(link, sourceNode);
+ _linkedStylesheetNodes.set(link, true);
let sheet = _linkElementSheets.get(link);
if (!sheet) {
sheet = new CSSStyleSheet();
_linkElementSheets.set(link, sheet);
}
- sheet._bindLinkedOwner(link, sourceNode, href, _linkedStylesheetIsOriginClean(href));
+ sheet._bindLinkedOwner(link, href);
return sheet;
}
globalThis.__obscura_registerLinkedStylesheet = _registerLinkedStylesheet;
@@ -550,10 +554,12 @@ function _cssImportApplies(media) {
}
async function _fetchLinkedCss(url, pageOrigin, depth = 0, seen = new Set()) {
- if (depth > 4 || seen.has(url)) return "";
+ if (depth > 4 || seen.has(url)) {
+ return { css: "", responseUrl: url, originClean: true };
+ }
seen.add(url);
- const raw = await Deno.core.ops.op_fetch_url(
- url, "GET", "{}", new Uint8Array(0), pageOrigin, "no-cors", "same-origin"
+ const raw = await __obscuraCore.ops.op_fetch_url(
+ url, "GET", "{}", new Uint8Array(0), pageOrigin, "no-cors", "same-origin", true
);
const parsed = JSON.parse(raw);
if (parsed.blocked || parsed.status >= 400 || parsed.status === 0) {
@@ -578,8 +584,16 @@ async function _fetchLinkedCss(url, pageOrigin, depth = 0, seen = new Set()) {
const imported = await Promise.all(imports.map(importUrl =>
_fetchLinkedCss(importUrl, pageOrigin, depth + 1, new Set(seen))
));
- imported.push(_rebaseCssUrls(css, url));
- return imported.filter(Boolean).join("\n");
+ const responseUrl = parsed.url || url;
+ const parts = imported.map(result => result.css).filter(Boolean);
+ parts.push(_rebaseCssUrls(css, responseUrl));
+ let ownOriginClean = false;
+ try { ownOriginClean = new URL(responseUrl).origin === pageOrigin; } catch(e) {}
+ return {
+ css: parts.filter(Boolean).join("\n"),
+ responseUrl,
+ originClean: ownOriginClean && imported.every(result => result.originClean),
+ };
}
// A dynamically-inserted <link rel="stylesheet" href> must fetch, enter the
@@ -595,21 +609,25 @@ async function _loadLinkedStylesheet(c) {
if (!rel.split(/\s+/).includes('stylesheet')) return;
const href = c.getAttribute('href');
if (!href) return;
+ if (!c.getAttribute('rel') && c.rel) c.setAttribute('rel', String(c.rel));
+ if (Object.prototype.hasOwnProperty.call(c, 'media')) {
+ if (c.media) c.setAttribute('media', String(c.media));
+ else c.removeAttribute('media');
+ }
+ if (Object.prototype.hasOwnProperty.call(c, 'disabled')) {
+ if (c.disabled) c.setAttribute('disabled', '');
+ else c.removeAttribute('disabled');
+ }
const fullUrl = _resolveResourceUrl(href);
let pageOrigin = "";
- try { pageOrigin = new URL(fullUrl).origin; } catch(e) {}
+ try { pageOrigin = new URL(_domParse("document_url") || "about:blank").origin; } catch(e) {}
try {
- const css = await _fetchLinkedCss(fullUrl, pageOrigin);
- const previous = _linkedStylesheetNodes.get(c);
- if (previous?.parentNode) previous.parentNode.removeChild(previous);
- const media = c.getAttribute("media") || "";
- const style = document.createElement("style");
- style.setAttribute("data-obscura-linked", fullUrl);
- style.textContent = css;
- _registerLinkedStylesheet(c, style, fullUrl);
- if (c.parentNode && !c.disabled && _cssImportApplies(media)) {
- c.parentNode.insertBefore(style, c.nextSibling);
- }
+ const loaded = await _fetchLinkedCss(fullUrl, pageOrigin);
+ __obscuraCore.ops.op_external_stylesheet_set(
+ c._nid, loaded.css, loaded.responseUrl, loaded.originClean,
+ globalThis.__obscura_frameId || 0
+ );
+ _registerLinkedStylesheet(c, loaded.responseUrl);
try { c.dispatchEvent(new Event('load', { bubbles: true })); } catch(e) {}
} catch(e) {
try { c.dispatchEvent(new Event('error', { bubbles: true })); } catch(e) {}
@@ -821,13 +839,13 @@ const _consoleFn = (level, args) => {
}
return String(a);
}).join(" ");
- const eventArgs = Deno.core.ops.op_runtime_events_enabled()
+ const eventArgs = __obscuraCore.ops.op_runtime_events_enabled()
? JSON.stringify(args.map(a => {
try { return _consoleRemoteObject(a); }
catch { return { type: typeof a, description: "<unavailable>" }; }
}))
: "";
- Deno.core.ops.op_console_msg(level, text, eventArgs);
+ __obscuraCore.ops.op_console_msg(level, text, eventArgs);
} catch {}
};
@@ -876,7 +894,7 @@ const _scheduleAfter = (delay, fn) => {
// tasks, so leave them pending instead of aborting or incorrectly turning a
// task into a microtask. Normal browser and CDP execution always takes the
// task-queue path below.
- if (!Deno.core.ops.op_async_runtime_available()) {
+ if (!__obscuraCore.ops.op_async_runtime_available()) {
return undefined;
}
// A child frame realm cannot use deno_core's timer queue: op_timer_queue
@@ -893,21 +911,21 @@ const _scheduleAfter = (delay, fn) => {
const frameTimerId = -(++_frameTimerSeq);
const state = { cancelled: false };
_frameTimerStates.set(frameTimerId, state);
- Deno.core.ops.op_sleep(d).then(() => {
+ __obscuraCore.ops.op_sleep(d).then(() => {
_frameTimerStates.delete(frameTimerId);
if (state.cancelled) return;
- Deno.core.ops.op_begin_render_task?.();
+ __obscuraCore.ops.op_begin_render_task?.();
fn();
});
return frameTimerId;
}
// The callback runs only when the embedder pumps the event loop, after the
// current microtask checkpoint.
- return Deno.core.queueUserTimer(0, false, d, () => {
+ return __obscuraCore.queueUserTimer(0, false, d, () => {
// HTML timer/observer/rAF delivery starts a new task. Freeze animation
// time lazily on that task's first style/layout read so a callback that
// waited in the host queue samples its actual delivery instant.
- Deno.core.ops.op_begin_render_task?.();
+ __obscuraCore.ops.op_begin_render_task?.();
return fn();
});
};
@@ -918,7 +936,7 @@ const _cancelScheduled = (nativeId) => {
if (state) state.cancelled = true;
_frameTimerStates.delete(nativeId);
}
- else Deno.core.cancelTimer(nativeId);
+ else __obscuraCore.cancelTimer(nativeId);
};
// Timers accept a string first arg per the HTML spec (e.g. the Aliyun WAF
@@ -1134,7 +1152,7 @@ let _browserPostedTaskWakePending = false;
const _invalidPostedTaskGeneration = -1;
function _browserPostedTaskGeneration() {
- return Deno.core.ops.op_posted_task_generation(_realmFrameId);
+ return __obscuraCore.ops.op_posted_task_generation(_realmFrameId);
}
function _browserPostedTaskDiscardQueue(queue) {
@@ -1148,8 +1166,8 @@ function _browserPostedTaskDiscardQueue(queue) {
function _browserPostedTaskScheduleWake() {
if (_browserPostedTaskWakePending) return;
- if (!Deno.core.ops.op_async_runtime_available()) return;
- const generation = Deno.core.ops.op_posted_task(
+ if (!__obscuraCore.ops.op_async_runtime_available()) return;
+ const generation = __obscuraCore.ops.op_posted_task(
_realmFrameId, _browserPostedTaskRunOne);
_browserPostedTaskWakePending = generation !== _invalidPostedTaskGeneration;
if (!_browserPostedTaskWakePending) {
@@ -1191,7 +1209,7 @@ function _browserPostedTaskRunOne(currentGeneration = _invalidPostedTaskGenerati
}
if (!callback) return;
- Deno.core.ops.op_begin_render_task?.();
+ __obscuraCore.ops.op_begin_render_task?.();
try { callback(); }
catch (error) { console.error("Posted task error:", error); }
finally {
@@ -1891,7 +1909,7 @@ function _eventTargetDispatch(target, event) {
const _customElementConstructionStack = [];
function __prepareInsertedScript(script) {
- if (!Deno.core.ops.op_script_try_start(script._nid)) return;
+ if (!__obscuraCore.ops.op_script_try_start(script._nid)) return;
const scriptType = (script.getAttribute('type') || '').trim().toLowerCase();
const isModule = scriptType === 'module';
const isImportMap = scriptType === 'importmap';
@@ -1905,7 +1923,7 @@ function __prepareInsertedScript(script) {
|| globalThis.location?.href
|| 'about:blank';
try {
- error = Deno.core.ops.op_add_import_map(script.textContent || '', base) || '';
+ error = __obscuraCore.ops.op_add_import_map(script.textContent || '', base) || '';
} catch (e) {
error = e && e.message ? e.message : String(e);
}
@@ -2177,11 +2195,10 @@ class Node {
);
}
const removedWindowNames = _windowNamedNamesInTree(c);
- const linkedStyle = c instanceof Element
- ? _linkedStylesheetNodes.get(c)
- : null;
- if (linkedStyle?.parentNode === this) {
- _dom("remove_child", linkedStyle._nid);
+ if (c instanceof Element && _linkedStylesheetNodes.has(c)) {
+ __obscuraCore.ops.op_external_stylesheet_remove(
+ c._nid, globalThis.__obscura_frameId || 0
+ );
_linkedStylesheetNodes.delete(c);
}
const parentConnected = this.isConnected;
@@ -2648,7 +2665,7 @@ function _applyDocQueryEncoding(u) {
let decoded;
try { decoded = decodeURIComponent(u.search.slice(1)); } catch (e) { return u; }
let reencoded;
- try { reencoded = Deno.core.ops.op_url_encode_query(decoded, _docEncoding(), _isSpecialScheme(u.protocol)); }
+ try { reencoded = __obscuraCore.ops.op_url_encode_query(decoded, _docEncoding(), _isSpecialScheme(u.protocol)); }
catch (e) { return u; }
const newSearch = '?' + reencoded;
if (newSearch === u.search) return u;
@@ -3147,7 +3164,7 @@ class Animation {
}
_native(action, value = 0) {
try {
- const changed = !!Deno.core.ops.op_waapi_control?.(this._nativeId, action, Number(value) || 0);
+ const changed = !!__obscuraCore.ops.op_waapi_control?.(this._nativeId, action, Number(value) || 0);
if (changed) _domMutationEpoch++;
return changed;
}
@@ -3167,7 +3184,7 @@ class Animation {
: this.effect._timing.iterations,
iterationsInfinite: this.effect._timing.iterations === Infinity,
};
- try { this._registered = !!Deno.core.ops.op_waapi_create?.(JSON.stringify(input)); }
+ try { this._registered = !!__obscuraCore.ops.op_waapi_create?.(JSON.stringify(input)); }
catch (_) { this._registered = false; }
if (this._registered) {
_waapiAnimations.add(this);
@@ -4314,6 +4331,7 @@ class Element extends Node {
}
this._frameId = 0;
this._iframeLoadingUrl = null;
+ this._iframeLoadedUrl = 'about:blank';
this._iframeDoc = new _IframeDocument(
'<!DOCTYPE html><html><head></head><body></body></html>', 'about:blank', this);
this._iframeWin = new _IframeWindow(this._iframeDoc, 'about:blank');
@@ -4329,20 +4347,28 @@ class Element extends Node {
this._resetIframeFrame();
this._iframeLoadingUrl = fullUrl;
const el = this;
- fetch(fullUrl, {mode: 'no-cors'}).then(async resp => {
+ let pageOrigin = '';
+ try { pageOrigin = new URL(_domParse('document_url') || 'about:blank').origin; } catch (_) {}
+ __obscuraCore.ops.op_fetch_url(
+ fullUrl, 'GET', '{}', new Uint8Array(0), pageOrigin,
+ 'no-cors', 'same-origin', true
+ ).then(raw => {
if (el._iframeLoadingUrl !== fullUrl) return;
- if (resp.ok || resp.type === 'opaque') {
- const html = await resp.text();
+ const response = JSON.parse(raw);
+ if (!response.blocked && response.status > 0 && response.status < 400) {
+ const html = response.body || '';
+ const loadedUrl = response.url || fullUrl;
+ el._iframeLoadedUrl = loadedUrl;
// Hand the document to the host, which gives this frame a realm of its
// own and runs the scripts that came with it (issue #600). The shim
// document below stays: it is what the parent reads through
// contentDocument.
const box = el.getBoundingClientRect();
- el._frameId = Deno.core.ops.op_frame_document_ready(
- fullUrl, html, Math.round(box.width) || 300, Math.round(box.height) || 150);
+ el._frameId = __obscuraCore.ops.op_frame_document_ready(
+ loadedUrl, html, Math.round(box.width) || 300, Math.round(box.height) || 150);
if (el._frameId) globalThis.__obscura_frameElements[el._frameId] = el;
- el._iframeDoc = new _IframeDocument(html, fullUrl, el);
- el._iframeWin = new _IframeWindow(el._iframeDoc, fullUrl);
+ el._iframeDoc = new _IframeDocument(html, loadedUrl, el);
+ el._iframeWin = new _IframeWindow(el._iframeDoc, loadedUrl);
// Bind the window to the realm the host just queued. This is what makes
// posting into the frame reach the frame's own listeners, and makes a
// message coming back out arrive with this window as its `source`.
@@ -4352,6 +4378,7 @@ class Element extends Node {
globalThis.__obscura_frameElements[el._frameId] = el;
}
} else {
+ el._iframeLoadedUrl = fullUrl;
el._iframeDoc = new _IframeDocument('<!DOCTYPE html><html><head></head><body></body></html>', fullUrl, el);
el._iframeWin = new _IframeWindow(el._iframeDoc, fullUrl);
}
@@ -4362,6 +4389,7 @@ class Element extends Node {
el.dispatchEvent(new Event('load'));
}).catch(() => {
if (el._iframeLoadingUrl !== fullUrl) return;
+ el._iframeLoadedUrl = fullUrl;
el._iframeDoc = new _IframeDocument('<!DOCTYPE html><html><head></head><body></body></html>', fullUrl, el);
el._iframeWin = new _IframeWindow(el._iframeDoc, fullUrl);
@@ -4374,8 +4402,11 @@ class Element extends Node {
if (real?.document) return real.document;
if (this._iframeDoc) {
const pageOrigin = (function(){ try { return new URL(_domParse("document_url")).origin; } catch(e) { return ''; } })();
- const iframeOrigin = (function(url){ try { return new URL(url).origin; } catch(e) { return ''; } })(this.src);
- if (pageOrigin === iframeOrigin || this.src === '' || this.src === 'about:blank' || !this.src.includes('://')) {
+ if (this.src === '' || this.src === 'about:blank' || this._iframeLoadedUrl === 'about:blank') {
+ return this._iframeDoc;
+ }
+ const iframeOrigin = (function(url){ try { return new URL(url).origin; } catch(e) { return ''; } })(this._iframeLoadedUrl);
+ if (pageOrigin !== '' && pageOrigin === iframeOrigin) {
return this._iframeDoc;
}
return null; // Cross-origin: blocked
@@ -4555,10 +4586,10 @@ class Element extends Node {
const encoded = pairs.join('&');
if (method === 'POST') {
- Deno.core.ops.op_navigate(targetUrl, 'POST', encoded);
+ __obscuraCore.ops.op_navigate(targetUrl, 'POST', encoded);
} else {
const sep = targetUrl.includes('?') ? '&' : '?';
- Deno.core.ops.op_navigate(targetUrl + (encoded ? sep + encoded : ''), 'GET', '');
+ __obscuraCore.ops.op_navigate(targetUrl + (encoded ? sep + encoded : ''), 'GET', '');
}
}
reset() {
@@ -4627,9 +4658,9 @@ class Element extends Node {
return metrics ? metrics.height : 20;
}
_renderClientMetrics() {
- if (typeof Deno.core.ops.op_layout_geometry !== 'function') return null;
+ if (typeof __obscuraCore.ops.op_layout_geometry !== 'function') return null;
try {
- const raw = Deno.core.ops.op_layout_geometry(String(this._nid | 0));
+ const raw = __obscuraCore.ops.op_layout_geometry(String(this._nid | 0));
if (!raw) return { width: 0, height: 0 };
const geometry = JSON.parse(raw);
if (geometry
@@ -4652,9 +4683,9 @@ class Element extends Node {
// CSSOM View returns an empty rect list for the latter, while the former
// deliberately retains Obscura's compatibility geometry.
_renderBoxGeometry() {
- if (typeof Deno.core.ops.op_layout_geometry !== 'function') return undefined;
+ if (typeof __obscuraCore.ops.op_layout_geometry !== 'function') return undefined;
try {
- const raw = Deno.core.ops.op_layout_geometry(String(this._nid | 0));
+ const raw = __obscuraCore.ops.op_layout_geometry(String(this._nid | 0));
if (!raw) return null;
const geometry = JSON.parse(raw);
if (geometry
@@ -4712,18 +4743,18 @@ class Element extends Node {
return t === 'HTML' || t === 'BODY';
}
_renderScrollMetrics() {
- if (typeof Deno.core.ops.op_layout_metrics !== 'function') return null;
+ if (typeof __obscuraCore.ops.op_layout_metrics !== 'function') return null;
try {
- const raw = Deno.core.ops.op_layout_metrics();
+ const raw = __obscuraCore.ops.op_layout_metrics();
return raw ? JSON.parse(raw) : null;
} catch (_e) {
return null;
}
}
_renderElementScrollMetrics() {
- if (typeof Deno.core.ops.op_element_scroll_metrics !== 'function') return undefined;
+ if (typeof __obscuraCore.ops.op_element_scroll_metrics !== 'function') return undefined;
try {
- const raw = Deno.core.ops.op_element_scroll_metrics(String(this._nid | 0));
+ const raw = __obscuraCore.ops.op_element_scroll_metrics(String(this._nid | 0));
if (!raw) return null;
const metrics = JSON.parse(raw);
return metrics && metrics.hasBox !== false ? metrics : null;
@@ -4732,27 +4763,27 @@ class Element extends Node {
}
}
_renderScrollOffset() {
- if (typeof Deno.core.ops.op_scroll_offset !== 'function') return null;
+ if (typeof __obscuraCore.ops.op_scroll_offset !== 'function') return null;
try {
- const raw = Deno.core.ops.op_scroll_offset();
+ const raw = __obscuraCore.ops.op_scroll_offset();
return raw ? JSON.parse(raw) : null;
} catch (_e) {
return null;
}
}
_setRenderScroll(x, y) {
- if (typeof Deno.core.ops.op_scroll_to !== 'function') return null;
+ if (typeof __obscuraCore.ops.op_scroll_to !== 'function') return null;
try {
- const raw = Deno.core.ops.op_scroll_to(+x || 0, +y || 0);
+ const raw = __obscuraCore.ops.op_scroll_to(+x || 0, +y || 0);
return raw ? JSON.parse(raw) : null;
} catch (_e) {
return null;
}
}
_setRenderElementScroll(x, y) {
- if (typeof Deno.core.ops.op_element_scroll_to !== 'function') return null;
+ if (typeof __obscuraCore.ops.op_element_scroll_to !== 'function') return null;
try {
- const raw = Deno.core.ops.op_element_scroll_to(String(this._nid | 0), +x || 0, +y || 0);
+ const raw = __obscuraCore.ops.op_element_scroll_to(String(this._nid | 0), +x || 0, +y || 0);
return raw ? JSON.parse(raw) : null;
} catch (_e) {
return null;
@@ -5325,7 +5356,7 @@ class Document extends Node {
if (this !== globalThis.document) _throwDocumentDomainSecurityError();
const current = this.domain;
if (!current) _throwDocumentDomainSecurityError();
- const candidate = Deno.core.ops.op_document_domain_candidate(current, input);
+ const candidate = __obscuraCore.ops.op_document_domain_candidate(current, input);
if (!candidate) _throwDocumentDomainSecurityError();
// This runtime currently has one top-level browsing context and no
// principal-backed same-origin-domain comparison. Persisting the
@@ -5337,7 +5368,7 @@ class Document extends Node {
}
get referrer() { return _domParse("document_referrer") ?? ""; }
get location() { return globalThis.location; }
- set location(url) { Deno.core.ops.op_navigate(_resolveUrl(String(url)), 'GET', ''); }
+ set location(url) { __obscuraCore.ops.op_navigate(_resolveUrl(String(url)), 'GET', ''); }
get defaultView() { return globalThis; }
get nodeType() { return 9; }
get nodeName() { return "#document"; }
@@ -5825,11 +5856,11 @@ class Document extends Node {
get links() { return this.querySelectorAll("a[href], area[href]"); }
get scripts() { return this.querySelectorAll("script"); }
get cookie() {
- return Deno.core.ops.op_get_cookies();
+ return __obscuraCore.ops.op_get_cookies();
}
set cookie(v) {
if (!v) return;
- Deno.core.ops.op_set_cookie(v);
+ __obscuraCore.ops.op_set_cookie(v);
}
// Inserts into the document's input stream, which the host keeps alive across calls.
// Parsing each call on its own would lose every construct that spans two of them. This is
@@ -6077,7 +6108,7 @@ class HTMLImageElement extends Element {
this._imageQueued = false;
this._imageInitialized = false;
this._imageCompletionDeferred = false;
- this._imageComplete = typeof Deno.core.ops.op_image_metadata === "function"
+ this._imageComplete = typeof __obscuraCore.ops.op_image_metadata === "function"
? true
: !this.getAttribute("src");
this._imageDecoded = false;
@@ -6204,7 +6235,7 @@ class HTMLImageElement extends Element {
// The lightweight build has no retained render-resource cache. It still
// preserves the historical non-blocking Image lifecycle so preloaders do
// not hang while rendering is disabled.
- const hasMetadataLoader = typeof Deno.core.ops.op_load_image_metadata === "function";
+ const hasMetadataLoader = typeof __obscuraCore.ops.op_load_image_metadata === "function";
this._adoptImageCandidate(hasMetadataLoader ? "" : this.src);
this._imageCompletionDeferred = true;
this._refreshImageFromCache(true);
@@ -6247,7 +6278,7 @@ class HTMLImageElement extends Element {
this._applyImageMetadata(metadata, request, true);
};
try {
- const op = Deno.core.ops.op_load_image_metadata;
+ const op = __obscuraCore.ops.op_load_image_metadata;
if (typeof op === "function") {
Promise.resolve(op(this._nid >>> 0)).then(
raw => {
@@ -6271,7 +6302,7 @@ class HTMLImageElement extends Element {
_refreshImageFromCache(deferCompletion) {
try {
- const op = Deno.core.ops.op_image_metadata;
+ const op = __obscuraCore.ops.op_image_metadata;
if (typeof op !== "function") return;
const metadata = JSON.parse(op(this._nid >>> 0, true));
if (!metadata) return;
@@ -6324,7 +6355,7 @@ class HTMLImageElement extends Element {
const width = Number(metadata && metadata.width);
const height = Number(metadata && metadata.height);
const loaded = !!(metadata && metadata.ok)
- && (typeof Deno.core.ops.op_image_metadata !== "function"
+ && (typeof __obscuraCore.ops.op_image_metadata !== "function"
|| (Number.isFinite(width) && width > 0 && Number.isFinite(height) && height > 0));
if (loaded) {
this._imageDecoded = true;
@@ -6591,7 +6622,7 @@ function __currentUrl() {
}
globalThis.location = {
get href() { return __currentUrl(); },
- set href(url) { var r = _resolveUrl(url); globalThis.__virtualUrl = r; Deno.core.ops.op_navigate(r, 'GET', ''); },
+ set href(url) { var r = _resolveUrl(url); globalThis.__virtualUrl = r; __obscuraCore.ops.op_navigate(r, 'GET', ''); },
get origin() { try { return new URL(this.href).origin; } catch { return ""; } },
get protocol() { try { return new URL(this.href).protocol; } catch { return ""; } },
get host() { try { return new URL(this.href).host; } catch { return ""; } },
@@ -6601,14 +6632,14 @@ globalThis.location = {
get hash() { try { return new URL(this.href).hash; } catch { return ""; } },
get port() { try { return new URL(this.href).port; } catch { return ""; } },
toString() { return this.href; },
- assign(url) { var r = _resolveUrl(url); globalThis.__virtualUrl = r; Deno.core.ops.op_navigate(r, 'GET', ''); },
- reload() { var r = _resolveUrl(this.href); globalThis.__virtualUrl = r; Deno.core.ops.op_navigate(r, 'GET', ''); },
- replace(url) { var r = _resolveUrl(url); globalThis.__virtualUrl = r; Deno.core.ops.op_navigate(r, 'GET', ''); },
+ assign(url) { var r = _resolveUrl(url); globalThis.__virtualUrl = r; __obscuraCore.ops.op_navigate(r, 'GET', ''); },
+ reload() { var r = _resolveUrl(this.href); globalThis.__virtualUrl = r; __obscuraCore.ops.op_navigate(r, 'GET', ''); },
+ replace(url) { var r = _resolveUrl(url); globalThis.__virtualUrl = r; __obscuraCore.ops.op_navigate(r, 'GET', ''); },
};
const _locationObj = globalThis.location;
Object.defineProperty(globalThis, 'location', {
get() { return _locationObj; },
- set(url) { var r = _resolveUrl(String(url)); globalThis.__virtualUrl = r; Deno.core.ops.op_navigate(r, 'GET', ''); },
+ set(url) { var r = _resolveUrl(String(url)); globalThis.__virtualUrl = r; __obscuraCore.ops.op_navigate(r, 'GET', ''); },
configurable: false,
enumerable: true,
});
@@ -7294,7 +7325,7 @@ globalThis.fetch = async (input, init = {}) => {
throw new TypeError("Failed to execute 'fetch': '" + fetchCredentials + "' is not a valid RequestCredentials value");
}
const pageOrigin = (function() { try { const u = new URL(_domParse("document_url") || "about:blank"); return u.origin; } catch(e) { return ""; } })();
- const raw = await Deno.core.ops.op_fetch_url(url, method, hdrs, body, pageOrigin, fetchMode, fetchCredentials);
+ const raw = await __obscuraCore.ops.op_fetch_url(url, method, hdrs, body, pageOrigin, fetchMode, fetchCredentials, false);
const parsed = JSON.parse(raw);
if (parsed.blocked) {
const err = new TypeError('net::ERR_FAILED');
@@ -7307,7 +7338,9 @@ globalThis.fetch = async (input, init = {}) => {
}
const respType = parsed.status === 0 || parsed.opaque ? "opaque" : "basic";
const exposeRedirectMetadata = respType !== "opaque" && fetchRedirect === "follow";
- const responseBody = parsed.bodyBase64 ? _base64ToUint8Array(parsed.bodyBase64) : (parsed.body || "");
+ const responseBody = respType === "opaque"
+ ? null
+ : (parsed.bodyBase64 ? _base64ToUint8Array(parsed.bodyBase64) : (parsed.body || ""));
const response = new Response(responseBody, {
status: parsed.status,
statusText: "",
@@ -7608,14 +7641,14 @@ _markNative(XMLHttpRequest.prototype.getAllResponseHeaders);
// the input is not a valid URL.
function _urlParseOp(url, base) {
try {
- const s = Deno.core.ops.op_url_parse(String(url), (base === undefined || base === null) ? "" : String(base));
+ const s = __obscuraCore.ops.op_url_parse(String(url), (base === undefined || base === null) ? "" : String(base));
const c = JSON.parse(s);
return (c && c.ok) ? c : null;
} catch (e) { return null; }
}
function _urlSetOp(href, part, value) {
try {
- const s = Deno.core.ops.op_url_set(String(href), part, String(value));
+ const s = __obscuraCore.ops.op_url_set(String(href), part, String(value));
const c = JSON.parse(s);
return (c && c.ok) ? c : null;
} catch (e) { return null; }
@@ -7624,7 +7657,7 @@ function _urlSetOp(href, part, value) {
// failure. Cheaper than _urlParseOp for callers that only need the href.
function _urlResolveOp(href, base) {
try {
- const r = Deno.core.ops.op_url_resolve(String(href), (base === undefined || base === null) ? "" : String(base));
+ const r = __obscuraCore.ops.op_url_resolve(String(href), (base === undefined || base === null) ? "" : String(base));
return r ? r : null;
} catch (e) { return null; }
}
@@ -7757,7 +7790,7 @@ function _decodeBodyWithCharset(bytes, headers) {
if (typeof Response === 'undefined') {
globalThis.Response = class Response {
constructor(body, init = {}) {
- this._bodyBytes = _bodyToUint8Array(body); this.status = init.status || 200; this.statusText = init.statusText || '';
+ this._bodyBytes = _bodyToUint8Array(body); this.status = init.status === undefined ? 200 : Number(init.status); this.statusText = init.statusText || '';
this.ok = this.status >= 200 && this.status < 300;
this.headers = new Headers(init.headers);
this.type = init.type || 'basic'; this.url = init.url || ''; this.redirected = !!init.redirected;
@@ -7954,10 +7987,10 @@ function _roNodeDepth(target) {
}
function _roMeasurement(target, suppliedGeometry, suppliedByBatch = false) {
let geometry = suppliedGeometry ?? null;
- const hasRenderer = typeof Deno.core.ops.op_layout_geometry === "function";
+ const hasRenderer = typeof __obscuraCore.ops.op_layout_geometry === "function";
if (!suppliedByBatch && hasRenderer && target?._nid != null) {
try {
- const raw = Deno.core.ops.op_layout_geometry(String(target._nid | 0));
+ const raw = __obscuraCore.ops.op_layout_geometry(String(target._nid | 0));
geometry = raw ? JSON.parse(raw) : null;
} catch (_error) {}
}
@@ -8055,7 +8088,7 @@ function _roMeasurement(target, suppliedGeometry, suppliedByBatch = false) {
function _roMeasurements(targets) {
const measurements = new Map();
if (!targets.length) return measurements;
- const bulk = Deno.core.ops.op_resize_observer_measurements;
+ const bulk = __obscuraCore.ops.op_resize_observer_measurements;
if (typeof bulk === "function"
&& targets.every(target => target?._nid != null)) {
try {
@@ -8223,7 +8256,7 @@ if (typeof TextDecoder === 'undefined') {
if (label === undefined) {
name = 'utf-8';
} else {
- name = Deno.core.ops.op_encoding_for_label(String(label));
+ name = __obscuraCore.ops.op_encoding_for_label(String(label));
if (!name) throw new RangeError("Failed to construct 'TextDecoder': The encoding label provided ('" + label + "') is invalid.");
}
const o = options || {};
@@ -8243,7 +8276,7 @@ if (typeof TextDecoder === 'undefined') {
return _utf8DecodeBytes(bytes, off);
}
// Legacy encodings / fatal mode: encoding_rs via the op.
- const r = JSON.parse(Deno.core.ops.op_text_decode(this.encoding, bytes, this.fatal, this.ignoreBOM));
+ const r = JSON.parse(__obscuraCore.ops.op_text_decode(this.encoding, bytes, this.fatal, this.ignoreBOM));
if (!r.ok) throw new TypeError("Failed to execute 'decode' on 'TextDecoder': The encoded data was not valid.");
return r.v;
}
@@ -8473,9 +8506,9 @@ globalThis.getComputedStyle = (el) => {
if (snapshot.epoch === _domMutationEpoch && !hasRunningAnimation) return;
snapshot.epoch = _domMutationEpoch;
snapshot.rendered = null;
- if (typeof Deno.core.ops.op_computed_style === 'function' && el?._nid != null) {
+ if (typeof __obscuraCore.ops.op_computed_style === 'function' && el?._nid != null) {
try {
- const raw = Deno.core.ops.op_computed_style(String(el._nid | 0));
+ const raw = __obscuraCore.ops.op_computed_style(String(el._nid | 0));
snapshot.rendered = raw ? JSON.parse(raw) : null;
} catch (e) {}
}
@@ -8772,6 +8805,8 @@ class CSSRuleList {
*[Symbol.iterator]() { for (let i = 0; i < this.length; i++) yield this.item(i); }
}
+const _cssStyleSheetPrivate = new WeakMap();
+
class CSSStyleSheet {
constructor(_options) {
this.ownerRule = null;
@@ -8784,48 +8819,84 @@ class CSSStyleSheet {
this._rules = [];
this._cssRules = new CSSRuleList(this);
this._adopters = new Set();
+ _cssStyleSheetPrivate.set(this, {
+ linked: false,
+ href: null,
+ originClean: true,
+ sourceText: "",
+ });
}
get type() { return "text/css"; }
get ownerNode() { return this._ownerNode; }
get parentStyleSheet() { return null; }
- get href() { return this._href; }
+ get href() { return _cssStyleSheetPrivate.get(this)?.href || null; }
get title() { return this._ownerNode?.getAttribute?.("title") || ""; }
get cssRules() {
- this._assertOriginClean();
this._refreshFromOwner();
+ this._assertOriginClean();
return this._cssRules;
}
get rules() { return this.cssRules; }
_bindOwner(ownerNode, sourceNode = ownerNode) {
+ const state = _cssStyleSheetPrivate.get(this);
+ state.linked = false;
+ state.href = null;
+ state.originClean = true;
+ state.sourceText = "";
this._ownerNode = ownerNode;
this._sourceNode = sourceNode;
this._sourceText = null;
this._refreshFromOwner();
}
- _bindLinkedOwner(ownerNode, sourceNode, href, originClean) {
+ _bindLinkedOwner(ownerNode, href) {
+ const state = _cssStyleSheetPrivate.get(this);
+ state.linked = true;
+ state.href = href || null;
+ state.originClean = false;
+ state.sourceText = "";
this._ownerNode = ownerNode;
- this._sourceNode = sourceNode;
- this._sourceText = null;
+ this._sourceNode = null;
+ this._sourceText = "";
this._href = href || null;
- this._originClean = originClean !== false;
- if (this._originClean) this._refreshFromOwner();
- else {
- this._setRules([]);
- this._sourceText = sourceNode?.textContent || "";
- }
+ this._originClean = false;
+ this._setRules([]);
+ this._refreshFromOwner();
}
_assertOriginClean() {
- if (!this._originClean) {
+ if (!_cssStyleSheetPrivate.get(this)?.originClean) {
throw new DOMException("Cannot access rules in a cross-origin stylesheet", "SecurityError");
}
}
_refreshFromOwner() {
- if (!this._sourceNode || !this._originClean) return;
- const text = this._sourceNode.textContent || "";
- if (text === this._sourceText) return;
+ const state = _cssStyleSheetPrivate.get(this);
+ if (!state) return;
+ let text;
+ if (state.linked) {
+ if (!this._ownerNode) return;
+ let loaded;
+ try {
+ loaded = JSON.parse(__obscuraCore.ops.op_external_stylesheet_get(
+ this._ownerNode._nid, globalThis.__obscura_frameId || 0
+ ));
+ } catch(e) { loaded = null; }
+ state.originClean = loaded?.originClean === true;
+ this._originClean = state.originClean;
+ if (!state.originClean) {
+ state.sourceText = "";
+ this._sourceText = "";
+ this._setRules([]);
+ return;
+ }
+ text = String(loaded.css || "");
+ } else {
+ if (!this._sourceNode) return;
+ text = this._sourceNode.textContent || "";
+ }
+ if (text === state.sourceText) return;
const parsed = _splitTopLevelCssRules(text);
const rules = parsed.rules.map(_cssRuleFromText).filter(Boolean);
this._setRules(rules);
+ state.sourceText = text;
this._sourceText = text;
}
_setRules(rules) {
@@ -8836,12 +8907,20 @@ class CSSStyleSheet {
_serializeText() { return this._rules.map(rule => rule.cssText).join("\n"); }
_ruleChanged() {
const text = this._serializeText();
+ const state = _cssStyleSheetPrivate.get(this);
+ if (state) state.sourceText = text;
this._sourceText = text;
- // DOM text is the renderer bridge for this bounded CSSOM implementation:
- // its ordinary style-element mutation path invalidates cascade/layout.
- // Avoiding the observable text rewrite requires a future native effective-
- // source channel shared by CSSOM and the renderer.
- if (this._sourceNode && this._sourceNode.textContent !== text) this._sourceNode.textContent = text;
+ if (state?.linked && this._ownerNode) {
+ __obscuraCore.ops.op_external_stylesheet_set(
+ this._ownerNode._nid,
+ text,
+ state.href || globalThis.document?.URL || "about:blank",
+ true,
+ globalThis.__obscura_frameId || 0,
+ );
+ } else if (this._sourceNode && this._sourceNode.textContent !== text) {
+ this._sourceNode.textContent = text;
+ }
_syncAdoptedStyleSheet(this);
}
insertRule(rule, index = 0) {
@@ -8887,10 +8966,7 @@ class CSSStyleSheet {
const _styleElementSheets = new WeakMap();
function _styleElementIsCssomBridge(style) {
- return style.hasAttribute("data-obscura-adopted")
- || style.hasAttribute("data-obscura-linked")
- || style.hasAttribute("data-obscura-external-stylesheets")
- || style.hasAttribute("data-obscura-inline-import");
+ return style.hasAttribute("data-obscura-adopted");
}
function _styleElementHasCssSheet(style) {
if (!style || style.localName !== "style" || !style.isConnected) return false;
@@ -8935,7 +9011,7 @@ function _sheetForLinkElement(link) {
}
let sheet = _linkElementSheets.get(link);
if (!sheet) {
- sheet = _registerLinkedStylesheet(link, _linkedStylesheetNodes.get(link));
+ sheet = _registerLinkedStylesheet(link);
}
return sheet;
}
@@ -9539,7 +9615,7 @@ function _ioClipsOverflow(value) {
function _ioMeasurements(elements) {
const measurements = new Map();
if (!elements.length) return measurements;
- const bulk = Deno.core.ops.op_intersection_observer_measurements;
+ const bulk = __obscuraCore.ops.op_intersection_observer_measurements;
const nativeElements = elements.filter(element => element?._nid != null);
if (typeof bulk !== "function" || !nativeElements.length) return measurements;
try {
@@ -10062,7 +10138,7 @@ globalThis.PromiseRejectionEvent = class PromiseRejectionEvent extends Event {
};
_markNative(globalThis.PromiseRejectionEvent);
-Deno.core.setUnhandledPromiseRejectionHandler((promise, reason) => {
+__obscuraCore.setUnhandledPromiseRejectionHandler((promise, reason) => {
const event = new PromiseRejectionEvent("unhandledrejection", {
promise,
reason,
@@ -10078,7 +10154,7 @@ Deno.core.setUnhandledPromiseRejectionHandler((promise, reason) => {
return true;
});
-Deno.core.setHandledPromiseRejectionHandler((promise, reason) => {
+__obscuraCore.setHandledPromiseRejectionHandler((promise, reason) => {
const event = new PromiseRejectionEvent("rejectionhandled", { promise, reason });
globalThis.dispatchEvent(event);
if (typeof globalThis.onrejectionhandled === "function") {
@@ -10752,12 +10828,12 @@ globalThis.Crypto = class Crypto {
if (arr.byteLength > 65536) {
throw new DOMException("The requested length exceeds 65536 bytes", "QuotaExceededError");
}
- const bytes = Deno.core.ops.op_random_bytes(arr.byteLength);
+ const bytes = __obscuraCore.ops.op_random_bytes(arr.byteLength);
new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength).set(bytes);
return arr;
}
randomUUID() {
- const b = Deno.core.ops.op_random_bytes(16);
+ const b = __obscuraCore.ops.op_random_bytes(16);
b[6] = (b[6] & 0x0f) | 0x40; // version 4
b[8] = (b[8] & 0x3f) | 0x80; // variant 10xx
let s = "";
@@ -11244,8 +11320,8 @@ function _cssTopLevelComma(text) {
function _cssSupportsDeclaration(name, value) {
name = name.trim().toLowerCase();
value = value.trim();
- if (typeof Deno.core.ops.op_css_supports === "function") {
- try { return !!Deno.core.ops.op_css_supports(name, value); }
+ if (typeof __obscuraCore.ops.op_css_supports === "function") {
+ try { return !!__obscuraCore.ops.op_css_supports(name, value); }
catch (_) { return false; }
}
if (!value || _cssHasInvalidSupportsValueSyntax(value)) return false;
@@ -12687,7 +12763,7 @@ function _sendRealmMessage(targetFrameId, data, targetOrigin) {
// An unspecified targetOrigin stays permissive (empty string); the receiver
// enforces a specified one against its own origin in __obscura_deliverMessage.
const to = (targetOrigin === undefined || targetOrigin === null) ? '' : String(targetOrigin);
- Deno.core.ops.op_post_frame_message(
+ __obscuraCore.ops.op_post_frame_message(
targetFrameId >>> 0, globalThis.__obscura_frameId >>> 0, _realmOrigin(), to, json);
}
@@ -13011,7 +13087,7 @@ class _Canvas2D {
this._h = valid ? requestedHeight : 0;
this._buf = new Uint8ClampedArray(this._w * this._h * 4);
this._resetDrawingState();
- const register = Deno.core.ops.op_canvas_register_surface;
+ const register = __obscuraCore.ops.op_canvas_register_surface;
if (typeof register === 'function') {
// op2 accepts Uint8Array, while Canvas exposes Uint8ClampedArray. This
// second view shares the exact backing store; no pixel copy is made.
@@ -13030,7 +13106,7 @@ class _Canvas2D {
this._damageQueued = true;
queueMicrotask(() => {
this._damageQueued = false;
- const damage = Deno.core.ops.op_canvas_paint_damage;
+ const damage = __obscuraCore.ops.op_canvas_paint_damage;
if (typeof damage === 'function') damage(this.canvas._nid);
});
}
@@ -13311,10 +13387,10 @@ Element.prototype.attachShadow = function attachShadow(opts) {
if (!globalThis.__obscura_shadowHostNames.has(_ln) && _ln.indexOf('-') === -1) {
throw new DOMException('Failed to execute attachShadow on Element: this element does not support attachShadow', 'NotSupportedError');
}
- if (Deno.core.ops.op_shadow_root_info(this._nid)) {
+ if (__obscuraCore.ops.op_shadow_root_info(this._nid)) {
throw new DOMException('Failed to execute attachShadow on Element: the element already hosts a shadow tree.', 'NotSupportedError');
}
- const rootNid = Deno.core.ops.op_shadow_attach(this._nid, _mode);
+ const rootNid = __obscuraCore.ops.op_shadow_attach(this._nid, _mode);
if (rootNid < 0) {
throw new DOMException('Failed to execute attachShadow on Element: this element does not support attachShadow', 'NotSupportedError');
}
@@ -13333,7 +13409,7 @@ _markNative(Element.prototype.attachShadow);
function _shadowRootForHost(host, includeClosed) {
if (!host) return null;
- const info = Deno.core.ops.op_shadow_root_info(host._nid);
+ const info = __obscuraCore.ops.op_shadow_root_info(host._nid);
if (!info) return null;
const parts = info.split('\0');
if (!includeClosed && parts[1] !== 'open') return null;
@@ -14292,7 +14368,7 @@ if (!globalThis.crypto.subtle) {
name !== "SHA-512/224" && name !== "SHA-512/256") {
throw new DOMException("Unrecognized algorithm name", "NotSupportedError");
}
- return bufferOf(Deno.core.ops.op_subtle_digest(name, toBytes(data)));
+ return bufferOf(__obscuraCore.ops.op_subtle_digest(name, toBytes(data)));
},
async importKey(format, keyData, algorithm, extractable, keyUsages) {
@@ -14332,14 +14408,14 @@ if (!globalThis.crypto.subtle) {
if (alg.name === "HMAC") {
const hash = normalizeHash(alg.hash);
const len = alg.length ? Math.ceil(alg.length / 8) : hashBlockSize(hash);
- const bytes = Deno.core.ops.op_random_bytes(len);
+ const bytes = __obscuraCore.ops.op_random_bytes(len);
return makeKey("secret", extractable, { name: "HMAC", hash: { name: hash }, length: len * 8 }, keyUsages, bytes);
}
if (alg.name === "AES-CTR" || alg.name === "AES-CBC" || alg.name === "AES-GCM" || alg.name === "AES-KW") {
if (alg.length !== 128 && alg.length !== 192 && alg.length !== 256) {
throw new DOMException("AES key length must be 128, 192, or 256 bits", "OperationError");
}
- const bytes = Deno.core.ops.op_random_bytes(alg.length / 8);
+ const bytes = __obscuraCore.ops.op_random_bytes(alg.length / 8);
return makeKey("secret", extractable, { name: alg.name, length: alg.length }, keyUsages, bytes);
}
throw new DOMException("generateKey does not support " + alg.name, "NotSupportedError");
@@ -14350,7 +14426,7 @@ if (!globalThis.crypto.subtle) {
const bytes = keyBytes(key);
if (alg.name === "HMAC") {
const hash = key.algorithm && key.algorithm.hash ? key.algorithm.hash.name : normalizeHash(alg.hash);
- return bufferOf(runOp(() => Deno.core.ops.op_subtle_hmac(hash, bytes, toBytes(data))));
+ return bufferOf(runOp(() => __obscuraCore.ops.op_subtle_hmac(hash, bytes, toBytes(data))));
}
throw new DOMException("sign does not support " + alg.name, "NotSupportedError");
},
@@ -14360,7 +14436,7 @@ if (!globalThis.crypto.subtle) {
const bytes = keyBytes(key);
if (alg.name === "HMAC") {
const hash = key.algorithm && key.algorithm.hash ? key.algorithm.hash.name : normalizeHash(alg.hash);
- const mac = runOp(() => Deno.core.ops.op_subtle_hmac(hash, bytes, toBytes(data)));
+ const mac = runOp(() => __obscuraCore.ops.op_subtle_hmac(hash, bytes, toBytes(data)));
const sig = toBytes(signature);
if (sig.length !== mac.length) return false;
let diff = 0;
@@ -14381,13 +14457,13 @@ if (!globalThis.crypto.subtle) {
const hash = normalizeHash(alg.hash);
const salt = toBytes(alg.salt);
const iterations = alg.iterations >>> 0;
- return bufferOf(runOp(() => Deno.core.ops.op_subtle_pbkdf2(hash, bytes, salt, iterations, lenBytes)));
+ return bufferOf(runOp(() => __obscuraCore.ops.op_subtle_pbkdf2(hash, bytes, salt, iterations, lenBytes)));
}
if (alg.name === "HKDF") {
const hash = normalizeHash(alg.hash);
const salt = alg.salt != null ? toBytes(alg.salt) : new Uint8Array(0);
const info = alg.info != null ? toBytes(alg.info) : new Uint8Array(0);
- return bufferOf(runOp(() => Deno.core.ops.op_subtle_hkdf(hash, bytes, salt, info, lenBytes)));
+ return bufferOf(runOp(() => __obscuraCore.ops.op_subtle_hkdf(hash, bytes, salt, info, lenBytes)));
}
throw new DOMException("deriveBits does not support " + alg.name, "NotSupportedError");
},
@@ -14437,16 +14513,16 @@ if (!globalThis.crypto.subtle) {
if (tagLength !== 128) {
throw new DOMException("Only a 128-bit AES-GCM tag length is supported", "NotSupportedError");
}
- return bufferOf(runOp(() => Deno.core.ops.op_subtle_aes_gcm(encrypt, bytes, iv, aad, input)));
+ return bufferOf(runOp(() => __obscuraCore.ops.op_subtle_aes_gcm(encrypt, bytes, iv, aad, input)));
}
if (alg.name === "AES-CBC") {
const iv = toBytes(alg.iv);
- return bufferOf(runOp(() => Deno.core.ops.op_subtle_aes_cbc(encrypt, bytes, iv, input)));
+ return bufferOf(runOp(() => __obscuraCore.ops.op_subtle_aes_cbc(encrypt, bytes, iv, input)));
}
if (alg.name === "AES-CTR") {
const counter = toBytes(alg.counter);
const length = alg.length >>> 0;
- return bufferOf(runOp(() => Deno.core.ops.op_subtle_aes_ctr(bytes, counter, length, input)));
+ return bufferOf(runOp(() => __obscuraCore.ops.op_subtle_aes_ctr(bytes, counter, length, input)));
}
throw new DOMException((encrypt ? "encrypt" : "decrypt") + " does not support " + alg.name, "NotSupportedError");
}
@@ -15093,7 +15169,7 @@ if (typeof FontFace === 'undefined') {
}
}
_syncNative() {
- if (!this._ownerDocument || typeof Deno.core.ops.op_set_dynamic_fonts !== 'function') return;
+ if (!this._ownerDocument || typeof __obscuraCore.ops.op_set_dynamic_fonts !== 'function') return;
const registrations = [];
for (const face of this._faces) registrations.push({
...(face._cssConnected ? { skip: true } : {}),
@@ -15103,7 +15179,7 @@ if (typeof FontFace === 'undefined') {
weight: face.weight,
unicodeRange: face.unicodeRange
});
- Deno.core.ops.op_set_dynamic_fonts(JSON.stringify(registrations.filter(face => !face.skip)));
+ __obscuraCore.ops.op_set_dynamic_fonts(JSON.stringify(registrations.filter(face => !face.skip)));
_scheduleResizeRenderCheckpoint();
}
_faceChanged(face) {
diff --git a/crates/obscura-js/src/ops.rs b/crates/obscura-js/src/ops.rs
index 125b9f37..ba7fe5b7 100644
--- a/crates/obscura-js/src/ops.rs
+++ b/crates/obscura-js/src/ops.rs
@@ -16,7 +16,8 @@ use obscura_net::{RequestCredentials, RequestMode, ResourceRequest};
#[cfg(feature = "stealth")]
use obscura_net::StealthHttpClient;
use obscura_net::{
- CallbackRegistry, CookieJar, ObscuraHttpClient, RequestInfo, ResourceType, Response,
+ same_site, CallbackRegistry, CookieJar, ObscuraHttpClient, RequestInfo, ResourceType, Response,
+ SameSiteContext,
};
use tokio::sync::Mutex;
@@ -1326,6 +1327,108 @@ fn op_shadow_root_info(state: &OpState, host_nid: u32) -> String {
.unwrap_or_default()
}
+fn stylesheet_origin_clean(document_url: &str, response_url: &str) -> bool {
+ let (Ok(document), Ok(response)) =
+ (url::Url::parse(document_url), url::Url::parse(response_url))
+ else {
+ return false;
+ };
+ document.origin() == response.origin()
+}
+
+/// Install host-fetched CSS without manufacturing a page-visible `<style>`.
+#[op2(fast)]
+fn op_external_stylesheet_set(
+ state: &OpState,
+ owner_nid: u32,
+ #[string] css: String,
+ #[string] response_url: String,
+ imported_origin_clean: bool,
+ frame_id: u32,
+) -> bool {
+ let shared = frame_state(state, frame_id);
+ let mut state = shared.borrow_mut();
+ let owner = NodeId::new(owner_nid);
+ let valid_owner = state.dom.as_ref().is_some_and(|dom| {
+ dom.get_node(owner).is_some_and(|node| {
+ node.as_element()
+ .is_some_and(|element| matches!(element.local.as_ref(), "link" | "style"))
+ })
+ });
+ if !valid_owner {
+ return false;
+ }
+ let origin_clean = imported_origin_clean && stylesheet_origin_clean(&state.url, &response_url);
+ let connected = state
+ .dom
+ .as_ref()
+ .is_some_and(|dom| node_is_connected(dom, owner));
+ let changed = state
+ .dom
+ .as_ref()
+ .is_some_and(|dom| dom.replace_external_stylesheet(owner, css, origin_clean));
+ if changed && connected {
+ state.activity_generation = state.activity_generation.wrapping_add(1);
+ #[cfg(feature = "render")]
+ {
+ state.prepared_render = None;
+ state.pending_style_mutations.clear();
+ state.resolved_scroll = None;
+ }
+ }
+ changed
+}
+
+#[op2(fast)]
+fn op_external_stylesheet_remove(state: &OpState, owner_nid: u32, frame_id: u32) -> bool {
+ let shared = frame_state(state, frame_id);
+ let mut state = shared.borrow_mut();
+ let owner = NodeId::new(owner_nid);
+ let connected = state
+ .dom
+ .as_ref()
+ .is_some_and(|dom| node_is_connected(dom, owner));
+ let changed = state
+ .dom
+ .as_ref()
+ .is_some_and(|dom| dom.remove_external_stylesheet(owner));
+ if changed && connected {
+ state.activity_generation = state.activity_generation.wrapping_add(1);
+ #[cfg(feature = "render")]
+ {
+ state.prepared_render = None;
+ state.pending_style_mutations.clear();
+ state.resolved_scroll = None;
+ }
+ }
+ changed
+}
+
+/// Return CSSOM-readable bytes only for an origin-clean loaded sheet.
+#[op2]
+#[string]
+fn op_external_stylesheet_get(state: &OpState, owner_nid: u32, frame_id: u32) -> String {
+ let shared = frame_state(state, frame_id);
+ let state = shared.borrow();
+ let Some(sheet) = state
+ .dom
+ .as_ref()
+ .and_then(|dom| dom.external_stylesheet(NodeId::new(owner_nid)))
+ else {
+ return "null".to_string();
+ };
+ if !sheet.origin_clean {
+ return r#"{"originClean":false}"#.to_string();
+ }
+ let css = sheet
+ .sources
+ .iter()
+ .map(|source| source.as_ref())
+ .collect::<Vec<_>>()
+ .join("\n");
+ serde_json::json!({ "originClean": true, "css": css }).to_string()
+}
+
#[op2]
#[string]
fn op_dom(
@@ -2695,6 +2798,56 @@ fn preflight_allows_header(name: &str, allowed: &[&str], credentialed: bool) ->
&& allowed.contains(&"*"))
}
+fn visible_response_headers(
+ headers: &HashMap<String, String>,
+ cross_origin: bool,
+ credentials: FetchCredentials,
+) -> HashMap<String, String> {
+ const SAFE: [&str; 7] = [
+ "cache-control",
+ "content-language",
+ "content-length",
+ "content-type",
+ "expires",
+ "last-modified",
+ "pragma",
+ ];
+
+ let mut expose_all = false;
+ let mut exposed = Vec::new();
+ if cross_origin {
+ if let Some(value) = headers.get("access-control-expose-headers") {
+ for name in value
+ .split(',')
+ .map(str::trim)
+ .filter(|name| !name.is_empty())
+ {
+ if name == "*" && credentials != FetchCredentials::Include {
+ expose_all = true;
+ } else {
+ exposed.push(name);
+ }
+ }
+ }
+ }
+
+ headers
+ .iter()
+ .filter(|(name, _)| {
+ if name.eq_ignore_ascii_case("set-cookie") || name.eq_ignore_ascii_case("set-cookie2") {
+ return false;
+ }
+ !cross_origin
+ || expose_all
+ || SAFE.iter().any(|safe| name.eq_ignore_ascii_case(safe))
+ || exposed
+ .iter()
+ .any(|exposed| name.eq_ignore_ascii_case(exposed))
+ })
+ .map(|(name, value)| (name.clone(), value.clone()))
+ .collect()
+}
+
/// Build the JS-facing result for an intercepted request a CDP client chose to
/// fulfill (`Fetch.fulfillRequest`). Mirrors the normal fetch result contract:
/// `body` is a lossy text view and `bodyBase64` carries the exact bytes, which
@@ -2707,13 +2860,25 @@ fn intercept_fulfill_response(
body: &str,
body_base64: &str,
url: &str,
+ page_origin: &str,
+ mode: &str,
+ credentials: FetchCredentials,
+ internal_load: bool,
) -> serde_json::Value {
+ let cross_origin = request_origin(url).is_some_and(|origin| origin != page_origin);
+ let opaque = !internal_load && mode == "no-cors" && cross_origin;
+ let visible_headers = if opaque {
+ HashMap::new()
+ } else {
+ visible_response_headers(&headers, cross_origin, credentials)
+ };
serde_json::json!({
- "status": status,
- "body": body,
- "bodyBase64": body_base64,
+ "status": if opaque { 0 } else { status },
+ "body": if opaque { "" } else { body },
+ "bodyBase64": if opaque { "" } else { body_base64 },
"url": url,
- "headers": headers,
+ "headers": visible_headers,
+ "opaque": opaque,
})
}
@@ -2728,6 +2893,7 @@ async fn op_fetch_url(
#[string] origin: String,
#[string] mode: String,
#[string] credentials: String,
+ internal_load: bool,
) -> Result<String, deno_error::JsErrorBox> {
let body = body.to_vec();
tracing::debug!(
@@ -2816,6 +2982,7 @@ async fn op_fetch_url(
}
page_in_flight.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let _page_in_flight = PageInFlightGuard(page_in_flight);
+ let credentials = FetchCredentials::parse(&credentials);
// Slots the interception channel can override via Continue so a consumer
// can rewrite url/method/headers/body before the request goes out.
@@ -2844,7 +3011,18 @@ async fn op_fetch_url(
body: b,
body_base64: bb,
}) => {
- return Ok(intercept_fulfill_response(status, h, &b, &bb, &url).to_string());
+ return Ok(intercept_fulfill_response(
+ status,
+ h,
+ &b,
+ &bb,
+ &url,
+ &origin,
+ &mode,
+ credentials,
+ internal_load,
+ )
+ .to_string());
}
Ok(InterceptResolution::Fail { reason }) => {
return Ok(serde_json::json!({
@@ -2919,7 +3097,6 @@ async fn op_fetch_url(
origin.clone()
};
let is_cross_origin = !page_origin.is_empty() && initial_request_origin != page_origin;
- let credentials = FetchCredentials::parse(&credentials);
let req_method: reqwest::Method = method.parse().unwrap_or(reqwest::Method::GET);
@@ -3058,6 +3235,7 @@ async fn op_fetch_url(
credentials,
callbacks.clone(),
allow_private_network,
+ internal_load,
)
.await;
}
@@ -3076,6 +3254,7 @@ async fn op_fetch_url(
let mut redirects_followed: usize = 0;
let mut redirected_from = Vec::new();
let mut crossed_origin = is_cross_origin;
+ let cookie_initiator = url::Url::parse(&page_origin).ok();
let response = loop {
let mut req = client
.request(current_method.clone(), &current_url)
@@ -3093,7 +3272,15 @@ async fn op_fetch_url(
if credentials_allowed {
if let Some(ref jar) = cookie_jar {
if let Ok(parsed_url) = url::Url::parse(&current_url) {
- let cookie_header = jar.get_cookie_header(&parsed_url);
+ let context = if cookie_initiator
+ .as_ref()
+ .is_some_and(|source| same_site(source, &parsed_url))
+ {
+ SameSiteContext::SameSite
+ } else {
+ SameSiteContext::CrossSite
+ };
+ let cookie_header = jar.get_cookie_header_in_context(&parsed_url, context);
if !cookie_header.is_empty() {
req = req.header("Cookie", &cookie_header);
}
@@ -3362,15 +3549,22 @@ async fn op_fetch_url(
resp_body.len()
);
+ let opaque = !internal_load && mode == "no-cors" && crossed_origin;
+ let script_headers = if opaque {
+ HashMap::new()
+ } else {
+ visible_response_headers(&resp_headers, final_is_cross_origin, credentials)
+ };
+
Ok(serde_json::json!({
- "status": status,
- "body": resp_body,
- "bodyBase64": resp_body_base64,
+ "status": if opaque { 0 } else { status },
+ "body": if opaque { String::new() } else { resp_body },
+ "bodyBase64": if opaque { String::new() } else { resp_body_base64 },
"requestId": response_request_id,
"url": current_url,
"redirected": redirected,
- "opaque": mode == "no-cors" && crossed_origin,
- "headers": resp_headers,
+ "opaque": opaque,
+ "headers": script_headers,
})
.to_string())
}
@@ -3412,6 +3606,7 @@ async fn stealth_fetch_all(
credentials: FetchCredentials,
callbacks: Option<Arc<CallbackRegistry>>,
allow_private_network: bool,
+ internal_load: bool,
) -> Result<String, deno_error::JsErrorBox> {
let mut current_url = url.clone();
let mut current_method = method;
@@ -3424,6 +3619,7 @@ async fn stealth_fetch_all(
let mut crossed_origin = request_origin(&current_url)
.map(|request_origin| request_origin != page_origin)
.unwrap_or(false);
+ let cookie_initiator = url::Url::parse(&page_origin).ok();
let (status, resp_headers, resp_bytes): (u16, HashMap<String, String>, Vec<u8>) = loop {
let parsed_current = match url::Url::parse(&current_url) {
@@ -3447,13 +3643,23 @@ async fn stealth_fetch_all(
}
let credentials_allowed = credentials.allows(&page_origin, &current_url);
+ let cookie_context = credentials_allowed.then(|| {
+ if cookie_initiator
+ .as_ref()
+ .is_some_and(|source| same_site(source, &parsed_current))
+ {
+ SameSiteContext::SameSite
+ } else {
+ SameSiteContext::CrossSite
+ }
+ });
let r = stealth
- .send_single(
+ .send_single_with_context(
&current_method,
&parsed_current,
&req_headers,
&current_body,
- credentials_allowed,
+ cookie_context,
credentials_allowed,
)
.await
@@ -3579,14 +3785,21 @@ async fn stealth_fetch_all(
}
}
+ let opaque = !internal_load && mode == "no-cors" && crossed_origin;
+ let script_headers = if opaque {
+ HashMap::new()
+ } else {
+ visible_response_headers(&resp_headers, final_is_cross_origin, credentials)
+ };
+
Ok(serde_json::json!({
- "status": status,
- "body": resp_body,
- "bodyBase64": resp_body_base64,
+ "status": if opaque { 0 } else { status },
+ "body": if opaque { String::new() } else { resp_body },
+ "bodyBase64": if opaque { String::new() } else { resp_body_base64 },
"url": current_url,
"redirected": redirects_followed > 0,
- "opaque": mode == "no-cors" && crossed_origin,
- "headers": resp_headers,
+ "opaque": opaque,
+ "headers": script_headers,
})
.to_string())
}
@@ -3676,9 +3889,9 @@ mod tests {
use obscura_dom::ShadowRootMode;
use super::read_body_capped;
- use super::{pbkdf2_derive, push_capped, PBKDF2_MAX_ITERATIONS, PBKDF2_MAX_OUTPUT_BYTES};
- use super::intercept_fulfill_response;
+ use super::{intercept_fulfill_response, visible_response_headers};
use super::url_set_inner;
+ use super::{pbkdf2_derive, push_capped, PBKDF2_MAX_ITERATIONS, PBKDF2_MAX_OUTPUT_BYTES};
use base64::{engine::general_purpose::STANDARD as FULFILL_BASE64, Engine as _};
// #1008: URL property setters must follow WHATWG — search/hash keep a bare
@@ -3846,6 +4059,10 @@ mod tests {
&lossy,
&b64,
"https://example.test/",
+ "https://example.test",
+ "cors",
+ FetchCredentials::SameOrigin,
+ false,
);
let out_b64 = result["bodyBase64"]
.as_str()
@@ -3856,6 +4073,72 @@ mod tests {
assert_eq!(decoded, raw, "the exact bytes must survive via bodyBase64");
}
+ #[test]
+ fn intercepted_internal_load_keeps_cross_origin_body_private_but_usable() {
+ let public = intercept_fulfill_response(
+ 200,
+ std::collections::HashMap::new(),
+ "script body",
+ "",
+ "https://cdn.example/script.js",
+ "https://page.example",
+ "no-cors",
+ FetchCredentials::SameOrigin,
+ false,
+ );
+ assert_eq!(public["status"], 0);
+ assert_eq!(public["body"], "");
+ assert_eq!(public["opaque"], true);
+
+ let internal = intercept_fulfill_response(
+ 200,
+ std::collections::HashMap::new(),
+ "script body",
+ "",
+ "https://cdn.example/script.js",
+ "https://page.example",
+ "no-cors",
+ FetchCredentials::SameOrigin,
+ true,
+ );
+ assert_eq!(internal["status"], 200);
+ assert_eq!(internal["body"], "script body");
+ assert_eq!(internal["opaque"], false);
+ }
+
+ #[test]
+ fn response_headers_hide_cookies_and_unexposed_cross_origin_fields() {
+ let headers = std::collections::HashMap::from([
+ ("content-type".to_string(), "text/plain".to_string()),
+ ("set-cookie".to_string(), "sid=secret; HttpOnly".to_string()),
+ ("x-secret".to_string(), "hidden".to_string()),
+ ("x-visible".to_string(), "shown".to_string()),
+ (
+ "access-control-expose-headers".to_string(),
+ "X-Visible, Set-Cookie".to_string(),
+ ),
+ ]);
+
+ let same_origin = visible_response_headers(&headers, false, FetchCredentials::SameOrigin);
+ assert!(!same_origin.contains_key("set-cookie"));
+ assert_eq!(
+ same_origin.get("x-secret").map(String::as_str),
+ Some("hidden")
+ );
+
+ let cross_origin = visible_response_headers(&headers, true, FetchCredentials::SameOrigin);
+ assert_eq!(
+ cross_origin.get("content-type").map(String::as_str),
+ Some("text/plain")
+ );
+ assert_eq!(
+ cross_origin.get("x-visible").map(String::as_str),
+ Some("shown")
+ );
+ assert!(!cross_origin.contains_key("x-secret"));
+ assert!(!cross_origin.contains_key("set-cookie"));
+ }
+
// SEC-002 / #705 — fetched_urls (and the like) must not grow without bound.
#[test]
fn push_capped_bounds_the_list_and_keeps_the_newest() {
@@ -4265,7 +4548,7 @@ mod tests {
"posted-task-from-op-resolution",
r#"
globalThis.__postedFromOp = 0;
- Deno.core.ops.op_sleep(0).then(() => {
+ __obscura_test_ops.op_sleep(0).then(() => {
const rearm = () => scheduler.postTask(() => {
__postedFromOp++;
if (__postedFromOp < 250) rearm();
@@ -5712,6 +5995,9 @@ pub fn build_extension() -> Extension {
op_script_try_start(),
op_shadow_attach(),
op_shadow_root_info(),
+ op_external_stylesheet_set(),
+ op_external_stylesheet_remove(),
+ op_external_stylesheet_get(),
op_runtime_events_enabled(),
op_console_msg(),
op_fetch_url(),
diff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rs
index 0c3d34fa..df79199c 100644
--- a/crates/obscura-js/src/runtime.rs
+++ b/crates/obscura-js/src/runtime.rs
@@ -611,6 +611,8 @@ impl ObscuraJsRuntime {
// Take the op table before any page script can run, and drop the global
// that exposed it in the same step.
instance.ops_handoff = instance.take_ops_handoff();
+ #[cfg(test)]
+ instance.expose_ops_for_tests();
// `JsRuntime::new` entered this isolate and rusty_v8 would leave it
// entered for life. Leave the thread's entry stack empty instead; every
@@ -663,9 +665,9 @@ impl ObscuraJsRuntime {
/// Takes the ops object bootstrap handed out, and removes the handoff from
/// the global so page script can never reach `Deno.core.ops`.
///
- /// deno_core hides `globalThis.Deno` after setup and bootstrap keeps its
- /// reference in a private const, so this handoff is the only way for the
- /// host to reach the bound op functions and pass them to a child realm.
+ /// Bootstrap keeps the core reference in a private const. Once deno_core
+ /// has bound the ops, this removes both public globals before page code can
+ /// run, leaving the handoff as the host's only route to child realms.
fn take_ops_handoff(&mut self) -> Option<deno_core::v8::Global<deno_core::v8::Value>> {
use deno_core::v8;
@@ -677,6 +679,7 @@ impl ObscuraJsRuntime {
let scope = &mut v8::ContextScope::new(scope, context);
let handoff_key = v8::String::new(scope, "__obscura_core_handoff")?;
+ let deno_key = v8::String::new(scope, "Deno")?;
let ops_key = v8::String::new(scope, "ops")?;
let global = context.global(scope);
@@ -688,9 +691,32 @@ impl ObscuraJsRuntime {
}
let ops = v8::Global::new(scope, ops);
global.delete(scope, handoff_key.into());
+ global.delete(scope, deno_key.into());
Some(ops)
}
+ /// Test-only instrumentation seam for assertions about native-op batching.
+ /// Production builds do not compile this method or publish the op table.
+ #[cfg(test)]
+ fn expose_ops_for_tests(&mut self) {
+ use deno_core::v8;
+
+ let Some(ops) = self.ops_handoff.clone() else {
+ return;
+ };
+ let main = self.runtime().main_context();
+ let mut entered = self.runtime();
+ let isolate = entered.v8_isolate();
+ let scope = &mut v8::HandleScope::new(isolate);
+ let context = v8::Local::new(scope, main);
+ let scope = &mut v8::ContextScope::new(scope, context);
+ let Some(key) = v8::String::new(scope, "__obscura_test_ops") else {
+ return;
+ };
+ let value = v8::Local::new(scope, ops);
+ let _ = context.global(scope).set(scope, key.into(), value);
+ }
+
/// Points a child realm's `Deno.core.ops` at the main realm's ops object.
///
/// A realm restored from the snapshot has its own `Deno.core` with an empty
@@ -756,6 +782,9 @@ impl ObscuraJsRuntime {
let Some(ops_key) = v8::String::new(scope, "ops") else {
return false;
};
+ let Some(deno_key) = v8::String::new(scope, "Deno") else {
+ return false;
+ };
let global = context.global(scope);
let Some(core) = global.get(scope, handoff_key.into()) else {
return false;
@@ -793,6 +822,7 @@ impl ObscuraJsRuntime {
}
// The child realm must not expose the handoff to frame script either.
global.delete(scope, handoff_key.into());
+ global.delete(scope, deno_key.into());
copied > 0
}
@@ -4248,6 +4278,24 @@ mod tests {
rt
}
+ #[test]
+ fn page_script_cannot_reach_deno_core_or_bootstrap_handoff() {
+ let mut rt = setup_runtime("<html><body><p id='value'>safe</p></body></html>");
+ rt.evaluate("delete globalThis.__obscura_test_ops").unwrap();
+
+ assert_eq!(
+ rt.evaluate("[typeof Deno, typeof __obscuraCore, typeof __obscura_core_handoff]")
+ .unwrap(),
+ serde_json::json!(["undefined", "undefined", "undefined"])
+ );
+ assert_eq!(
+ rt.evaluate("document.getElementById('value').textContent")
+ .unwrap(),
+ serde_json::json!("safe"),
+ "DOM ops must continue to work through the private closure"
+ );
+ }
+
// #1013: removeAttribute('id') must update the id_index so getElementById no
// longer returns the (still-attached) element.
#[test]
@@ -11875,19 +11923,19 @@ mod tests {
globalThis.__resizeBulkSizes = [];
globalThis.__resizeLegacyGeometryCalls = 0;
globalThis.__resizeComputedStyleCalls = 0;
- const nativeBulk = Deno.core.ops.op_resize_observer_measurements;
- const nativeGeometry = Deno.core.ops.op_layout_geometry;
- const nativeComputedStyle = Deno.core.ops.op_computed_style;
- Deno.core.ops.op_resize_observer_measurements = input => {
+ const nativeBulk = __obscura_test_ops.op_resize_observer_measurements;
+ const nativeGeometry = __obscura_test_ops.op_layout_geometry;
+ const nativeComputedStyle = __obscura_test_ops.op_computed_style;
+ __obscura_test_ops.op_resize_observer_measurements = input => {
__resizeBulkCalls++;
__resizeBulkSizes.push(JSON.parse(input).length);
return nativeBulk(input);
};
- Deno.core.ops.op_layout_geometry = (...args) => {
+ __obscura_test_ops.op_layout_geometry = (...args) => {
__resizeLegacyGeometryCalls++;
return nativeGeometry(...args);
};
- Deno.core.ops.op_computed_style = (...args) => {
+ __obscura_test_ops.op_computed_style = (...args) => {
__resizeComputedStyleCalls++;
return nativeComputedStyle(...args);
};
@@ -12040,8 +12088,8 @@ mod tests {
"count-scroll-geometry-reads",
r#"
globalThis.__scrollGeometryReads = 0;
- globalThis.__nativeLayoutGeometry = Deno.core.ops.op_layout_geometry;
- Deno.core.ops.op_layout_geometry = (...args) => {
+ globalThis.__nativeLayoutGeometry = __obscura_test_ops.op_layout_geometry;
+ __obscura_test_ops.op_layout_geometry = (...args) => {
__scrollGeometryReads++;
return __nativeLayoutGeometry(...args);
};
@@ -12055,7 +12103,7 @@ mod tests {
.unwrap();
rt.execute_script(
"restore-layout-geometry-op",
- "Deno.core.ops.op_layout_geometry = __nativeLayoutGeometry;",
+ "__obscura_test_ops.op_layout_geometry = __nativeLayoutGeometry;",
)
.unwrap();
assert_eq!(result, serde_json::json!([50, 0, 1]));
@@ -12242,19 +12290,19 @@ mod tests {
globalThis.__intersectionBulkSizes = [];
globalThis.__intersectionLegacyGeometryCalls = 0;
globalThis.__intersectionComputedStyleCalls = 0;
- const nativeBulk = Deno.core.ops.op_intersection_observer_measurements;
- const nativeGeometry = Deno.core.ops.op_layout_geometry;
- const nativeComputedStyle = Deno.core.ops.op_computed_style;
- Deno.core.ops.op_intersection_observer_measurements = input => {
+ const nativeBulk = __obscura_test_ops.op_intersection_observer_measurements;
+ const nativeGeometry = __obscura_test_ops.op_layout_geometry;
+ const nativeComputedStyle = __obscura_test_ops.op_computed_style;
+ __obscura_test_ops.op_intersection_observer_measurements = input => {
__intersectionBulkCalls++;
__intersectionBulkSizes.push(JSON.parse(input).length);
return nativeBulk(input);
};
- Deno.core.ops.op_layout_geometry = (...args) => {
+ __obscura_test_ops.op_layout_geometry = (...args) => {
__intersectionLegacyGeometryCalls++;
return nativeGeometry(...args);
};
- Deno.core.ops.op_computed_style = (...args) => {
+ __obscura_test_ops.op_computed_style = (...args) => {
__intersectionComputedStyleCalls++;
return nativeComputedStyle(...args);
};
@@ -16492,7 +16540,7 @@ mod tests {
let url = url::Url::parse("http://example.com/test").unwrap();
let result = rt.evaluate("document.cookie").unwrap();
assert!(result.as_str().unwrap().contains("foo=bar"));
- let header = jar.get_cookie_header(&url);
+ let header = jar.get_cookie_header_same_site(&url);
assert!(
header.contains("foo=bar"),
"cookie should be in jar, got: {}",
@@ -16542,7 +16590,7 @@ mod tests {
"cookie should be deleted, got: {}",
result
);
- assert!(!jar.get_cookie_header(&url).contains("temp="));
+ assert!(!jar.get_cookie_header_same_site(&url).contains("temp="));
}
#[test]
@@ -16955,10 +17003,10 @@ mod tests {
let result = rt
.call_function_on_for_cdp(
r#"async () => {
- const originalFetchOp = Deno.core.ops.op_fetch_url;
+ const originalFetchOp = __obscura_test_ops.op_fetch_url;
const seen = [];
try {
- Deno.core.ops.op_fetch_url = (url) => {
+ __obscura_test_ops.op_fetch_url = (url) => {
seen.push(url);
return JSON.stringify({ status: 200, headers: {}, body: "{}", url });
};
@@ -16969,7 +17017,7 @@ mod tests {
await new Promise((r) => setTimeout(r, 0));
return seen;
} finally {
- Deno.core.ops.op_fetch_url = originalFetchOp;
+ __obscura_test_ops.op_fetch_url = originalFetchOp;
}
}"#,
None,
@@ -16996,9 +17044,9 @@ mod tests {
let result = rt
.call_function_on_for_cdp(
r#"async () => {
- const originalFetchOp = Deno.core.ops.op_fetch_url;
+ const originalFetchOp = __obscura_test_ops.op_fetch_url;
try {
- Deno.core.ops.op_fetch_url = (url) => {
+ __obscura_test_ops.op_fetch_url = (url) => {
globalThis.__capturedFetchUrl = url;
return JSON.stringify({
status: 200,
@@ -17011,7 +17059,7 @@ mod tests {
const bytes = Array.from(new Uint8Array(await response.arrayBuffer()));
return { url: globalThis.__capturedFetchUrl, bytes };
} finally {
- Deno.core.ops.op_fetch_url = originalFetchOp;
+ __obscura_test_ops.op_fetch_url = originalFetchOp;
}
}"#,
None,
@@ -17040,17 +17088,17 @@ mod tests {
let result = rt
.call_function_on_for_cdp(
r#"async () => {
- const original = Deno.core.ops.op_fetch_url;
+ const original = __obscura_test_ops.op_fetch_url;
let captured = null;
try {
- Deno.core.ops.op_fetch_url = (url, method) => {
+ __obscura_test_ops.op_fetch_url = (url, method) => {
captured = method;
return JSON.stringify({ status: 200, headers: {}, body: "ok", url });
};
await fetch(new URL("/api", document.URL), { method: "delete" });
return captured;
} finally {
- Deno.core.ops.op_fetch_url = original;
+ __obscura_test_ops.op_fetch_url = original;
}
}"#,
None,
@@ -17074,10 +17122,10 @@ mod tests {
let result = rt
.call_function_on_for_cdp(
r#"async () => {
- const originalFetchOp = Deno.core.ops.op_fetch_url;
+ const originalFetchOp = __obscura_test_ops.op_fetch_url;
const calls = [];
try {
- Deno.core.ops.op_fetch_url =
+ __obscura_test_ops.op_fetch_url =
(url, method, headers, body, origin, mode, credentials) => {
calls.push({ url, credentials });
return JSON.stringify({
@@ -17115,7 +17163,7 @@ mod tests {
return { calls, invalidFetchRejected };
} finally {
- Deno.core.ops.op_fetch_url = originalFetchOp;
+ __obscura_test_ops.op_fetch_url = originalFetchOp;
}
}"#,
None,
@@ -17228,10 +17276,10 @@ mod tests {
let result = rt
.call_function_on_for_cdp(
r#"async () => {
- const originalFetchOp = Deno.core.ops.op_fetch_url;
+ const originalFetchOp = __obscura_test_ops.op_fetch_url;
const calls = [];
try {
- Deno.core.ops.op_fetch_url =
+ __obscura_test_ops.op_fetch_url =
(url, method, headers, body) => {
calls.push({
path: new URL(url).pathname,
@@ -17291,7 +17339,7 @@ mod tests {
return calls;
} finally {
- Deno.core.ops.op_fetch_url = originalFetchOp;
+ __obscura_test_ops.op_fetch_url = originalFetchOp;
}
}"#,
None,
@@ -17322,7 +17370,7 @@ mod tests {
let result = rt
.call_function_on_for_cdp(
r#"async () => {
- const originalFetchOp = Deno.core.ops.op_fetch_url;
+ const originalFetchOp = __obscura_test_ops.op_fetch_url;
const calls = [];
const includesBytes = (bytes, needle) => {
outer: for (let i = 0; i <= bytes.length - needle.length; i++) {
@@ -17334,7 +17382,7 @@ mod tests {
return false;
};
try {
- Deno.core.ops.op_fetch_url =
+ __obscura_test_ops.op_fetch_url =
(url, method, headers, body) => {
const bytes = Array.from(
body instanceof Uint8Array
@@ -17410,7 +17458,7 @@ mod tests {
},
};
} finally {
- Deno.core.ops.op_fetch_url = originalFetchOp;
+ __obscura_test_ops.op_fetch_url = originalFetchOp;
}
}"#,
None,
@@ -17868,7 +17916,15 @@ mod tests {
.call_function_on_for_cdp(
r#"async () => {
const response = await fetch("/start", { mode: "no-cors" });
- return { type: response.type, url: response.url, redirected: response.redirected };
+ return {
+ type: response.type,
+ url: response.url,
+ redirected: response.redirected,
+ status: response.status,
+ body: await response.text(),
+ bodyIsNull: response.body === null,
+ headerCount: Array.from(response.headers).length,
+ };
}"#,
None,
&[],
@@ -17879,7 +17935,15 @@ mod tests {
.unwrap();
assert_eq!(
result.value.unwrap(),
- serde_json::json!({ "type": "opaque", "url": "", "redirected": false })
+ serde_json::json!({
+ "type": "opaque",
+ "url": "",
+ "redirected": false,
+ "status": 0,
+ "body": "",
+ "bodyIsNull": true,
+ "headerCount": 0,
+ })
);
}
@@ -17944,9 +18008,9 @@ mod tests {
let result = rt
.call_function_on_for_cdp(
r#"async () => {
- const originalFetchOp = Deno.core.ops.op_fetch_url;
+ const originalFetchOp = __obscura_test_ops.op_fetch_url;
try {
- Deno.core.ops.op_fetch_url = (url) => JSON.stringify({
+ __obscura_test_ops.op_fetch_url = (url) => JSON.stringify({
status: 200,
headers: { "content-type": "text/css" },
body: url.endsWith("/assets/route.css")
@@ -17962,12 +18026,10 @@ mod tests {
});
document.head.appendChild(link);
await loaded;
- const style = document.querySelector("style[data-obscura-linked]");
- const css = style.textContent;
- const afterLink = link.nextSibling === style;
const list = document.styleSheets;
const sheet = link.sheet;
const rules = sheet.cssRules;
+ const css = Array.from(rules, rule => rule.cssText).join("\n");
const cssom = {
listed: list.length === 1 && list[0] === sheet,
stable: link.sheet === sheet && sheet.cssRules === rules,
@@ -17977,22 +18039,22 @@ mod tests {
};
link.remove();
return {
- afterLink,
+ noSyntheticStyle:
+ !document.querySelector("style[data-obscura-linked]"),
importedBeforeRoute:
- css.indexOf("color:red") < css.indexOf("display:grid"),
+ rules[0].cssText.includes("color")
+ && rules[1].cssText.includes("display"),
importedUrl:
css.includes("http://example.com/assets/theme/grain.png"),
routeUrl:
css.includes("http://example.com/img/card.png"),
- removedWithLink:
- !document.querySelector("style[data-obscura-linked]"),
cssom,
detachedCssom: sheet.ownerNode === null
&& link.sheet === null
&& list.length === 0,
};
} finally {
- Deno.core.ops.op_fetch_url = originalFetchOp;
+ __obscura_test_ops.op_fetch_url = originalFetchOp;
}
}"#,
None,
@@ -18006,11 +18068,10 @@ mod tests {
assert_eq!(
result.value.unwrap(),
serde_json::json!({
- "afterLink": true,
+ "noSyntheticStyle": true,
"importedBeforeRoute": true,
"importedUrl": true,
"routeUrl": true,
- "removedWithLink": true,
"cssom": {
"listed": true,
"stable": true,
@@ -18029,9 +18090,9 @@ mod tests {
let result = rt
.call_function_on_for_cdp(
r#"async () => {
- const originalFetchOp = Deno.core.ops.op_fetch_url;
+ const originalFetchOp = __obscura_test_ops.op_fetch_url;
try {
- Deno.core.ops.op_fetch_url = (url) => JSON.stringify({
+ __obscura_test_ops.op_fetch_url = (url) => JSON.stringify({
status: 401,
headers: { "content-type": "application/json" },
body: "globalThis.__executedFailedScript = true",
@@ -18049,7 +18110,7 @@ mod tests {
executed: globalThis.__executedFailedScript === true,
};
} finally {
- Deno.core.ops.op_fetch_url = originalFetchOp;
+ __obscura_test_ops.op_fetch_url = originalFetchOp;
}
}"#,
None,
@@ -18069,16 +18130,110 @@ mod tests {
);
}
+ #[tokio::test(flavor = "current_thread")]
+ async fn cross_origin_dynamic_script_loads_without_exposing_fetch_body() {
+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
+ let address = listener.local_addr().unwrap();
+ std::thread::spawn(move || {
+ use std::io::{Read as _, Write as _};
+ let (mut stream, _) = listener.accept().unwrap();
+ let mut buffer = [0u8; 1024];
+ let _ = stream.read(&mut buffer);
+ let body = "globalThis.__crossOriginScriptLoaded = true";
+ let response = format!(
+ "HTTP/1.1 200 OK\r\nContent-Type: text/javascript\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
+ body.len(),
+ );
+ let _ = stream.write_all(response.as_bytes());
+ });
+
+ let page = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
+ let page_address = page.local_addr().unwrap();
+ drop(page);
+ let mut rt = redirect_runtime_for_origin(&format!("http://{page_address}"));
+ let result = rt
+ .call_function_on_for_cdp(
+ &format!(
+ r#"async () => {{
+ const script = document.createElement("script");
+ script.src = "http://{address}/script.js";
+ const outcome = await new Promise(resolve => {{
+ script.onload = () => resolve("load");
+ script.onerror = () => resolve("error");
+ document.head.appendChild(script);
+ }});
+ return {{ outcome, loaded: globalThis.__crossOriginScriptLoaded === true }};
+ }}"#
+ ),
+ None,
+ &[],
+ true,
+ true,
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(
+ result.value.unwrap(),
+ serde_json::json!({ "outcome": "load", "loaded": true })
+ );
+ }
+
+ #[tokio::test(flavor = "current_thread")]
+ async fn iframe_origin_follows_the_final_redirect_url() {
+ let mut rt = setup_runtime("<html><head></head><body></body></html>");
+ let result = rt
+ .call_function_on_for_cdp(
+ r#"async () => {
+ const originalFetchOp = __obscura_test_ops.op_fetch_url;
+ try {
+ __obscura_test_ops.op_fetch_url = async () => JSON.stringify({
+ status: 200,
+ headers: { "content-type": "text/html" },
+ body: "<!doctype html><title>secret</title>",
+ url: "https://cross-origin.example/secret",
+ redirected: true,
+ });
+ const frame = document.createElement("iframe");
+ const loaded = new Promise(resolve => frame.onload = resolve);
+ frame.src = "/same-origin-start";
+ document.body.appendChild(frame);
+ await loaded;
+ return {
+ readable: frame.contentDocument !== null,
+ loadedUrl: frame._iframeLoadedUrl,
+ };
+ } finally {
+ __obscura_test_ops.op_fetch_url = originalFetchOp;
+ }
+ }"#,
+ None,
+ &[],
+ true,
+ true,
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(
+ result.value.unwrap(),
+ serde_json::json!({
+ "readable": false,
+ "loadedUrl": "https://cross-origin.example/secret",
+ })
+ );
+ }
+
#[tokio::test(flavor = "current_thread")]
async fn dynamic_classic_scripts_are_async_by_default_but_honor_async_false_order() {
let mut rt = setup_runtime("<html><head></head><body></body></html>");
let result = rt
.call_function_on_for_cdp(
r#"async () => {
- const originalFetchOp = Deno.core.ops.op_fetch_url;
+ const originalFetchOp = __obscura_test_ops.op_fetch_url;
const runPair = async (explicitlyInOrder) => {
globalThis.__dynamicOrder = [];
- Deno.core.ops.op_fetch_url = (url) => new Promise(resolve => {
+ __obscura_test_ops.op_fetch_url = (url) => new Promise(resolve => {
const slow = url.includes("slow");
setTimeout(() => resolve(JSON.stringify({
status: 200,
@@ -18106,7 +18261,7 @@ mod tests {
pending: globalThis.__obscura_hasPendingDynamicScripts(),
};
} finally {
- Deno.core.ops.op_fetch_url = originalFetchOp;
+ __obscura_test_ops.op_fetch_url = originalFetchOp;
}
}"#,
None,
@@ -19826,9 +19981,9 @@ mod tests {
document.body.appendChild(parsed.querySelector("script"));
let externalFetches = 0;
- const originalFetchOp = Deno.core.ops.op_fetch_url;
+ const originalFetchOp = __obscura_test_ops.op_fetch_url;
try {
- Deno.core.ops.op_fetch_url = () => {
+ __obscura_test_ops.op_fetch_url = () => {
externalFetches++;
return JSON.stringify({
status: 200,
@@ -19841,7 +19996,7 @@ mod tests {
external.innerHTML = "<script src=/inert.js><\/script>";
document.head.appendChild(external.firstChild);
} finally {
- Deno.core.ops.op_fetch_url = originalFetchOp;
+ __obscura_test_ops.op_fetch_url = originalFetchOp;
}
return [globalThis.__fragmentScriptRuns, externalFetches];
"#,
diff --git a/crates/obscura-mcp/src/http.rs b/crates/obscura-mcp/src/http.rs
index 4e8c93cf..a2298b41 100644
--- a/crates/obscura-mcp/src/http.rs
+++ b/crates/obscura-mcp/src/http.rs
@@ -1,7 +1,10 @@
use anyhow::Result;
use serde_json::{json, Value};
+use std::sync::Arc;
+
use tokio::io::{AsyncBufRead, AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
use tokio::net::TcpListener;
+use tokio::sync::{mpsc, oneshot, Semaphore};
use tokio::time::Duration;
use crate::{dispatch, BrowserState};
@@ -9,9 +12,16 @@ use crate::{dispatch, BrowserState};
/// Hard cap on a single MCP request body. The client-supplied `Content-Length`
/// is used to pre-size the read buffer; without a ceiling a request advertising
/// e.g. `Content-Length: 4294967296` makes the server allocate and zero-fill
-/// that many bytes before reading any body — an unauthenticated OOM/DoS. 16 MiB
-/// is far above any real JSON-RPC tool call.
-const MAX_BODY_BYTES: usize = 16 * 1024 * 1024;
+/// that many bytes before reading any body — an unauthenticated OOM/DoS. One
+/// MiB is far above any real JSON-RPC tool call.
+const MAX_BODY_BYTES: usize = 1024 * 1024;
+const MAX_REQUEST_LINE_BYTES: usize = 8 * 1024;
+const MAX_HEADER_LINE_BYTES: usize = 16 * 1024;
+const MAX_HEADER_BYTES: usize = 64 * 1024;
+const MAX_BATCH_ITEMS: usize = 64;
+const MAX_ID_BYTES: usize = 1024;
+const MAX_CONNECTIONS: usize = 128;
+const MAX_PENDING_REQUESTS: usize = 32;
/// Maximum time allowed to receive one complete HTTP request (request line,
/// headers, and body). The deadline is shared across all reads so a client
@@ -31,6 +41,8 @@ struct HttpRequest {
accept_sse: bool,
keep_alive: bool,
origin: Option<String>,
+ authorized: bool,
+ content_type_is_json: bool,
body: RequestBody,
}
@@ -40,14 +52,79 @@ enum RequestRead {
Request(HttpRequest),
}
+struct PendingRequest {
+ body: Vec<u8>,
+ reply: oneshot::Sender<Value>,
+}
+
+fn token_from_env() -> Result<Option<String>> {
+ let token = std::env::var("OBSCURA_MCP_TOKEN")
+ .ok()
+ .filter(|value| !value.is_empty());
+ if token.as_ref().is_some_and(|value| value.len() < 32) {
+ anyhow::bail!("OBSCURA_MCP_TOKEN must be at least 32 bytes");
+ }
+ Ok(token)
+}
+
+fn constant_time_eq(left: &str, right: &str) -> bool {
+ if left.len() != right.len() {
+ return false;
+ }
+ left.bytes()
+ .zip(right.bytes())
+ .fold(0u8, |difference, (left, right)| difference | (left ^ right))
+ == 0
+}
+
+fn bearer_authorized(header: Option<&str>, expected: Option<&str>) -> bool {
+ match expected {
+ None => true,
+ Some(expected) => header
+ .and_then(|value| value.strip_prefix("Bearer "))
+ .is_some_and(|provided| constant_time_eq(provided, expected)),
+ }
+}
+
+async fn read_line_limited(
+ reader: &mut (impl AsyncBufRead + Unpin),
+ limit: usize,
+) -> Result<Option<String>> {
+ let mut bytes = Vec::new();
+ loop {
+ let available = reader.fill_buf().await?;
+ if available.is_empty() {
+ if bytes.is_empty() {
+ return Ok(None);
+ }
+ break;
+ }
+ let consumed = available
+ .iter()
+ .position(|byte| *byte == b'\n')
+ .map_or(available.len(), |index| index + 1);
+ if bytes.len() + consumed > limit {
+ anyhow::bail!("HTTP line too long");
+ }
+ bytes.extend_from_slice(&available[..consumed]);
+ reader.consume(consumed);
+ if bytes.last() == Some(&b'\n') {
+ break;
+ }
+ }
+ String::from_utf8(bytes)
+ .map(Some)
+ .map_err(|_| anyhow::anyhow!("HTTP head is not UTF-8"))
+}
+
async fn read_request(
reader: &mut (impl AsyncBufRead + Unpin),
allowed_origins: Option<&str>,
+ auth_token: Option<&str>,
) -> Result<RequestRead> {
- let mut request_line = String::new();
- if reader.read_line(&mut request_line).await? == 0 {
+ let Some(request_line) = read_line_limited(reader, MAX_REQUEST_LINE_BYTES).await? else {
return Ok(RequestRead::Closed);
- }
+ };
let request_line = request_line.trim();
if request_line.is_empty() {
return Ok(RequestRead::Closed);
@@ -64,10 +141,18 @@ async fn read_request(
let mut accept_sse = false;
let mut keep_alive = false;
let mut origin: Option<String> = None;
+ let mut authorization: Option<String> = None;
+ let mut content_type_is_json = false;
+ let mut header_bytes = 0usize;
loop {
- let mut line = String::new();
- reader.read_line(&mut line).await?;
+ let Some(line) = read_line_limited(reader, MAX_HEADER_LINE_BYTES).await? else {
+ return Ok(RequestRead::Invalid);
+ };
+ header_bytes = header_bytes.saturating_add(line.len());
+ if header_bytes > MAX_HEADER_BYTES {
+ anyhow::bail!("HTTP headers too large");
+ }
let trimmed = line.trim_end_matches("\r\n").trim_end_matches('\n');
if trimmed.is_empty() {
break;
@@ -81,6 +166,17 @@ async fn read_request(
origin = Some(trimmed[idx + 1..].trim().to_string());
}
}
+ if lower.starts_with("authorization:") {
+ if let Some(idx) = trimmed.find(':') {
+ authorization = Some(trimmed[idx + 1..].trim().to_string());
+ }
+ }
+ if let Some(value) = lower.strip_prefix("content-type:") {
+ content_type_is_json = value
+ .split(';')
+ .next()
+ .is_some_and(|media_type| media_type.trim() == "application/json");
+ }
if lower.contains("text/event-stream") {
accept_sse = true;
}
@@ -91,9 +187,12 @@ async fn read_request(
// Only consume a body for a POST that can reach the MCP route. Invalid
// paths and forbidden origins retain the existing early-response behavior.
+ let authorized = bearer_authorized(authorization.as_deref(), auth_token);
let body = if method == "POST"
&& path == "/mcp"
&& origin_allowed(origin.as_deref(), allowed_origins)
+ && authorized
+ && content_type_is_json
{
match content_length {
None => RequestBody::MissingLength,
@@ -115,6 +214,8 @@ async fn read_request(
accept_sse,
keep_alive,
origin,
+ authorized,
+ content_type_is_json,
body,
}))
}
@@ -122,16 +223,17 @@ async fn read_request(
async fn read_request_with_timeout(
reader: &mut (impl AsyncBufRead + Unpin),
allowed_origins: Option<&str>,
+ auth_token: Option<&str>,
timeout: Duration,
) -> Result<RequestRead> {
- tokio::time::timeout(timeout, read_request(reader, allowed_origins))
+ tokio::time::timeout(timeout, read_request(reader, allowed_origins, auth_token))
.await
.map_err(|_| anyhow::anyhow!("request read timed out"))?
}
/// Origin allowlist for browser callers, read from `OBSCURA_MCP_ALLOWED_ORIGINS`
-/// (comma-separated). Unset/empty → permissive (unchanged `*`) so hosted
-/// dashboards keep working (issue #175).
+/// (comma-separated). Unset/empty refuses browser callers; native clients do
+/// not send Origin and remain unaffected.
fn allowed_origins_env() -> Option<String> {
std::env::var("OBSCURA_MCP_ALLOWED_ORIGINS")
.ok()
@@ -144,11 +246,11 @@ fn allowed_origins_env() -> Option<String> {
/// browser `Origin` must match one of its entries (case-insensitive); this
/// stops a malicious local web page from driving the loopback MCP port.
fn origin_allowed(origin: Option<&str>, allowlist: Option<&str>) -> bool {
- match allowlist {
+ match origin {
None => true,
- Some(list) => match origin {
- None => true,
- Some(o) => {
+ Some(o) => match allowlist {
+ None => false,
+ Some(list) => {
let o = o.trim();
list.split(',')
.map(str::trim)
@@ -158,47 +260,77 @@ fn origin_allowed(origin: Option<&str>, allowlist: Option<&str>) -> bool {
}
}
-/// CORS `Access-Control-Allow-Origin` value for a response. With no allowlist
-/// we keep the permissive `*` (issue #175). With an allowlist the request's
-/// origin has already passed `origin_allowed`, so echo it back plus `Vary:
-/// Origin` instead of advertising `*`; a native client with no `Origin` needs
-/// no CORS header at all.
+/// CORS response for an already-authorized browser caller. A wildcard is never
+/// emitted for this privileged endpoint.
fn cors_header(origin: Option<&str>, allowlist: Option<&str>) -> String {
- match allowlist {
- None => "Access-Control-Allow-Origin: *\r\n".to_string(),
- Some(_) => match origin {
- Some(o) => format!("Access-Control-Allow-Origin: {o}\r\nVary: Origin\r\n"),
- None => String::new(),
- },
+ match (origin, allowlist) {
+ (Some(origin), Some(_)) => {
+ format!("Access-Control-Allow-Origin: {origin}\r\nVary: Origin\r\n")
+ }
+ _ => String::new(),
}
}
/// MCP Streamable HTTP transport (POST /mcp → JSON response).
///
-/// Connections are handled sequentially on the current thread — the browser
-/// session (including the V8 runtime) is single-threaded and `!Send`, so we
-/// never need to move state across threads.
pub async fn run(host: String, port: u16, proxy: Option<String>, user_agent: Option<String>, stealth: bool) -> Result<()> {
let addr: std::net::SocketAddr = format!("{}:{}", host, port).parse()?;
+ let auth_token = token_from_env()?;
+ if !addr.ip().is_loopback() && auth_token.is_none() {
+ anyhow::bail!(
+ "refusing to expose MCP without authentication; set OBSCURA_MCP_TOKEN to at least 32 bytes"
+ );
+ }
let listener = TcpListener::bind(&addr).await?;
tracing::info!("MCP HTTP server on http://{}:{}/mcp", host, port);
+ if auth_token.is_some() {
+ tracing::info!("MCP bearer authentication enabled");
+ }
let mut state = BrowserState::new(proxy, user_agent, stealth);
- let allowed_origins = allowed_origins_env();
+ let allowed_origins = Arc::new(allowed_origins_env());
+ let auth_token = Arc::new(auth_token);
+ let connection_slots = Arc::new(Semaphore::new(MAX_CONNECTIONS));
+ let (request_tx, mut request_rx) = mpsc::channel::<PendingRequest>(MAX_PENDING_REQUESTS);
loop {
- let (stream, peer) = listener.accept().await?;
- tracing::debug!("MCP HTTP connection from {}", peer);
- if let Err(e) = handle_connection(stream, &mut state, allowed_origins.as_deref()).await {
- tracing::debug!("connection closed: {}", e);
+ tokio::select! {
+ accepted = listener.accept() => {
+ let (stream, peer) = accepted?;
+ let Ok(permit) = connection_slots.clone().try_acquire_owned() else {
+ tracing::warn!("refusing MCP connection: connection limit reached");
+ continue;
+ };
+ tracing::debug!("MCP HTTP connection from {}", peer);
+ let request_tx = request_tx.clone();
+ let allowed_origins = allowed_origins.clone();
+ let auth_token = auth_token.clone();
+ tokio::spawn(async move {
+ let result = handle_connection(
+ stream,
+ request_tx,
+ allowed_origins.as_deref().as_deref(),
+ auth_token.as_deref().as_deref(),
+ ).await;
+ drop(permit);
+ if let Err(error) = result {
+ tracing::debug!("connection closed: {}", error);
+ }
+ });
+ }
+ Some(request) = request_rx.recv() => {
+ let response = process_body(&request.body, &mut state).await;
+ let _ = request.reply.send(response);
+ }
}
}
}
async fn handle_connection(
stream: tokio::net::TcpStream,
- state: &mut BrowserState,
+ request_tx: mpsc::Sender<PendingRequest>,
allowed_origins: Option<&str>,
+ auth_token: Option<&str>,
) -> Result<()> {
let (reader, mut writer) = stream.into_split();
let mut reader = BufReader::new(reader);
@@ -207,6 +339,7 @@ async fn handle_connection(
let request = match read_request_with_timeout(
&mut reader,
allowed_origins,
+ auth_token,
REQUEST_READ_TIMEOUT,
)
.await?
@@ -220,6 +353,8 @@ async fn handle_connection(
accept_sse,
keep_alive,
origin,
+ authorized,
+ content_type_is_json,
body,
} = request;
@@ -238,6 +373,10 @@ async fn handle_connection(
respond(&mut writer, 403, b"{\"error\":\"origin not allowed\"}").await?;
break;
}
+ if method != "OPTIONS" && !authorized {
+ respond(&mut writer, 401, b"{\"error\":\"authentication required\"}").await?;
+ break;
+ }
let cors = cors_header(origin.as_deref(), allowed_origins);
match method.as_str() {
@@ -250,7 +389,7 @@ async fn handle_connection(
"HTTP/1.1 204 No Content\r\n\
{cors}\
Access-Control-Allow-Methods: GET, POST, OPTIONS\r\n\
- Access-Control-Allow-Headers: Content-Type, Authorization, X-API-Key, mcp-protocol-version\r\n\
+ Access-Control-Allow-Headers: Content-Type, Authorization, mcp-protocol-version\r\n\
Access-Control-Max-Age: 86400\r\n\
\r\n"
);
@@ -288,6 +427,15 @@ async fn handle_connection(
}
"POST" => {
+ if !content_type_is_json {
+ respond(
+ &mut writer,
+ 415,
+ b"{\"error\":\"Content-Type must be application/json\"}",
+ )
+ .await?;
+ break;
+ }
let body = match body {
RequestBody::MissingLength => {
respond(&mut writer, 400, b"{\"error\":\"missing Content-Length\"}").await?;
@@ -301,7 +449,14 @@ async fn handle_connection(
RequestBody::NotRead => unreachable!("valid MCP POST body was not read"),
};
- let response = process_body(&body, state).await;
+ let (reply, response) = oneshot::channel();
+ request_tx
+ .send(PendingRequest { body, reply })
+ .await
+ .map_err(|_| anyhow::anyhow!("MCP dispatcher stopped"))?;
+ let response = response
+ .await
+ .map_err(|_| anyhow::anyhow!("MCP dispatcher dropped response"))?;
let bytes = serde_json::to_vec(&response)?;
respond_json(&mut writer, &bytes, &cors).await?;
@@ -327,6 +482,9 @@ async fn process_body(body: &[u8], state: &mut BrowserState) -> Value {
};
if let Some(batch) = msg.as_array() {
+ if batch.is_empty() || batch.len() > MAX_BATCH_ITEMS {
+ return json!({"jsonrpc":"2.0","id":null,"error":{"code":-32600,"message":"Invalid Request"}});
+ }
let mut results = Vec::new();
for item in batch {
if let Some(r) = process_one(item, state).await {
@@ -342,6 +500,13 @@ async fn process_body(body: &[u8], state: &mut BrowserState) -> Value {
async fn process_one(msg: &Value, state: &mut BrowserState) -> Option<Value> {
let id = msg.get("id").cloned()?; // notifications have no id — return None
+ if matches!(id, Value::Array(_) | Value::Object(_))
+ || serde_json::to_vec(&id).map_or(true, |encoded| encoded.len() > MAX_ID_BYTES)
+ {
+ return Some(
+ json!({"jsonrpc":"2.0","id":null,"error":{"code":-32600,"message":"Invalid Request"}}),
+ );
+ }
let method = msg.get("method").and_then(Value::as_str).unwrap_or("");
let params = msg.get("params").unwrap_or(&Value::Null);
let resp = dispatch(method, id, params, state).await;
@@ -367,10 +532,12 @@ async fn respond_json(writer: &mut (impl AsyncWriteExt + Unpin), body: &[u8], co
async fn respond(writer: &mut (impl AsyncWriteExt + Unpin), status: u16, body: &[u8]) -> Result<()> {
let status_text = match status {
400 => "Bad Request",
+ 401 => "Unauthorized",
403 => "Forbidden",
404 => "Not Found",
405 => "Method Not Allowed",
413 => "Payload Too Large",
+ 415 => "Unsupported Media Type",
_ => "OK",
};
let hdr = format!(
@@ -389,16 +556,18 @@ async fn respond(writer: &mut (impl AsyncWriteExt + Unpin), status: u16, body: &
#[cfg(test)]
mod mcp_hardening_tests {
use super::{
- origin_allowed, read_request_with_timeout, MAX_BODY_BYTES,
+ bearer_authorized, cors_header, origin_allowed, read_request_with_timeout, MAX_BODY_BYTES,
REQUEST_READ_TIMEOUT,
};
use tokio::io::{AsyncWriteExt, BufReader};
use tokio::time::Duration;
#[test]
- fn no_allowlist_is_permissive() {
- assert!(origin_allowed(Some("https://evil.example"), None));
+ fn no_allowlist_refuses_browser_callers() {
+ assert!(!origin_allowed(Some("https://evil.example"), None));
+ assert!(!origin_allowed(Some("null"), None));
assert!(origin_allowed(None, None));
+ assert!(!cors_header(Some("https://evil.example"), None).contains('*'));
}
#[test]
@@ -418,6 +587,18 @@ mod mcp_hardening_tests {
assert!(MAX_BODY_BYTES <= 64 << 20);
}
+ #[test]
+ fn bearer_token_is_required_when_configured() {
+ let token = "01234567890123456789012345678901";
+ assert!(bearer_authorized(
+ Some(&format!("Bearer {token}")),
+ Some(token)
+ ));
+ assert!(!bearer_authorized(None, Some(token)));
+ assert!(!bearer_authorized(Some("Bearer wrong"), Some(token)));
+ assert!(bearer_authorized(None, None));
+ }
+
#[test]
fn request_read_timeout_is_generous_but_bounded() {
assert!(REQUEST_READ_TIMEOUT >= Duration::from_secs(10));
@@ -428,7 +609,7 @@ mod mcp_hardening_tests {
async fn stalled_request_line_hits_deadline() {
let (_client, server) = tokio::io::duplex(64);
let mut reader = BufReader::new(server);
- let err = match read_request_with_timeout(&mut reader, None, Duration::from_millis(20))
+ let err = match read_request_with_timeout(&mut reader, None, None, Duration::from_millis(20))
.await
{
Err(err) => err,
@@ -439,11 +620,12 @@ mod mcp_hardening_tests {
#[tokio::test]
async fn stalled_request_body_hits_deadline() {
- let (mut client, server) = tokio::io::duplex(64);
+ let (mut client, server) = tokio::io::duplex(256);
client
.write_all(
b"POST /mcp HTTP/1.1\r\n\
Content-Length: 8\r\n\
+ Content-Type: application/json\r\n\
\r\n\
{}",
)
@@ -451,7 +633,7 @@ mod mcp_hardening_tests {
.unwrap();
let mut reader = BufReader::new(server);
- let err = match read_request_with_timeout(&mut reader, None, Duration::from_millis(20))
+ let err = match read_request_with_timeout(&mut reader, None, None, Duration::from_millis(20))
.await
{
Err(err) => err,
diff --git a/crates/obscura-mcp/src/lib.rs b/crates/obscura-mcp/src/lib.rs
index bd5e79cf..6b6b780b 100644
--- a/crates/obscura-mcp/src/lib.rs
+++ b/crates/obscura-mcp/src/lib.rs
@@ -937,6 +937,12 @@ fn truncate(text: &str, max_chars: usize) -> String {
async fn tool_navigate(args: &Value, state: &mut BrowserState) -> Result<String, String> {
let url = args.get("url").and_then(Value::as_str)
.ok_or("Missing url parameter")?;
+ if url::Url::parse(url)
+ .ok()
+ .is_some_and(|parsed| parsed.scheme() == "file")
+ {
+ return Err("file:// navigation is disabled for MCP".to_string());
+ }
let wait_until = args.get("waitUntil").and_then(Value::as_str).unwrap_or("load");
let condition = obscura_browser::lifecycle::WaitUntil::from_str(wait_until);
@@ -2118,6 +2124,15 @@ mod tests {
}));
}
+ #[tokio::test(flavor = "current_thread")]
+ async fn mcp_navigation_rejects_local_files() {
+ let mut state = BrowserState::new(None, None, false);
+ let error = tool_navigate(&json!({"url": "file:///etc/passwd"}), &mut state)
+ .await
+ .expect_err("MCP must not expose local files");
+ assert!(error.contains("file:// navigation is disabled"));
+ }
+
#[cfg(feature = "render")]
#[test]
fn render_tools_are_advertised_with_flat_schemas() {
diff --git a/crates/obscura-mcp/tests/cors_preflight.rs b/crates/obscura-mcp/tests/cors_preflight.rs
index 80e95ef8..a89b2fc9 100644
--- a/crates/obscura-mcp/tests/cors_preflight.rs
+++ b/crates/obscura-mcp/tests/cors_preflight.rs
@@ -1,8 +1,5 @@
-//! Regression test for issue #175: the MCP HTTP server's OPTIONS preflight
-//! response must list every header a browser MCP client may send, including
-//! `mcp-protocol-version` (from the MCP spec) and `Authorization` /
-//! `X-API-Key` (common in hosted deployments). Otherwise the browser blocks
-//! the actual request with a CORS error.
+//! Browser callers are denied unless the operator explicitly allowlists their
+//! Origin. Native MCP clients send no Origin and are unaffected.
use std::net::TcpListener as StdListener;
use std::time::Duration;
@@ -19,7 +16,7 @@ fn pick_free_port() -> u16 {
}
#[tokio::test(flavor = "current_thread")]
-async fn options_preflight_lists_required_browser_headers() {
+async fn browser_preflight_is_denied_without_an_origin_allowlist() {
let port = pick_free_port();
let local = LocalSet::new();
@@ -60,27 +57,9 @@ async fn options_preflight_lists_required_browser_headers() {
server.abort();
- assert!(
- response.starts_with("HTTP/1.1 204"),
- "expected 204 No Content preflight, got:\n{response}"
- );
+ assert!(response.starts_with("HTTP/1.1 403"), "expected 403, got:\n{response}");
let lc = response.to_lowercase();
- assert!(
- lc.contains("access-control-allow-headers:"),
- "preflight must include Access-Control-Allow-Headers; got:\n{response}"
- );
- assert!(
- lc.contains("mcp-protocol-version"),
- "ACAH must list mcp-protocol-version (per MCP spec); got:\n{response}"
- );
- assert!(
- lc.contains("authorization"),
- "ACAH must list Authorization for hosted deployments; got:\n{response}"
- );
- assert!(
- lc.contains("x-api-key"),
- "ACAH must list X-API-Key for hosted deployments; got:\n{response}"
- );
+ assert!(!lc.contains("access-control-allow-origin: *"));
})
.await;
}
diff --git a/crates/obscura-mcp/tests/sse_stream_does_not_wedge.rs b/crates/obscura-mcp/tests/sse_stream_does_not_wedge.rs
index 81c92b2b..401b6ca1 100644
--- a/crates/obscura-mcp/tests/sse_stream_does_not_wedge.rs
+++ b/crates/obscura-mcp/tests/sse_stream_does_not_wedge.rs
@@ -72,7 +72,6 @@ async fn open_sse_stream_does_not_block_other_requests() {
.expect("second connection refused");
let req = b"OPTIONS /mcp HTTP/1.1\r\n\
Host: 127.0.0.1\r\n\
- Origin: https://dashboard.example.com\r\n\
Access-Control-Request-Method: POST\r\n\
\r\n";
stream.write_all(req).await.unwrap();
diff --git a/crates/obscura-net/Cargo.toml b/crates/obscura-net/Cargo.toml
index 8d0763b1..070a4fda 100644
--- a/crates/obscura-net/Cargo.toml
+++ b/crates/obscura-net/Cargo.toml
@@ -20,6 +20,7 @@ thiserror = { workspace = true }
async-trait = "0.1"
encoding_rs = "0.8"
tempfile = "3"
+psl = "2"
futures-util = { version = "0.3", optional = true }
# wreq and wreq-util are pre-release crates whose API changes between rc builds
# (CertStore moved out of `tls`, `cert_store` renamed to `tls_cert_store`, the
diff --git a/crates/obscura-net/src/client.rs b/crates/obscura-net/src/client.rs
index a11847ff..acf92496 100644
--- a/crates/obscura-net/src/client.rs
+++ b/crates/obscura-net/src/client.rs
@@ -12,7 +12,7 @@ use reqwest::{Client, Method};
use tokio::sync::{RwLock, watch};
use url::Url;
-use crate::cookies::CookieJar;
+use crate::cookies::{same_site, CookieJar, SameSiteContext};
use crate::interceptor::{InterceptAction, RequestInterceptor};
fn configured_root_paths() -> Vec<std::path::PathBuf> {
@@ -449,6 +449,23 @@ pub(crate) fn request_fetch_site(request: &ResourceRequest, target: &Url) -> &'s
}
}
+pub(crate) fn same_site_context(
+ request: &ResourceRequest,
+ target: &Url,
+ method_is_safe: bool,
+) -> SameSiteContext {
+ let Some(initiator) = request.initiator.as_ref() else {
+ return SameSiteContext::SameSite;
+ };
+ if same_site(initiator, target) {
+ SameSiteContext::SameSite
+ } else if request.mode == RequestMode::Navigate && method_is_safe {
+ SameSiteContext::CrossSiteTopLevelSafe
+ } else {
+ SameSiteContext::CrossSite
+ }
+}
+
pub(crate) fn request_referrer(request: &ResourceRequest, target: &Url) -> Option<String> {
let source = request
.referrer
@@ -1288,7 +1305,12 @@ impl ObscuraHttpClient {
}) {
return None;
}
- if request.sends_credentials_to(url) && !self.cookie_jar.get_cookie_header(url).is_empty() {
+ if request.sends_credentials_to(url)
+ && !self
+ .cookie_jar
+ .get_cookie_header_in_context(url, SameSiteContext::SameSite)
+ .is_empty()
+ {
return None;
}
Some(ResourceCacheKey {
@@ -1579,7 +1601,14 @@ impl ObscuraHttpClient {
}
let cookie_header = if request.sends_credentials_to(&current_url) {
- self.cookie_jar.get_cookie_header(&current_url)
+ self.cookie_jar.get_cookie_header_in_context(
+ &current_url,
+ same_site_context(
+ &request,
+ &current_url,
+ matches!(method, Method::GET | Method::HEAD),
+ ),
+ )
} else {
String::new()
};
@@ -2147,7 +2176,7 @@ mod ssrf_tests {
assert!(request.contains("sec-fetch-mode: cors\r\n"));
assert!(request.contains("sec-fetch-dest: font\r\n"));
assert!(!request.contains("cookie:"));
- assert_eq!(jar.get_cookie_header(&target), "seed=1");
+ assert_eq!(jar.get_cookie_header_same_site(&target), "seed=1");
}
// #849 — the OBSCURA_FETCH_MAX_BODY_BYTES override #581 gave fetch()/XHR
@@ -2209,7 +2238,7 @@ mod ssrf_tests {
assert!(request.contains("sec-fetch-dest: script\r\n"));
assert!(request.contains(&format!("referer: {}\r\n", importing_module)));
assert!(!request.contains("cookie:"));
- assert_eq!(jar.get_cookie_header(&target), "seed=1");
+ assert_eq!(jar.get_cookie_header_same_site(&target), "seed=1");
}
#[tokio::test]
@@ -2245,7 +2274,7 @@ mod ssrf_tests {
let second = received.recv().await.unwrap().to_ascii_lowercase();
assert!(first.contains("cookie: seed=1\r\n"));
assert!(second.contains("cookie: seed=1\r\n"));
- let cookies = jar.get_cookie_header(&target);
+ let cookies = jar.get_cookie_header_same_site(&target);
assert!(cookies.contains("seed=1"));
assert!(cookies.contains("accepted=1"));
}
diff --git a/crates/obscura-net/src/cookies.rs b/crates/obscura-net/src/cookies.rs
index 6ac82600..82cb3688 100644
--- a/crates/obscura-net/src/cookies.rs
+++ b/crates/obscura-net/src/cookies.rs
@@ -32,6 +32,14 @@ pub struct CookieJar {
cookies: RwLock<HashMap<String, HashMap<(String, String), CookieEntry>>>,
}
+/// The site relationship used when deciding whether a cookie may be sent.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum SameSiteContext {
+ SameSite,
+ CrossSiteTopLevelSafe,
+ CrossSite,
+}
+
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
struct CookieEntry {
name: String,
@@ -117,20 +125,29 @@ impl CookieJar {
}
// Validate Domain against the response origin (RFC 6265): an unrelated
- // or public-suffix Domain is ignored so a response from attacker.test
+ // or public-suffix Domain rejects the cookie so a response from attacker.test
// cannot scope a cookie to victim.test (GHSA-f22c-8v6q-v6h6).
let (domain, host_only) = match resolve_cookie_domain(&request_host, domain_attr.as_deref()) {
Some(d) => d,
None => return,
};
+ let source_is_secure = url.scheme() == "https";
+ if (secure && !source_is_secure) || (same_site == "None" && !secure) {
+ return;
+ }
+
+ let mut cookies = self.cookies.write().unwrap();
+ if !source_is_secure && secure_cookie_conflicts(&cookies, &name, &domain, &path) {
+ return;
+ }
+
if let Some(exp) = expires {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_secs();
if exp <= now {
- let mut cookies = self.cookies.write().unwrap();
if let Some(domain_cookies) = cookies.get_mut(&domain) {
domain_cookies.remove(&(name.clone(), path.clone()));
}
@@ -150,16 +167,30 @@ impl CookieJar {
same_site,
};
- let mut cookies = self.cookies.write().unwrap();
cookies.entry(domain).or_default().insert((name, path), entry);
}
+ /// Return cookies for a same-site request.
+ ///
+ /// Existing callers use this method without an initiator URL. Browser
+ /// request paths use `get_cookie_header_in_context` so cross-site policy is
+ /// still enforced where the site relationship is known.
pub fn get_cookie_header(&self, url: &Url) -> String {
+ self.get_cookie_header_same_site(url)
+ }
+
+ pub fn get_cookie_header_same_site(&self, url: &Url) -> String {
+ self.get_cookie_header_in_context(url, SameSiteContext::SameSite)
+ }
+
+ pub fn get_cookie_header_in_context(&self, url: &Url, context: SameSiteContext) -> String {
let host = url.host_str().unwrap_or("");
let path = url.path();
let is_secure = url.scheme() == "https";
let cookies = self.cookies.read().unwrap();
-
+ if cookies.is_empty() {
+ return String::new();
+ }
let mut matching: Vec<String> = Vec::new();
let now = std::time::SystemTime::now()
@@ -183,6 +214,19 @@ impl CookieJar {
if entry.secure && !is_secure {
continue;
}
+ match context {
+ SameSiteContext::SameSite => {}
+ SameSiteContext::CrossSiteTopLevelSafe => {
+ if entry.same_site == "Strict" {
+ continue;
+ }
+ }
+ SameSiteContext::CrossSite => {
+ if entry.same_site != "None" {
+ continue;
+ }
+ }
+ }
if !path_matches(path, &entry.path) {
continue;
}
@@ -221,15 +265,49 @@ impl CookieJar {
}
pub fn set_cookies_from_cdp(&self, cookies: Vec<CookieInfo>) {
+ self.set_cookies_from_import(cookies.into_iter().map(|cookie| (cookie, false)));
+ }
+
+ /// Import CDP cookies while preserving whether each cookie was created
+ /// from a URL (host-only) or an explicit Domain field (domain-scoped).
+ #[doc(hidden)]
+ pub fn set_cookies_from_cdp_with_scope(
+ &self,
+ cookies: impl IntoIterator<Item = (CookieInfo, bool)>,
+ ) {
+ self.set_cookies_from_import(cookies);
+ }
+
+ /// Replace this jar with an independent copy of another jar, including
+ /// host-only scope which is intentionally absent from the public CDP model.
+ pub fn copy_from(&self, source: &CookieJar) {
+ if std::ptr::eq(self, source) {
+ return;
+ }
+ let snapshot = source.cookies.read().unwrap().clone();
+ *self.cookies.write().unwrap() = snapshot;
+ }
+
+ fn set_cookies_from_import(&self, cookies: impl IntoIterator<Item = (CookieInfo, bool)>) {
let mut jar = self.cookies.write().unwrap();
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_secs() as i64;
- for cookie in cookies {
+ for (cookie, host_only) in cookies {
// RFC 6265 4.1.2.3: the leading dot is ignored. The Set-Cookie path already strips
// it, but this code did not, which is why one cookie became two entries.
let domain = canonical_domain(&cookie.domain);
+ if domain.is_empty()
+ || (is_public_suffix(&domain)
+ && domain != "localhost"
+ && domain.parse::<std::net::IpAddr>().is_err())
+ {
+ continue;
+ }
+ if cookie.same_site == "None" && !cookie.secure {
+ continue;
+ }
if cookie.expires.is_some_and(|expires| {
expires == 0 || (expires > 0 && expires <= now)
}) {
@@ -251,9 +329,7 @@ impl CookieJar {
value: cookie.value,
path: cookie.path.clone(),
domain: domain.clone(),
- // CDP/persisted import is trusted; honor the explicit domain as
- // domain-scoped (matches the prior behavior).
- host_only: false,
+ host_only,
secure: cookie.secure,
http_only: cookie.http_only,
expires,
@@ -368,13 +444,22 @@ impl CookieJar {
None => return,
};
+ let source_is_secure = url.scheme() == "https";
+ if (secure && !source_is_secure) || (same_site == "None" && !secure) {
+ return;
+ }
+
+ let mut cookies = self.cookies.write().unwrap();
+ if !source_is_secure && secure_cookie_conflicts(&cookies, &name, &domain, &path) {
+ return;
+ }
+
if let Some(exp) = expires {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_secs();
if exp <= now {
- let mut cookies = self.cookies.write().unwrap();
if let Some(domain_cookies) = cookies.get_mut(&domain) {
// RFC 6265 §5.3: a non-HTTP API (document.cookie) must not
// delete an existing HttpOnly cookie.
@@ -400,7 +485,6 @@ impl CookieJar {
same_site,
};
- let mut cookies = self.cookies.write().unwrap();
let domain_cookies = cookies.entry(domain).or_default();
// RFC 6265 §5.3: a non-HTTP API (document.cookie) must not overwrite an
// existing HttpOnly cookie set by the server.
@@ -454,7 +538,7 @@ impl CookieJar {
.unwrap_or_default()
.as_secs();
- let mut all: Vec<CookieInfo> = Vec::new();
+ let mut all: Vec<PersistedCookie> = Vec::new();
for domain_cookies in cookies.values() {
for entry in domain_cookies.values() {
if let Some(exp) = entry.expires {
@@ -462,15 +546,18 @@ impl CookieJar {
continue;
}
}
- all.push(CookieInfo {
- name: entry.name.clone(),
- value: entry.value.clone(),
- domain: entry.domain.clone(),
- path: entry.path.clone(),
- secure: entry.secure,
- http_only: entry.http_only,
- same_site: entry.same_site.clone(),
- expires: entry.expires.map(|e| e as i64),
+ all.push(PersistedCookie {
+ cookie: CookieInfo {
+ name: entry.name.clone(),
+ value: entry.value.clone(),
+ domain: entry.domain.clone(),
+ path: entry.path.clone(),
+ secure: entry.secure,
+ http_only: entry.http_only,
+ same_site: entry.same_site.clone(),
+ expires: entry.expires.map(|e| e as i64),
+ },
+ host_only: Some(entry.host_only),
});
}
}
@@ -497,12 +584,14 @@ impl CookieJar {
return Ok(0);
}
let data = std::fs::read_to_string(path)?;
- let cookies: Vec<CookieInfo> =
- serde_json::from_str(&data).map_err(|e| {
- std::io::Error::new(std::io::ErrorKind::InvalidData, e)
- })?;
+ let cookies: Vec<PersistedCookie> = serde_json::from_str(&data)
+ .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
let count = cookies.len();
- self.set_cookies_from_cdp(cookies);
+ self.set_cookies_from_import(
+ cookies
+ .into_iter()
+ .map(|persisted| (persisted.cookie, persisted.host_only.unwrap_or(false))),
+ );
Ok(count)
}
}
@@ -528,6 +617,17 @@ pub struct CookieInfo {
pub expires: Option<i64>,
}
+#[derive(Debug, serde::Serialize, serde::Deserialize)]
+struct PersistedCookie {
+ #[serde(flatten)]
+ cookie: CookieInfo,
+ /// Absent in older/third-party cookie files, whose Domain field has always
+ /// meant a domain-scoped cookie. Files written by Obscura preserve the
+ /// distinction explicitly.
+ #[serde(default, rename = "hostOnly", skip_serializing_if = "Option::is_none")]
+ host_only: Option<bool>,
+}
+
fn parse_http_date(s: &str) -> Result<u64, ()> {
let months = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];
@@ -564,17 +664,10 @@ fn parse_http_date(s: &str) -> Result<u64, ()> {
/// `origin_host` (RFC 6265 §5.2/§5.3). With no Domain attribute the cookie is
/// host-only: scoped to the exact origin host. A Domain attribute is honored
/// only when it domain-matches the origin (equal to it or a parent domain) and
-/// is not an obvious public suffix; otherwise the attribute is ignored and the
-/// cookie is stored host-only on the origin. This is what stops a response from
-/// attacker.test planting a cookie scoped to victim.test.
-///
-/// Returns None only when the origin host itself is absent (the cookie cannot
-/// be scoped and is dropped).
+/// is not a public suffix. Invalid Domain attributes reject the cookie rather
+/// than silently widening or changing its scope. Per RFC 6265, a public suffix
+/// equal to the request host is retained as a host-only cookie.
///
-/// Note: a full public suffix list is not bundled, so multi-label public
-/// suffixes (co.uk, github.io) are not rejected; the domain-match check still
-/// blocks the reported cross-domain attack, and single-label suffixes (com,
-/// local) are rejected.
fn resolve_cookie_domain(origin_host: &str, domain_attr: Option<&str>) -> Option<(String, bool)> {
let origin = canonical_domain(origin_host);
if origin.is_empty() {
@@ -584,14 +677,52 @@ fn resolve_cookie_domain(origin_host: &str, domain_attr: Option<&str>) -> Option
None => return Some((origin, true)),
Some(raw) => canonical_domain(raw),
};
- if dom.is_empty() || dom == origin {
- return Some((origin, true));
+ if dom.is_empty() {
+ return None;
}
- if dom.contains('.') && origin.ends_with(&format!(".{dom}")) {
- Some((dom, false))
- } else {
- Some((origin, true))
+ if is_public_suffix(&dom) {
+ return (dom == origin).then_some((origin, true));
}
+ (dom == origin
+ || origin
+ .strip_suffix(&dom)
+ .is_some_and(|prefix| prefix.ends_with('.')))
+ .then_some((dom, false))
+}
+
+fn is_public_suffix(domain: &str) -> bool {
+ psl::suffix_str(domain).is_some_and(|suffix| suffix.eq_ignore_ascii_case(domain))
+}
+
+/// RFC 6265bis secure-overlay protection: an insecure response must not replace
+/// or shadow a Secure cookie. Cookie writes are rare, so scanning the jar here
+/// is preferable to adding another index to every request hot path.
+fn secure_cookie_conflicts(
+ cookies: &HashMap<String, HashMap<(String, String), CookieEntry>>,
+ name: &str,
+ domain: &str,
+ path: &str,
+) -> bool {
+ cookies.iter().any(|(stored_domain, entries)| {
+ (domain_matches(domain, stored_domain) || domain_matches(stored_domain, domain))
+ && entries.values().any(|entry| {
+ entry.secure
+ && entry.name == name
+ && (path_matches(path, &entry.path) || path_matches(&entry.path, path))
+ })
+ })
+}
+
+pub fn same_site(source: &Url, target: &Url) -> bool {
+ if source.scheme() != target.scheme() {
+ return false;
+ }
+ let (Some(source_host), Some(target_host)) = (source.host_str(), target.host_str()) else {
+ return false;
+ };
+ let source_site = psl::domain_str(source_host).unwrap_or(source_host);
+ let target_site = psl::domain_str(target_host).unwrap_or(target_host);
+ source_site.eq_ignore_ascii_case(target_site)
}
// RFC 6265 5.1.4 default-path: the path a cookie is scoped to when its
@@ -661,7 +792,7 @@ mod tests {
let url = Url::parse("https://example.com/path").unwrap();
jar.set_cookie("session=abc123; Path=/; Secure; HttpOnly", &url);
- let header = jar.get_cookie_header(&url);
+ let header = jar.get_cookie_header_same_site(&url);
assert!(header.contains("session=abc123"));
}
@@ -680,7 +811,8 @@ mod tests {
"JS must not overwrite an HttpOnly cookie"
);
assert!(
- !jar.get_cookie_header(&url).contains("attacker_value"),
+ !jar.get_cookie_header_same_site(&url)
+ .contains("attacker_value"),
"the attacker value must not be stored"
);
}
@@ -708,7 +840,7 @@ mod tests {
jar.set_cookie_from_js("pref=dark", &url);
assert!(
- jar.get_cookie_header(&url).contains("pref=dark"),
+ jar.get_cookie_header_same_site(&url).contains("pref=dark"),
"JS must remain able to overwrite a non-HttpOnly cookie"
);
}
@@ -719,15 +851,15 @@ mod tests {
let url = Url::parse("https://www.example.com/").unwrap();
jar.set_cookie("token=xyz; Domain=example.com", &url);
- let header = jar.get_cookie_header(&url);
+ let header = jar.get_cookie_header_same_site(&url);
assert!(header.contains("token=xyz"));
let sub_url = Url::parse("https://api.example.com/").unwrap();
- let header2 = jar.get_cookie_header(&sub_url);
+ let header2 = jar.get_cookie_header_same_site(&sub_url);
assert!(header2.contains("token=xyz"));
let other_url = Url::parse("https://other.com/").unwrap();
- let header3 = jar.get_cookie_header(&other_url);
+ let header3 = jar.get_cookie_header_same_site(&other_url);
assert!(header3.is_empty());
}
@@ -746,15 +878,15 @@ mod tests {
}]);
let apex_url = Url::parse("https://example.com/").unwrap();
- let apex_header = jar.get_cookie_header(&apex_url);
+ let apex_header = jar.get_cookie_header_same_site(&apex_url);
assert!(apex_header.contains("token=xyz"));
let subdomain_url = Url::parse("https://api.example.com/").unwrap();
- let subdomain_header = jar.get_cookie_header(&subdomain_url);
+ let subdomain_header = jar.get_cookie_header_same_site(&subdomain_url);
assert!(subdomain_header.contains("token=xyz"));
let other_url = Url::parse("https://other.com/").unwrap();
- let other_header = jar.get_cookie_header(&other_url);
+ let other_header = jar.get_cookie_header_same_site(&other_url);
assert!(other_header.is_empty());
}
@@ -765,7 +897,7 @@ mod tests {
jar.set_cookie("secure_token=secret; Secure", &https_url);
let http_url = Url::parse("http://example.com/").unwrap();
- let header = jar.get_cookie_header(&http_url);
+ let header = jar.get_cookie_header_same_site(&http_url);
assert!(header.is_empty());
}
@@ -774,10 +906,12 @@ mod tests {
let jar = CookieJar::new();
let url = Url::parse("https://example.com/").unwrap();
jar.set_cookie("session=abc", &url);
- assert!(jar.get_cookie_header(&url).contains("session=abc"));
+ assert!(jar
+ .get_cookie_header_same_site(&url)
+ .contains("session=abc"));
jar.set_cookie("session=abc; Max-Age=0", &url);
- assert!(jar.get_cookie_header(&url).is_empty());
+ assert!(jar.get_cookie_header_same_site(&url).is_empty());
}
#[test]
@@ -806,7 +940,7 @@ mod tests {
let url = Url::parse("https://example.com/a/x").unwrap();
jar.set_cookie("id=1; Path=/a", &url);
jar.set_cookie("id=2; Path=/a", &url);
- let header = jar.get_cookie_header(&url);
+ let header = jar.get_cookie_header_same_site(&url);
assert!(header.contains("id=2"), "newer value must win: {header:?}");
assert!(!header.contains("id=1"), "old value must be replaced: {header:?}");
}
@@ -832,7 +966,7 @@ mod tests {
let jar = CookieJar::new();
let url = Url::parse("https://example.com/").unwrap();
jar.set_cookie("token=xyz; Max-Age=3600", &url);
- assert!(jar.get_cookie_header(&url).contains("token=xyz"));
+ assert!(jar.get_cookie_header_same_site(&url).contains("token=xyz"));
}
#[test]
@@ -841,7 +975,7 @@ mod tests {
let url = Url::parse("https://example.com/").unwrap();
jar.set_cookie("old=current", &url);
jar.set_cookie("old=gone; Expires=Thu, 01 Jan 2020 00:00:00 GMT", &url);
- assert!(jar.get_cookie_header(&url).is_empty());
+ assert!(jar.get_cookie_header_same_site(&url).is_empty());
assert!(jar.get_all_cookies().is_empty());
}
@@ -862,7 +996,9 @@ mod tests {
let jar = CookieJar::new();
let url = Url::parse("https://example.com/").unwrap();
jar.set_cookie("strict_cookie=val; SameSite=Strict", &url);
- assert!(jar.get_cookie_header(&url).contains("strict_cookie=val"));
+ assert!(jar
+ .get_cookie_header_same_site(&url)
+ .contains("strict_cookie=val"));
}
#[test]
@@ -870,10 +1006,10 @@ mod tests {
let jar = CookieJar::new();
let url = Url::parse("https://example.com/").unwrap();
jar.set_cookie("a=1", &url);
- assert!(!jar.get_cookie_header(&url).is_empty());
+ assert!(!jar.get_cookie_header_same_site(&url).is_empty());
jar.clear();
- assert!(jar.get_cookie_header(&url).is_empty());
+ assert!(jar.get_cookie_header_same_site(&url).is_empty());
}
#[test]
@@ -1137,7 +1273,7 @@ mod tests {
let count = jar2.load_from_file(&path).unwrap();
assert_eq!(count, 2);
- let header = jar2.get_cookie_header(&url);
+ let header = jar2.get_cookie_header_same_site(&url);
assert!(header.contains("session=abc123"));
assert!(header.contains("token=xyz"));
}
@@ -1172,7 +1308,6 @@ mod tests {
#[test]
fn test_cookie_from_file_load_then_send_in_request() {
// Simulate what happens: load cookies from file → navigate → cookie should be in request
- use std::io::Write;
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("cookies.json");
@@ -1188,7 +1323,7 @@ mod tests {
assert_eq!(count, 2, "Should load 2 cookies");
let url = Url::parse("https://www.xiaohongshu.com/explore").unwrap();
- let header = jar.get_cookie_header(&url);
+ let header = jar.get_cookie_header_same_site(&url);
assert!(header.contains("a1=testval"), "Missing a1 in: '{}'", header);
assert!(header.contains("web_session=sess123"), "Missing web_session in: '{}'", header);
}
@@ -1203,12 +1338,16 @@ mod tests {
let victim = Url::parse("http://victim.test/account").unwrap();
assert!(
- !jar.get_cookie_header(&victim).contains("sid=attacker"),
+ !jar.get_cookie_header_same_site(&victim)
+ .contains("sid=attacker"),
"cross-domain cookie leaked to victim: {}",
- jar.get_cookie_header(&victim)
+ jar.get_cookie_header_same_site(&victim)
);
- // The cookie is stored host-only on the attacker origin instead.
- assert!(jar.get_cookie_header(&attacker).contains("sid=attacker"));
+ // An invalid Domain attribute rejects the cookie rather than silently
+ // changing its scope.
+ assert!(!jar
+ .get_cookie_header_same_site(&attacker)
+ .contains("sid=attacker"));
}
#[test]
@@ -1219,9 +1358,10 @@ mod tests {
let victim = Url::parse("http://victim.test/account").unwrap();
assert!(
- !jar.get_cookie_header(&victim).contains("js_sid=attacker"),
+ !jar.get_cookie_header_same_site(&victim)
+ .contains("js_sid=attacker"),
"cross-domain JS cookie leaked to victim: {}",
- jar.get_cookie_header(&victim)
+ jar.get_cookie_header_same_site(&victim)
);
}
@@ -1232,7 +1372,123 @@ mod tests {
jar.set_cookie("bad=1; Domain=com; Path=/", &url);
// "com" is a public suffix; the cookie must not be scoped to it.
let other = Url::parse("http://other.com/").unwrap();
- assert!(!jar.get_cookie_header(&other).contains("bad=1"));
+ assert!(!jar.get_cookie_header_same_site(&other).contains("bad=1"));
+ }
+
+ #[test]
+ fn multi_label_and_private_public_suffixes_are_rejected() {
+ for (origin, suffix, sibling) in [
+ (
+ "https://a.example.co.uk/",
+ "co.uk",
+ "https://b.example.co.uk/",
+ ),
+ (
+ "https://alice.github.io/",
+ "github.io",
+ "https://bob.github.io/",
+ ),
+ ] {
+ let jar = CookieJar::new();
+ jar.set_cookie(
+ &format!("sid=secret; Domain={suffix}; Path=/; Secure"),
+ &Url::parse(origin).unwrap(),
+ );
+ assert!(jar
+ .get_cookie_header_same_site(&Url::parse(origin).unwrap())
+ .is_empty());
+ assert!(jar
+ .get_cookie_header_same_site(&Url::parse(sibling).unwrap())
+ .is_empty());
+ }
+
+ let jar = CookieJar::new();
+ let public_suffix_host = Url::parse("https://github.io/").unwrap();
+ jar.set_cookie(
+ "sid=secret; Domain=github.io; Path=/; Secure",
+ &public_suffix_host,
+ );
+ assert!(jar
+ .get_cookie_header_same_site(&public_suffix_host)
+ .contains("sid=secret"));
+ assert!(jar
+ .get_cookie_header_same_site(&Url::parse("https://sub.github.io/").unwrap())
+ .is_empty());
+ }
+
+ #[test]
+ fn insecure_origin_cannot_set_or_overwrite_secure_cookie() {
+ let jar = CookieJar::new();
+ let https = Url::parse("https://example.com/").unwrap();
+ let http = Url::parse("http://example.com/").unwrap();
+
+ jar.set_cookie("sid=secure; Secure; Path=/", &https);
+ jar.set_cookie("sid=attacker; Path=/", &http);
+ assert_eq!(jar.get_cookie_header_same_site(&https), "sid=secure");
+
+ jar.set_cookie("new=attacker; Secure; Path=/", &http);
+ assert!(!jar.get_cookie_header_same_site(&https).contains("new="));
+ }
+
+ #[test]
+ fn host_only_scope_survives_save_and_load() {
+ let tmp = tempfile::tempdir().unwrap();
+ let path = tmp.path().join("cookies.json");
+ let jar = CookieJar::new();
+ let host = Url::parse("https://www.example.com/").unwrap();
+ jar.set_cookie("sid=host-only; Secure; Path=/", &host);
+ jar.save_to_file(&path).unwrap();
+
+ let loaded = CookieJar::new();
+ loaded.load_from_file(&path).unwrap();
+ assert!(loaded
+ .get_cookie_header_same_site(&host)
+ .contains("sid=host-only"));
+ assert!(loaded
+ .get_cookie_header_same_site(&Url::parse("https://sub.www.example.com/").unwrap())
+ .is_empty());
+ }
+
+ #[test]
+ fn same_site_is_enforced_for_subresources() {
+ let jar = CookieJar::new();
+ let target = Url::parse("https://api.example.com/data").unwrap();
+ jar.set_cookie(
+ "strict=1; Domain=example.com; SameSite=Strict; Secure",
+ &target,
+ );
+ jar.set_cookie("lax=1; Domain=example.com; SameSite=Lax; Secure", &target);
+ jar.set_cookie("none=1; Domain=example.com; SameSite=None; Secure", &target);
+
+ let same_site_source = Url::parse("https://www.example.com/page").unwrap();
+ assert!(same_site(&same_site_source, &target));
+ let same_site_header = jar.get_cookie_header_in_context(&target, SameSiteContext::SameSite);
+ assert!(same_site_header.contains("strict=1"));
+ assert!(same_site_header.contains("lax=1"));
+ assert!(same_site_header.contains("none=1"));
+
+ let cross_site_source = Url::parse("https://attacker.test/page").unwrap();
+ assert!(!same_site(&cross_site_source, &target));
+ let subresource = jar.get_cookie_header_in_context(&target, SameSiteContext::CrossSite);
+ assert_eq!(subresource, "none=1");
+
+ let top_level =
+ jar.get_cookie_header_in_context(&target, SameSiteContext::CrossSiteTopLevelSafe);
+ assert!(!top_level.contains("strict=1"));
+ assert!(top_level.contains("lax=1"));
+ assert!(top_level.contains("none=1"));
+ }
+
+ #[test]
+ fn same_site_none_requires_secure() {
+ let jar = CookieJar::new();
+ let target = Url::parse("https://example.com/").unwrap();
+ jar.set_cookie("insecure=1; SameSite=None", &target);
+ jar.set_cookie("secure=1; SameSite=None; Secure", &target);
+ assert_eq!(
+ jar.get_cookie_header_in_context(&target, SameSiteContext::CrossSite),
+ "secure=1"
+ );
}
#[test]
@@ -1241,12 +1497,12 @@ mod tests {
let www = Url::parse("http://www.example.com/").unwrap();
jar.set_cookie("hostonly=1; Path=/", &www); // no Domain attribute -> host-only
- assert!(jar.get_cookie_header(&www).contains("hostonly=1"));
+ assert!(jar.get_cookie_header_same_site(&www).contains("hostonly=1"));
let sub = Url::parse("http://sub.www.example.com/").unwrap();
assert!(
- !jar.get_cookie_header(&sub).contains("hostonly=1"),
+ !jar.get_cookie_header_same_site(&sub).contains("hostonly=1"),
"host-only cookie leaked to subdomain: {}",
- jar.get_cookie_header(&sub)
+ jar.get_cookie_header_same_site(&sub)
);
}
@@ -1258,9 +1514,9 @@ mod tests {
jar.set_cookie("token=1; Domain=example.com; Path=/", &www);
let apex = Url::parse("http://example.com/").unwrap();
- assert!(jar.get_cookie_header(&apex).contains("token=1"));
+ assert!(jar.get_cookie_header_same_site(&apex).contains("token=1"));
let api = Url::parse("http://api.example.com/").unwrap();
- assert!(jar.get_cookie_header(&api).contains("token=1"));
+ assert!(jar.get_cookie_header_same_site(&api).contains("token=1"));
}
#[test]
@@ -1274,16 +1530,18 @@ mod tests {
let sibling = Url::parse("https://example.com/administrator").unwrap();
assert!(
- !jar.get_cookie_header(&sibling).contains("sess=1"),
+ !jar.get_cookie_header_same_site(&sibling).contains("sess=1"),
"cookie leaked to sibling path /administrator: {}",
- jar.get_cookie_header(&sibling)
+ jar.get_cookie_header_same_site(&sibling)
);
- assert!(jar.get_cookie_header(&admin).contains("sess=1"));
+ assert!(jar.get_cookie_header_same_site(&admin).contains("sess=1"));
let exact_slash = Url::parse("https://example.com/admin/").unwrap();
- assert!(jar.get_cookie_header(&exact_slash).contains("sess=1"));
+ assert!(jar
+ .get_cookie_header_same_site(&exact_slash)
+ .contains("sess=1"));
let sub = Url::parse("https://example.com/admin/panel").unwrap();
- assert!(jar.get_cookie_header(&sub).contains("sess=1"));
+ assert!(jar.get_cookie_header_same_site(&sub).contains("sess=1"));
}
#[test]
@@ -1311,19 +1569,22 @@ mod tests {
let dashboard = Url::parse("https://example.com/app/dashboard").unwrap();
assert!(
- jar.get_cookie_header(&dashboard).contains("sid=abc"),
+ jar.get_cookie_header_same_site(&dashboard)
+ .contains("sid=abc"),
"session cookie was not sent to a sibling path under the same directory: {}",
- jar.get_cookie_header(&dashboard)
+ jar.get_cookie_header_same_site(&dashboard)
);
// Still sent at the directory root and the original path.
let app_root = Url::parse("https://example.com/app/").unwrap();
- assert!(jar.get_cookie_header(&app_root).contains("sid=abc"));
- assert!(jar.get_cookie_header(&login).contains("sid=abc"));
+ assert!(jar
+ .get_cookie_header_same_site(&app_root)
+ .contains("sid=abc"));
+ assert!(jar.get_cookie_header_same_site(&login).contains("sid=abc"));
// But not to an unrelated top-level path outside the directory.
let other = Url::parse("https://example.com/other").unwrap();
assert!(
- !jar.get_cookie_header(&other).contains("sid=abc"),
+ !jar.get_cookie_header_same_site(&other).contains("sid=abc"),
"cookie leaked outside its default-path directory"
);
}
diff --git a/crates/obscura-net/src/lib.rs b/crates/obscura-net/src/lib.rs
index b9d0b96d..2b8c18fb 100644
--- a/crates/obscura-net/src/lib.rs
+++ b/crates/obscura-net/src/lib.rs
@@ -12,7 +12,9 @@ pub use client::{
ObscuraNetError, RequestCallback, RequestCredentials, RequestInfo, RequestMode,
ResourceRequest, ResourceType, Response, ResponseCallback, SsrfGuardResolver,
};
-pub use cookies::{canonical_domain, default_cookie_path, CookieInfo, CookieJar};
+pub use cookies::{
+ canonical_domain, default_cookie_path, same_site, CookieInfo, CookieJar, SameSiteContext,
+};
pub use encoding::{
decode_non_html, decode_response, decode_response_with_name, decode_with_label, label_name,
url_encode_query,
diff --git a/crates/obscura-net/src/wreq_client.rs b/crates/obscura-net/src/wreq_client.rs
index 8806c38f..550dd18e 100644
--- a/crates/obscura-net/src/wreq_client.rs
+++ b/crates/obscura-net/src/wreq_client.rs
@@ -14,16 +14,16 @@ use tokio::sync::RwLock;
#[cfg(feature = "stealth")]
use url::Url;
-#[cfg(feature = "stealth")]
-use crate::cookies::CookieJar;
#[cfg(feature = "stealth")]
use crate::client::{
- CallbackRegistry, InFlightGuard, ObscuraNetError, RequestInfo, RequestMode,
- ResourceRequest, Response, SsrfGuardResolver, cors_required, env_allows_private_network,
- fetch_file_url, is_forbidden_ip, redirect_taints_origin, request_fetch_site,
- request_referrer, response_too_large, serialized_request_origin, validate_cors_response,
- validate_request_mode, validate_url,
+ cors_required, env_allows_private_network, fetch_file_url, is_forbidden_ip,
+ redirect_taints_origin, request_fetch_site, request_referrer, response_too_large,
+ same_site_context, serialized_request_origin, validate_cors_response, validate_request_mode,
+ validate_url, CallbackRegistry, InFlightGuard, ObscuraNetError, RequestInfo, RequestMode,
+ ResourceRequest, Response, SsrfGuardResolver,
};
+#[cfg(feature = "stealth")]
+use crate::cookies::{CookieJar, SameSiteContext};
/// The wreq half of [`SsrfGuardResolver`]. `validate_url` only inspects the
/// host *string*, so on its own it lets a public name that resolves inward
@@ -346,7 +346,14 @@ impl StealthHttpClient {
let request_origin = serialized_request_origin(&request, redirect_tainted);
let cookie_header = if request.sends_credentials_to(&current_url) {
- self.cookie_jar.get_cookie_header(&current_url)
+ self.cookie_jar.get_cookie_header_in_context(
+ &current_url,
+ same_site_context(
+ &request,
+ &current_url,
+ request.mode == crate::RequestMode::Navigate,
+ ),
+ )
} else {
String::new()
};
@@ -463,6 +470,28 @@ impl StealthHttpClient {
body: &[u8],
send_cookies: bool,
store_cookies: bool,
+ ) -> Result<Response, ObscuraNetError> {
+ self.send_single_with_context(
+ method,
+ url,
+ headers,
+ body,
+ send_cookies.then_some(SameSiteContext::SameSite),
+ store_cookies,
+ )
+ .await
+ }
+
+ /// One request with an explicit cookie site context. Scripted fetch/XHR
+ /// uses this so Strict and Lax cookies cannot leak cross-site.
+ pub async fn send_single_with_context(
+ &self,
+ method: &str,
+ url: &Url,
+ headers: &HashMap<String, String>,
+ body: &[u8],
+ cookie_context: Option<SameSiteContext>,
+ store_cookies: bool,
) -> Result<Response, ObscuraNetError> {
if is_tracker_blocked(url, self.block_trackers) {
tracing::debug!("Blocked tracker: {}", url);
@@ -480,8 +509,8 @@ impl StealthHttpClient {
.map_err(|e| ObscuraNetError::Network(format!("invalid method '{}': {}", method, e)))?;
let mut req = self.client.request(req_method, url.as_str());
- if send_cookies {
- let cookie_header = self.cookie_jar.get_cookie_header(url);
+ if let Some(context) = cookie_context {
+ let cookie_header = self.cookie_jar.get_cookie_header_in_context(url, context);
if !cookie_header.is_empty() {
req = req.header("cookie", &cookie_header);
}
@@ -813,7 +842,7 @@ mod tests {
#[tokio::test]
async fn stealth_client_decodes_gzip_response() {
let port = gzip_fixture().await;
- let client = StealthHttpClient::new(Arc::new(CookieJar::new()));
+ let client = StealthHttpClient::with_proxy(Arc::new(CookieJar::new()), None, true);
let url = Url::parse(&format!("http://127.0.0.1:{port}/")).unwrap();
let resp = client.fetch(&url).await.expect("fixture must be reachable");
diff --git a/crates/obscura-render/src/dom.rs b/crates/obscura-render/src/dom.rs
index cc9da6e9..6030faf7 100644
--- a/crates/obscura-render/src/dom.rs
+++ b/crates/obscura-render/src/dom.rs
@@ -2566,7 +2566,7 @@ fn cascade_node_style(
tree: &DomTree,
id: NodeId,
sheet: &crate::css::Stylesheet,
- document_sheet: &crate::css::Stylesheet,
+ _document_sheet: &crate::css::Stylesheet,
shadow_sheets: &HashMap<NodeId, std::sync::Arc<crate::css::Stylesheet>>,
matcher: &mut obscura_dom::selector::Matcher,
styles: &mut HashMap<NodeId, crate::LayoutStyle>,
@@ -4348,6 +4348,7 @@ fn collect_shadow_stylesheets(
viewport: (f32, f32),
media_type: crate::CssMediaType,
) -> HashMap<NodeId, std::sync::Arc<crate::css::Stylesheet>> {
+ let external = tree.external_stylesheets();
let mut roots = Vec::new();
let mut stack = vec![tree.document()];
let mut visited = HashSet::new();
@@ -4365,24 +4366,35 @@ fn collect_shadow_stylesheets(
roots
.into_iter()
.map(|root| {
- let sources = tree
- .descendants(root)
- .into_iter()
- .filter_map(|node_id| {
- let node = tree.get_node(node_id)?;
- let element = node.as_element()?;
- (element.local.as_ref() == "style"
- && node.get_attribute("media").is_none_or(|media| {
- media.trim().is_empty()
- || crate::css::media_query_applies_for_viewport_and_type(
- media,
- viewport,
- media_type,
- )
- }))
- .then(|| tree.text_content(node_id))
- })
- .collect::<Vec<_>>();
+ let mut sources = Vec::new();
+ for node_id in tree.descendants(root) {
+ let Some(node) = tree.get_node(node_id) else {
+ continue;
+ };
+ let Some(element) = node.as_element() else {
+ continue;
+ };
+ let media_applies = node.get_attribute("media").is_none_or(|media| {
+ media.trim().is_empty()
+ || crate::css::media_query_applies_for_viewport_and_type(
+ media, viewport, media_type,
+ )
+ });
+ let linked = element.local.as_ref() == "link"
+ && node.get_attribute("disabled").is_none()
+ && node.get_attribute("rel").is_some_and(|rel| {
+ rel.split_ascii_whitespace()
+ .any(|part| part.eq_ignore_ascii_case("stylesheet"))
+ });
+ if media_applies && (linked || element.local.as_ref() == "style") {
+ if let Some(sheet) = external.get(&node_id) {
+ sources.extend(sheet.sources.iter().map(ToString::to_string));
+ }
+ }
+ if media_applies && element.local.as_ref() == "style" {
+ sources.push(tree.text_content(node_id));
+ }
+ }
let sheet = crate::css::Stylesheet::parse_for_viewport_and_media(
tree,
&sources,
@@ -4409,21 +4421,31 @@ fn layout_dom_with_web_fonts_pass_limit_at_animation_time(
) -> (DomLayout, ContainerLayoutTelemetry) {
let timing = std::env::var("OBSCURA_RENDER_TIMING").is_ok();
- // Collect the text of every <style> block in document order.
+ // Collect inline and host-fetched author sheets in document order. Loaded
+ // cross-origin bytes remain outside the page-visible DOM.
+ let external = tree.external_stylesheets();
let mut css_sources = Vec::new();
for nid in tree.descendants(tree.document()) {
if let Some(node) = tree.get_node(nid) {
if let Some(elem) = node.as_element() {
- if elem.local.as_ref() == "style"
- && node.get_attribute("media").is_none_or(|media| {
- media.trim().is_empty()
- || crate::css::media_query_applies_for_viewport_and_type(
- media,
- viewport,
- media_type,
- )
- })
- {
+ let media_applies = node.get_attribute("media").is_none_or(|media| {
+ media.trim().is_empty()
+ || crate::css::media_query_applies_for_viewport_and_type(
+ media, viewport, media_type,
+ )
+ });
+ let linked = elem.local.as_ref() == "link"
+ && node.get_attribute("disabled").is_none()
+ && node.get_attribute("rel").is_some_and(|rel| {
+ rel.split_ascii_whitespace()
+ .any(|part| part.eq_ignore_ascii_case("stylesheet"))
+ });
+ if media_applies && (linked || elem.local.as_ref() == "style") {
+ if let Some(sheet) = external.get(&nid) {
+ css_sources.extend(sheet.sources.iter().map(ToString::to_string));
+ }
+ }
+ if media_applies && elem.local.as_ref() == "style" {
css_sources.push(tree.text_content(nid));
}
}
@@ -14837,6 +14859,28 @@ mod tests {
root
}
+ #[test]
+ fn host_fetched_stylesheet_cascades_without_a_visible_style_node() {
+ let tree = parse_html(
+ r#"<html><head><link rel="stylesheet" href="https://cdn.test/app.css"></head><body><div id="target"></div></body></html>"#,
+ );
+ let link = tree
+ .query_selector("link")
+ .expect("valid selector")
+ .expect("stylesheet link");
+ assert!(tree.replace_external_stylesheet(
+ link,
+ "#target{width:37px;height:19px}".to_string(),
+ false,
+ ));
+
+ let laid = layout_dom(&tree, (200.0, 100.0));
+ let target = tree.get_element_by_id("target").expect("target");
+ assert_eq!(laid.rects[&target].width, 37.0);
+ assert_eq!(laid.rects[&target].height, 19.0);
+ assert!(tree.query_selector_all("style").unwrap().is_empty());
+ }
+
#[test]
fn shadow_rendered_children_distribute_named_and_default_slots() {
let tree = parse_html(
diff --git a/crates/obscura-render/src/style.rs b/crates/obscura-render/src/style.rs
index 37c7ba08..eb59f970 100644
--- a/crates/obscura-render/src/style.rs
+++ b/crates/obscura-render/src/style.rs
@@ -6383,7 +6383,32 @@ struct LengthContext {
percent_base: f32,
}
+// CSS math functions recurse through nested calc()/min()/max()/clamp()
+// expressions. Real stylesheets stay shallow; bounding the nesting prevents a
+// hostile declaration from exhausting the native stack before it is rejected.
+const MAX_CSS_MATH_NESTING: usize = 64;
+
+fn css_math_nesting_is_safe(value: &str) -> bool {
+ let mut depth = 0usize;
+ for character in value.chars() {
+ match character {
+ '(' => {
+ depth += 1;
+ if depth > MAX_CSS_MATH_NESTING {
+ return false;
+ }
+ }
+ ')' => depth = depth.saturating_sub(1),
+ _ => {}
+ }
+ }
+ true
+}
+
fn resolve_contextual(value: &str, context: &LengthContext) -> Option<f32> {
+ if !css_math_nesting_is_safe(value) {
+ return None;
+ }
let value = value.trim();
if let Some(rest) = value.strip_prefix('(') {
let end = find_matching_paren(rest)?;
@@ -6607,6 +6632,9 @@ fn eval_contextual_product(term: &str, context: &LengthContext) -> Option<f32> {
/// example from Wikipedia's icon sizing), so each case recurses back into
/// this function rather than assuming a flat expression.
fn resolve_length(value: &str) -> Option<f32> {
+ if !css_math_nesting_is_safe(value) {
+ return None;
+ }
let v = value.trim();
if let Some(rest) = v.strip_prefix('(') {
let end = find_matching_paren(rest)?;
@@ -10823,6 +10851,26 @@ mod tests {
assert_eq!(resolve_length(expr), Some(20.0));
}
+ #[test]
+ fn deeply_nested_css_math_is_rejected_without_recursing() {
+ let mut expression = "1px".to_string();
+ for _ in 0..5_000 {
+ expression = format!("calc({expression})");
+ }
+
+ assert_eq!(resolve_length(&expression), None);
+ assert_eq!(
+ resolve_contextual_length(&expression, 16.0, 16.0, 10.0, 10.0, 100.0),
+ None
+ );
+
+ let mut ordinary = "1px".to_string();
+ for _ in 0..8 {
+ ordinary = format!("calc({ordinary})");
+ }
+ assert_eq!(resolve_length(&ordinary), Some(1.0));
+ }
+
#[test]
fn width_property_resolves_calc_with_var() {
let s = compute_style("div", Some("width: calc(var(--x, 10px) + 5px)"));
diff --git a/crates/obscura/src/cookie.rs b/crates/obscura/src/cookie.rs
index 04c65a4a..3b80ff86 100644
--- a/crates/obscura/src/cookie.rs
+++ b/crates/obscura/src/cookie.rs
@@ -66,7 +66,7 @@ impl CookieStore {
pub fn get_for_url(&self, url: &str) -> Result<Vec<Cookie>, crate::error::Error> {
let parsed = url::Url::parse(url)
.map_err(|e| crate::error::Error::Internal(e.into()))?;
- let header = self.jar.get_cookie_header(&parsed);
+ let header = self.jar.get_cookie_header_same_site(&parsed);
Ok(header
.split("; ")
.filter(|s| !s.is_empty())
diff --git a/docs/CLI-reference.md b/docs/CLI-reference.md
index 31fe850b..ba92a230 100644
--- a/docs/CLI-reference.md
+++ b/docs/CLI-reference.md
@@ -121,7 +121,7 @@ Run obscura as an MCP server.
-v, --verbose Enable info logging
```
-`--host` only applies with `--http`. The default `127.0.0.1` keeps the server loopback-only; set `0.0.0.0` to bind all interfaces (for example a Docker Compose sidecar) and pair it with `OBSCURA_MCP_ALLOWED_ORIGINS`.
+`--host` only applies with `--http`. The default `127.0.0.1` keeps the server loopback-only. A non-loopback bind requires `OBSCURA_MCP_TOKEN` (at least 32 bytes); use `OBSCURA_MCP_ALLOWED_ORIGINS` as well when a browser-based client needs access.
Default transport is stdio. See [Use the MCP server](Use-the-MCP-server.md).
diff --git a/docs/Environment-variables.md b/docs/Environment-variables.md
index 2f957bca..5780dd38 100644
--- a/docs/Environment-variables.md
+++ b/docs/Environment-variables.md
@@ -60,6 +60,16 @@ Per-command deadline for the CDP server. A hung page (a runaway `Runtime.evaluat
OBSCURA_CDP_COMMAND_TIMEOUT_MS=30000 obscura serve
```
+### `OBSCURA_CDP_TOKEN`
+
+Bearer token for the CDP discovery and WebSocket endpoints. It is optional on
+loopback. A non-loopback bind is refused unless this is set to at least 32
+bytes. Pass it as `Authorization: Bearer <token>` in the CDP client's headers.
+
+```bash
+OBSCURA_CDP_TOKEN="$(openssl rand -hex 32)" obscura serve --host 0.0.0.0
+```
+
### `OBSCURA_FETCH_TIMEOUT_MS`
Request timeout for scripted `fetch()`, `XMLHttpRequest`, and ES-module loads. Without it a request to a server that accepts the connection but never responds (including a CORS preflight) hangs forever and the XHR is stuck with no completion event. Default 30000 (30 seconds).
@@ -131,12 +141,21 @@ OBSCURA_ROTATE_PROFILE=1 obscura serve
### `OBSCURA_MCP_ALLOWED_ORIGINS`
-Comma-separated `Origin` allowlist for the HTTP MCP transport (`obscura mcp --http`). Off by default, which keeps the permissive behavior. When set, a browser request whose `Origin` is not listed is refused with `403` before it can drive the server; native, non-browser MCP clients (which send no `Origin`) are always allowed. Use it to stop cross-origin pages from reaching a loopback MCP port.
+Comma-separated `Origin` allowlist for the HTTP MCP transport (`obscura mcp --http`). Browser requests are refused by default; when set, only listed origins are accepted. Native, non-browser MCP clients (which send no `Origin`) are always allowed.
```bash
OBSCURA_MCP_ALLOWED_ORIGINS="https://app.example.com" obscura mcp --http --host 0.0.0.0
```
+### `OBSCURA_MCP_TOKEN`
+
+Bearer token for MCP HTTP requests. It is optional on loopback. A non-loopback
+bind is refused unless this is set to at least 32 bytes.
+
+```bash
+OBSCURA_MCP_TOKEN="$(openssl rand -hex 32)" obscura mcp --http --host 0.0.0.0
+```
+
## Logging
### `RUST_LOG`
diff --git a/docs/Run-in-production-at-scale.md b/docs/Run-in-production-at-scale.md
index 5ffd3cbe..1207961d 100644
--- a/docs/Run-in-production-at-scale.md
+++ b/docs/Run-in-production-at-scale.md
@@ -9,6 +9,7 @@ docker run -d \
--name obscura \
--restart unless-stopped \
-p 127.0.0.1:9222:9222 \
+ -e OBSCURA_CDP_TOKEN="$(openssl rand -hex 32)" \
-v /srv/obscura/data:/data \
h4ckf0r0day/obscura \
serve --host 0.0.0.0 --storage-dir /data --stealth
@@ -44,9 +45,8 @@ required for the published port to work at all. Publish to **host loopback**
exposes the port on every host interface, and Docker's iptables rules bypass
most host firewalls.
-The CDP control plane has no authentication of its own: anything that can reach
-the port can drive the browser. See [Authentication](#authentication) for the
-controls that actually gate it.
+The container bind requires `OBSCURA_CDP_TOKEN`. Send it as a bearer token from
+the CDP client and still publish the port to host loopback where possible.
## Systemd
@@ -148,24 +148,26 @@ CDP needs WebSocket upgrade and long read timeouts.
## Authentication
-Obscura's CDP server has no built-in auth. Anyone who can reach the port can drive the browser. Options:
+Obscura requires `OBSCURA_CDP_TOKEN` (at least 32 bytes) for every non-loopback
+CDP bind. Pass it in the client's `Authorization` header. Also:
- Bind to `127.0.0.1` and require SSH for access (default).
-- Put it behind a reverse proxy that enforces auth.
+- Put it behind a reverse proxy that enforces an additional auth boundary.
- Use Docker network isolation.
Never bind `0.0.0.0` on a public IP without one of the above.
## MCP HTTP transport
-`obscura mcp --http` binds `127.0.0.1` by default. To reach it from another container, bind with `--host 0.0.0.0` and set an `Origin` allowlist so a browser page cannot drive it cross-origin:
+`obscura mcp --http` binds `127.0.0.1` by default. A non-loopback bind requires a bearer token. Browser origins are denied by default; set an allowlist only when a browser-based MCP client needs access:
```bash
+OBSCURA_MCP_TOKEN="$(openssl rand -hex 32)" \
OBSCURA_MCP_ALLOWED_ORIGINS="https://app.example.com" \
obscura mcp --http --host 0.0.0.0 --port 3000
```
-Request bodies are capped at 16 MiB. Like the CDP server it has no built-in auth, so keep it on an internal network or behind an authenticating proxy. See [Use the MCP server](Use-the-MCP-server.md).
+Request bodies and headers, batch size, pending requests, and connections are bounded. Keep the service on an internal network even with authentication. See [Use the MCP server](Use-the-MCP-server.md).
## Observability
diff --git a/docs/Use-the-MCP-server.md b/docs/Use-the-MCP-server.md
index bf2f8631..5cd0a6da 100644
--- a/docs/Use-the-MCP-server.md
+++ b/docs/Use-the-MCP-server.md
@@ -28,17 +28,18 @@ obscura mcp --stealth --proxy http://proxy.example.com:8080
## Security
-The HTTP transport has no built-in auth, so anyone who can reach the port can drive the browser. Two guards ship for the HTTP transport:
+The HTTP transport exposes a privileged browser session. Its guards are:
-- **Origin allowlist.** Set `OBSCURA_MCP_ALLOWED_ORIGINS` to a comma-separated list of allowed `Origin` values. When set, a browser request from an unlisted origin is refused with `403` before it can drive the server, which blocks a malicious page from POSTing to a loopback MCP port. Native, non-browser clients send no `Origin` and are always allowed. Unset (the default) keeps the permissive behavior.
-- **Body cap.** A single request body is capped at 16 MiB, so an unauthenticated caller cannot force a large allocation with an oversized `Content-Length`.
+- **Bearer authentication.** Set `OBSCURA_MCP_TOKEN` and send it in the `Authorization: Bearer ...` header. A non-loopback bind is refused without a token of at least 32 bytes.
+- **Origin allowlist.** Browser requests are refused by default. Set `OBSCURA_MCP_ALLOWED_ORIGINS` to permit specific browser origins. Native clients send no `Origin` and are unaffected.
+- **Resource bounds.** Request bodies, headers, JSON-RPC batches, pending work, and live connections are bounded.
```bash
-OBSCURA_MCP_ALLOWED_ORIGINS="https://app.example.com" obscura mcp --http --host 0.0.0.0
+OBSCURA_MCP_TOKEN="$(openssl rand -hex 32)" \
+OBSCURA_MCP_ALLOWED_ORIGINS="https://app.example.com" \
+ obscura mcp --http --host 0.0.0.0
```
-When you expose the HTTP transport beyond loopback, set the allowlist and put it behind a reverse proxy or network isolation that enforces auth.
-
## Tools exposed
The server keeps a live browser session, so tools operate on the current page rather than taking a URL each call. Navigate first, then read or act.