Skip to content

The headless browser for AI agents and web scraping

fix(js): keep Web Storage across navigation and persist it, and back IndexedDB

opencodef661c2e0f687
diff --git a/crates/obscura-browser/Cargo.toml b/crates/obscura-browser/Cargo.toml
index 20d48286..05bf7429 100644
--- a/crates/obscura-browser/Cargo.toml
+++ b/crates/obscura-browser/Cargo.toml
@@ -20,6 +20,7 @@ url = { workspace = true }
tracing = { workspace = true }
thiserror = { workspace = true }
anyhow = { workspace = true }
+serde = { workspace = true }
serde_json = { workspace = true }
base64 = { workspace = true }
image = { version = "0.25", default-features = false, features = ["jpeg", "png"], optional = true }
diff --git a/crates/obscura-browser/src/context.rs b/crates/obscura-browser/src/context.rs
index 7b5139aa..96cadf97 100644
--- a/crates/obscura-browser/src/context.rs
+++ b/crates/obscura-browser/src/context.rs
@@ -1,11 +1,19 @@
use std::path::PathBuf;
use std::sync::Arc;
+use obscura_js::ops::{IndexedDbStorage, OriginStorage};
use obscura_net::{CookieJar, ObscuraHttpClient, RobotsCache};
pub struct BrowserContext {
pub id: String,
pub cookie_jar: Arc<CookieJar>,
+ /// `localStorage` backing store, keyed by origin. Owned by the context
+ /// rather than by a V8 realm, so an entry written in one document is still
+ /// there in the next (issue #678).
+ pub local_storage: Arc<OriginStorage>,
+ /// IndexedDB records and schema, keyed by origin. Owned by the context, so
+ /// a page reload or a second tab sees the same databases.
+ pub indexed_db: Arc<IndexedDbStorage>,
pub http_client: Arc<ObscuraHttpClient>,
pub user_agent: String,
pub platform: String,
@@ -33,6 +41,61 @@ pub struct BrowserContext {
pub allow_private_network: bool,
}
+/// One origin's persisted `localStorage`. The origin is inside the file, so the
+/// file name only has to be unique and stable, not reversible.
+#[derive(serde::Serialize, serde::Deserialize)]
+struct StoredOriginStorage {
+ origin: String,
+ /// `[key, value]` pairs in insertion order, the order `Storage.key(i)` uses.
+ entries: Vec<(String, String)>,
+}
+
+/// Filename-safe stem for an origin: a sanitized prefix for readability plus the
+/// full FNV-1a digest of the origin, so `https://a-b.example` and
+/// `https://a_b.example` cannot share a file.
+fn storage_file_stem(origin: &str) -> String {
+ let prefix: String = origin
+ .chars()
+ .take(48)
+ .map(|c| if c.is_ascii_alphanumeric() || c == '.' { c } else { '_' })
+ .collect();
+ let mut digest: u64 = 0xcbf2_9ce4_8422_2325;
+ for byte in origin.as_bytes() {
+ digest ^= u64::from(*byte);
+ digest = digest.wrapping_mul(0x0000_0100_0000_01b3);
+ }
+ format!("{prefix}-{digest:016x}")
+}
+
+/// Write through a temporary file so an interrupted write cannot leave a
+/// half-written profile behind.
+fn write_file_atomically(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> {
+ let tmp = path.with_extension("json.tmp");
+ std::fs::write(&tmp, bytes)?;
+ std::fs::rename(&tmp, path)
+}
+
+/// Restore `{storage_dir}/localStorage/*.json` into a fresh store.
+fn load_web_storage(storage: &OriginStorage, dir: Option<&PathBuf>) {
+ let Some(dir) = dir else { return };
+ let root = dir.join("localStorage");
+ let Ok(read_dir) = std::fs::read_dir(&root) else { return };
+ for entry in read_dir.flatten() {
+ let path = entry.path();
+ if path.extension().and_then(|ext| ext.to_str()) != Some("json") {
+ continue;
+ }
+ let Ok(contents) = std::fs::read_to_string(&path) else {
+ tracing::warn!("Failed to read {}", path.display());
+ continue;
+ };
+ match serde_json::from_str::<StoredOriginStorage>(&contents) {
+ Ok(stored) => storage.load(&stored.origin, stored.entries),
+ Err(e) => tracing::warn!("Ignoring unreadable {}: {}", path.display(), e),
+ }
+ }
+}
+
impl BrowserContext {
pub fn new(id: String) -> Self {
Self::_new_inner(id, None, false, None, None, false)
@@ -119,9 +182,16 @@ impl BrowserContext {
*guard = resolved_ua.clone();
}
let http_client = Arc::new(client);
+ let local_storage = Arc::new(OriginStorage::default());
+ if let Some(ref dir) = storage_dir {
+ load_web_storage(&local_storage, Some(dir));
+ }
+
BrowserContext {
id,
cookie_jar,
+ local_storage,
+ indexed_db: Arc::new(IndexedDbStorage::default()),
http_client,
user_agent: resolved_ua,
platform,
@@ -179,6 +249,19 @@ impl BrowserContext {
BrowserContext {
id,
cookie_jar,
+ // localStorage belongs to the profile, so a persistent copy shares
+ // the template's store instead of snapshotting it: two contexts on
+ // one --storage-dir would otherwise overwrite each other's origins.
+ local_storage: if persistent {
+ self.local_storage.clone()
+ } else {
+ Arc::new(OriginStorage::default())
+ },
+ indexed_db: if persistent {
+ self.indexed_db.clone()
+ } else {
+ Arc::new(IndexedDbStorage::default())
+ },
http_client: Arc::new(client),
user_agent: self.user_agent.clone(),
platform: self.platform.clone(),
@@ -194,6 +277,54 @@ impl BrowserContext {
}
}
+ /// Flush `localStorage` to `{storage_dir}/localStorage`. Only the origins
+ /// that changed since the last successful write are touched, and an origin
+ /// that lost its last entry has its file removed so a restart cannot
+ /// resurrect it. The store is only marked clean once every touched origin
+ /// reached the disk, so a failed write is retried instead of lost.
+ pub fn save_local_storage(&self) {
+ let Some(ref dir) = self.storage_dir else {
+ return;
+ };
+ if !self.local_storage.is_dirty() {
+ return;
+ }
+ let changed = self.local_storage.changed_origins();
+ let root = dir.join("localStorage");
+ if let Err(e) = std::fs::create_dir_all(&root) {
+ tracing::warn!("Failed to create {}: {}", root.display(), e);
+ return;
+ }
+ for origin in &changed {
+ let path = root.join(format!("{}.json", storage_file_stem(origin)));
+ let entries = self.local_storage.snapshot(origin);
+ if entries.is_empty() {
+ match std::fs::remove_file(&path) {
+ Ok(()) => {}
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
+ Err(e) => tracing::warn!("Failed to remove {}: {}", path.display(), e),
+ }
+ continue;
+ }
+ let stored = StoredOriginStorage { origin: origin.clone(), entries };
+ match serde_json::to_string(&stored) {
+ Ok(payload) => {
+ if let Err(e) = write_file_atomically(&path, payload.as_bytes()) {
+ tracing::warn!("Failed to save {}: {}", path.display(), e);
+ }
+ }
+ Err(e) => tracing::warn!("Failed to encode localStorage: {}", e),
+ }
+ }
+ self.local_storage.take_changed();
+ }
+
+ /// Persist cookies and Web Storage if storage_dir is configured.
+ pub fn save_storage(&self) {
+ self.save_local_storage();
+ self.save_cookies();
+ }
+
/// Persist cookies to disk if storage_dir is configured.
/// Called during graceful shutdown.
pub fn save_cookies(&self) {
@@ -246,6 +377,141 @@ mod tests {
assert!(ctx.user_agent.contains("Chrome"));
}
+ fn temp_storage_dir(name: &str) -> PathBuf {
+ let dir = std::env::temp_dir().join(format!(
+ "obscura-storage-{name}-{}",
+ std::process::id()
+ ));
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(&dir).unwrap();
+ dir
+ }
+
+ /// --storage-dir has to survive a restart, which is the whole point of a
+ /// profile: a second context over the same directory reads back what the
+ /// first one wrote.
+ #[test]
+ fn local_storage_round_trips_through_the_storage_dir() {
+ let dir = temp_storage_dir("roundtrip");
+ let first = BrowserContext::with_storage("profile-a".into(), Some(dir.clone()));
+ first.local_storage.set("https://app.example", "token".into(), "abc".into());
+ first.local_storage.set("https://app.example", "theme".into(), "dark".into());
+ first.local_storage.set("https://other.example", "k".into(), "v".into());
+ first.save_local_storage();
+
+ let files: Vec<String> = std::fs::read_dir(dir.join("localStorage"))
+ .unwrap()
+ .flatten()
+ .map(|entry| entry.file_name().to_string_lossy().to_string())
+ .collect();
+ assert_eq!(files.len(), 2, "one file per origin: {files:?}");
+
+ let second = BrowserContext::with_storage("profile-b".into(), Some(dir.clone()));
+ assert_eq!(
+ second.local_storage.get("https://app.example", "token"),
+ Some("abc".to_string())
+ );
+ assert_eq!(
+ second.local_storage.get("https://app.example", "theme"),
+ Some("dark".to_string())
+ );
+ assert_eq!(
+ second.local_storage.get("https://other.example", "k"),
+ Some("v".to_string())
+ );
+ // Insertion order is part of the format: Storage.key(i) depends on it.
+ let keys: Vec<String> = second
+ .local_storage
+ .snapshot("https://app.example")
+ .into_iter()
+ .map(|(key, _)| key)
+ .collect();
+ assert_eq!(keys, vec!["token".to_string(), "theme".to_string()]);
+
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
+ /// Without --storage-dir nothing is written and nothing is loaded, and the
+ /// incognito copy of a persistent context stays empty.
+ #[test]
+ fn local_storage_stays_in_memory_without_a_storage_dir() {
+ let persistent = BrowserContext::with_storage("no-dir".into(), None);
+ assert!(persistent.storage_dir.is_none());
+ persistent.local_storage.set("https://app.example", "k".into(), "v".into());
+ persistent.save_local_storage();
+ // No directory is configured, so the write is a no-op and the entry
+ // stays in this process only.
+ assert!(persistent.local_storage.is_dirty());
+ assert_eq!(
+ persistent.local_storage.get("https://app.example", "k"),
+ Some("v".to_string())
+ );
+
+ let incognito = persistent.isolated_copy("incognito".into(), false);
+ assert_eq!(incognito.local_storage.get("https://app.example", "k"), None);
+ // The template keeps its own entry.
+ assert_eq!(
+ persistent.local_storage.get("https://app.example", "k"),
+ Some("v".to_string())
+ );
+ }
+
+ /// An unchanged store must not touch the disk, or every navigation on a
+ /// large profile would rewrite every origin file.
+ #[test]
+ fn save_local_storage_skips_untouched_origins() {
+ let dir = temp_storage_dir("dirty");
+ let context = BrowserContext::with_storage("dirty-check".into(), Some(dir.clone()));
+ context.local_storage.set("https://app.example", "k".into(), "v".into());
+ context.save_local_storage();
+ let first_write = std::fs::metadata(
+ dir.join("localStorage").join(format!("{}.json", storage_file_stem("https://app.example"))),
+ )
+ .and_then(|meta| meta.modified())
+ .expect("the first write must land");
+ std::thread::sleep(std::time::Duration::from_millis(1100));
+ context.save_local_storage();
+ let second_write = std::fs::metadata(
+ dir.join("localStorage").join(format!("{}.json", storage_file_stem("https://app.example"))),
+ )
+ .and_then(|meta| meta.modified())
+ .expect("the file must still exist");
+ assert_eq!(
+ first_write, second_write,
+ "an unchanged store must not be rewritten"
+ );
+
+ // A write to one origin must leave another origin's file alone.
+ context.local_storage.set("https://other.example", "x".into(), "y".into());
+ context.save_local_storage();
+ let other_path = dir.join("localStorage").join(format!(
+ "{}.json",
+ storage_file_stem("https://other.example")
+ ));
+ let other_first = std::fs::metadata(&other_path).unwrap().modified().unwrap();
+ std::thread::sleep(std::time::Duration::from_millis(1100));
+ context.local_storage.set("https://app.example", "k2".into(), "v2".into());
+ context.save_local_storage();
+ let other_second = std::fs::metadata(&other_path).unwrap().modified().unwrap();
+ assert_eq!(other_first, other_second, "an untouched origin must not be rewritten");
+
+ // Clearing an origin removes its file instead of leaving it behind for
+ // the next load to resurrect.
+ context.local_storage.clear("https://other.example");
+ context.save_local_storage();
+ assert!(!other_path.exists(), "a cleared origin must not keep its file");
+ let after_clear =
+ BrowserContext::with_storage("dirty-check-3".into(), Some(dir.clone()));
+ assert_eq!(after_clear.local_storage.get("https://other.example", "x"), None);
+
+ let reloaded = BrowserContext::with_storage("dirty-check-2".into(), Some(dir.clone()));
+ assert_eq!(
+ reloaded.local_storage.get("https://app.example", "k2"),
+ Some("v2".to_string())
+ );
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
#[tokio::test(flavor = "current_thread")]
async fn isolated_copy_does_not_share_mutable_network_state() {
let source = BrowserContext::with_full_options(
diff --git a/crates/obscura-browser/src/page.rs b/crates/obscura-browser/src/page.rs
index fbdc129b..dfe988ce 100644
--- a/crates/obscura-browser/src/page.rs
+++ b/crates/obscura-browser/src/page.rs
@@ -3,7 +3,7 @@ use std::sync::Arc;
use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
use obscura_dom::{parse_html, DomTree};
use obscura_js::frame::FrameRealm;
-use obscura_js::ops::{max_live_frames, NavigationTiming};
+use obscura_js::ops::{OriginStorage, max_live_frames, NavigationTiming};
use obscura_js::runtime::ObscuraJsRuntime;
use obscura_net::{
CallbackRegistry, ObscuraHttpClient, ObscuraNetError, RequestCallback, ResourceRequest,
@@ -249,6 +249,11 @@ pub struct Page {
pub lifecycle: LifecycleState,
pub http_client: Arc<ObscuraHttpClient>,
pub context: Arc<BrowserContext>,
+ /// `sessionStorage` backing store, keyed by origin. Owned by the Page rather
+ /// than by the realm: `init_js` runs on every navigation and on CDP target
+ /// switching, but a session entry must survive both while never leaving the
+ /// tab (issue #678).
+ session_storage: Arc<OriginStorage>,
pub title: String,
/// Source document URL for the current document. This is deliberately
/// separate from `url`: direct automation navigations have no referrer,
@@ -1102,6 +1107,7 @@ impl Page {
lifecycle: LifecycleState::Idle,
http_client,
context,
+ session_storage: Arc::new(OriginStorage::default()),
title: String::new(),
referrer: String::new(),
viewport: (1280.0, 720.0),
@@ -1827,6 +1833,10 @@ impl Page {
);
rt.set_cookie_jar(self.context.cookie_jar.clone());
+ // Web Storage lives outside the realm so a navigation cannot drop it.
+ rt.set_local_storage(self.context.local_storage.clone());
+ rt.set_session_storage(self.session_storage.clone());
+ rt.set_indexed_db(self.context.indexed_db.clone());
rt.set_http_client(self.http_client.clone());
rt.set_callbacks(self.callbacks.clone());
rt.set_blocked_urls(self.blocked_url_patterns.clone());
@@ -3589,6 +3599,9 @@ impl Page {
// page.click() handlers were no-ops. Now scripts run regardless
// of waitUntil and DCL means "DOM parsed AND scripts executed".
self.execute_scripts().await;
+ // The document's own scripts are the common source of storage writes,
+ // so the profile is flushed once they have run, not before.
+ self.context.save_local_storage();
#[cfg(feature = "render")]
{
@@ -6497,6 +6510,160 @@ mod tests {
assert!(!script_response_is_executable(500));
}
+ /// Issue #678: `localStorage` belongs to the BrowserContext and
+ /// `sessionStorage` to the Page, so both survive the realm rebuild that
+ /// `init_js` performs on every navigation. The fixture serves one origin on
+ /// two paths plus a second origin, so a cross-origin hop is testable too.
+ async fn spawn_storage_server() -> (String, String) {
+ let first = "<html><body><script>window.__ran='YES';</script></body></html>";
+ async fn serve(listener: tokio::net::TcpListener, body: &'static str) {
+ while let Ok((mut socket, _)) = listener.accept().await {
+ let body = body.to_string();
+ tokio::spawn(async move {
+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
+ let mut buf = [0u8; 2048];
+ let _ = socket.read(&mut buf).await;
+ let resp = format!(
+ "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
+ body.len()
+ );
+ let _ = socket.write_all(resp.as_bytes()).await;
+ });
+ }
+ }
+ let listener_a = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr_a = listener_a.local_addr().unwrap();
+ let listener_b = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr_b = listener_b.local_addr().unwrap();
+ tokio::spawn(serve(listener_a, first));
+ tokio::spawn(serve(listener_b, first));
+ (format!("http://{addr_a}"), format!("http://{addr_b}"))
+ }
+
+ fn storage_page(name: &str, context: std::sync::Arc<crate::BrowserContext>) -> super::Page {
+ super::Page::new(name.to_string(), context)
+ }
+
+ #[tokio::test]
+ async fn web_storage_survives_navigation_and_is_scoped_per_origin() {
+ std::env::set_var("OBSCURA_ALLOW_PRIVATE_NETWORK", "1");
+ let (origin_a, origin_b) = spawn_storage_server().await;
+ let context = std::sync::Arc::new(crate::BrowserContext::with_storage_and_network(
+ "storage-regression".into(),
+ None,
+ false,
+ None,
+ None,
+ true,
+ ));
+ let mut page = storage_page("storage-regression", context.clone());
+
+ page.navigate(&origin_a).await.unwrap();
+ page.evaluate(
+ r#"(() => {
+ localStorage.setItem('l1', 'local-value');
+ sessionStorage.setItem('s1', 'session-value');
+ return 'seeded';
+ })()"#,
+ );
+
+ // Same origin, different path: a new document, and therefore a new realm.
+ page.navigate(&format!("{origin_a}/second")).await.unwrap();
+ let after = page
+ .evaluate(
+ r#"({
+ local: localStorage.getItem('l1'),
+ session: sessionStorage.getItem('s1'),
+ length: localStorage.length,
+ viaProperty: localStorage.l1,
+ has: 'l1' in localStorage,
+ keys: Object.keys(localStorage),
+ })"#,
+ );
+ assert_eq!(
+ after.get("local").and_then(|v| v.as_str()),
+ Some("local-value"),
+ "localStorage must survive a same-origin navigation: {after:?}"
+ );
+ assert_eq!(
+ after.get("session").and_then(|v| v.as_str()),
+ Some("session-value"),
+ "sessionStorage must survive a same-origin navigation in the same tab: {after:?}"
+ );
+ // The Proxy surface has to agree with the methods now that the data
+ // lives in Rust: property access, `in`, key enumeration and length.
+ assert_eq!(after.get("viaProperty").and_then(|v| v.as_str()), Some("local-value"));
+ assert_eq!(after.get("has").and_then(|v| v.as_bool()), Some(true));
+ assert_eq!(after.get("length").and_then(|v| v.as_u64()), Some(1));
+ assert_eq!(
+ after.get("keys").and_then(|v| v.as_array()).map(|k| k.len()),
+ Some(1)
+ );
+
+ // Another origin gets an empty store of its own: no cross-origin leak.
+ page.navigate(&origin_b).await.unwrap();
+ let other = page
+ .evaluate(
+ r#"({
+ local: localStorage.getItem('l1'),
+ session: sessionStorage.getItem('s1'),
+ })"#,
+ );
+ assert!(
+ other["local"].is_null() && other["session"].is_null(),
+ "a different origin must not see this origin's storage: {other:?}"
+ );
+
+ // Coming back, the original origin's data is still there.
+ page.navigate(&origin_a).await.unwrap();
+ let back = page.evaluate("localStorage.getItem('l1')");
+ assert_eq!(back.as_str(), Some("local-value"));
+ }
+
+ #[tokio::test]
+ async fn session_storage_stays_inside_the_tab_and_local_storage_is_shared() {
+ std::env::set_var("OBSCURA_ALLOW_PRIVATE_NETWORK", "1");
+ let (origin, _) = spawn_storage_server().await;
+ let context = std::sync::Arc::new(crate::BrowserContext::with_storage_and_network(
+ "storage-scope".into(),
+ None,
+ false,
+ None,
+ None,
+ true,
+ ));
+ let mut first = storage_page("storage-scope-1", context.clone());
+ first.navigate(&origin).await.unwrap();
+ first.evaluate(
+ r#"(() => {
+ localStorage.setItem('shared', 'from-tab-one');
+ sessionStorage.setItem('tab', 'from-tab-one');
+ return 'ok';
+ })()"#,
+ );
+
+ // A second page of the same context shares localStorage but not
+ // sessionStorage, which is the split the storage bug got wrong.
+ let mut second = storage_page("storage-scope-2", context.clone());
+ second.navigate(&origin).await.unwrap();
+ let view = second
+ .evaluate(
+ r#"({
+ local: localStorage.getItem('shared'),
+ session: sessionStorage.getItem('tab'),
+ })"#,
+ );
+ assert_eq!(
+ view.get("local").and_then(|v| v.as_str()),
+ Some("from-tab-one"),
+ "localStorage is scoped to the BrowserContext: {view:?}"
+ );
+ assert!(
+ view.get("session") == Some(&serde_json::Value::Null),
+ "sessionStorage must not cross tabs: {view:?}"
+ );
+ }
+
/// `/` puts its iframe inside a closed shadow root, `/plain.html` puts the
/// same iframe straight in the document, and `/child.html` is the frame.
async fn spawn_shadow_frame_server() -> String {
diff --git a/crates/obscura-cdp/src/server.rs b/crates/obscura-cdp/src/server.rs
index b3fc7dfd..13cf6397 100644
--- a/crates/obscura-cdp/src/server.rs
+++ b/crates/obscura-cdp/src/server.rs
@@ -653,7 +653,7 @@ pub async fn start_with_serve_options_limit_and_ready_file(
}
tokio::time::sleep(tokio::time::Duration::from_millis(20)).await;
}
- persistence_ctx.save_cookies();
+ persistence_ctx.save_storage();
Ok(())
}
@@ -887,7 +887,7 @@ fn run_connection(
&initial_cookies,
&persisted_context.cookie_jar.get_all_cookies(),
);
- persistence_context.save_cookies();
+ persistence_context.save_storage();
}
drop(persisted_context);
diff --git a/crates/obscura-cli/src/main.rs b/crates/obscura-cli/src/main.rs
index e0522bc3..8c43d6ef 100644
--- a/crates/obscura-cli/src/main.rs
+++ b/crates/obscura-cli/src/main.rs
@@ -411,6 +411,7 @@ async fn run_cli() -> anyhow::Result<()> {
}
let global_proxy = args.proxy.clone();
+ let global_storage_dir = args.storage_dir.clone();
let stealth = args.stealth;
let obey_robots = args.obey_robots;
@@ -594,6 +595,14 @@ async fn run_cli() -> anyhow::Result<()> {
user_agent,
}) => {
let mcp_proxy = merge_proxy(global_proxy.clone(), proxy);
+ // `obscura mcp` builds its BrowserContext from the environment, so
+ // the global profile flag has to be handed over explicitly.
+ if let Some(ref dir) = global_storage_dir {
+ // SAFETY: single threaded here, before the MCP server starts.
+ unsafe {
+ std::env::set_var("OBSCURA_STORAGE_DIR", dir);
+ }
+ }
if http {
obscura_mcp::http::run(host, port, mcp_proxy, user_agent, stealth).await?;
} else {
@@ -1160,7 +1169,7 @@ async fn run_fetch(
other => other.to_string(),
};
write_or_print(rendered, output.as_ref()).await?;
- context.save_cookies();
+ context.save_storage();
return Ok(());
}
if screenshot.is_some() {
@@ -1334,7 +1343,7 @@ async fn run_fetch(
std::fs::metadata(path).map(|m| m.len()).unwrap_or(0)
);
}
- context.save_cookies();
+ context.save_storage();
return Ok(());
}
#[cfg(not(feature = "render"))]
@@ -1359,7 +1368,7 @@ async fn run_fetch(
write_or_print(rendered, output.as_ref()).await?;
// Save cookies to disk if storage_dir is configured
- context.save_cookies();
+ context.save_storage();
Ok(())
}
diff --git a/crates/obscura-js/js/bootstrap.js b/crates/obscura-js/js/bootstrap.js
index be457daf..7ab5cc7e 100644
--- a/crates/obscura-js/js/bootstrap.js
+++ b/crates/obscura-js/js/bootstrap.js
@@ -12152,35 +12152,83 @@ globalThis.reportError = globalThis.reportError || ((e) => console.error(e));
// WHATWG Storage as a legacy platform object: a Proxy routes property access
// (localStorage.foo, localStorage["foo"], delete, `in`, Object.keys) through
// the named getter/setter so length/key()/iteration stay in sync with the
-// backing map. Plain prototype methods alone could not intercept direct
+// backing store. Plain prototype methods alone could not intercept direct
// property access, so `localStorage.foo = x` never updated length before.
+// The store itself is Rust, keyed by origin, so it outlives the realm.
globalThis.Storage = function Storage() {};
-Storage.prototype.getItem = function(k) { k = String(k); return Object.prototype.hasOwnProperty.call(this._data, k) ? this._data[k] : null; };
-Storage.prototype.setItem = function(k, v) { this._data[String(k)] = String(v); };
-Storage.prototype.removeItem = function(k) { delete this._data[String(k)]; };
-Storage.prototype.clear = function() { const d = this._data; for (const k in d) delete d[k]; };
-Storage.prototype.key = function(i) { const ks = Object.keys(this._data); i = i >>> 0; return i < ks.length ? ks[i] : null; };
-Object.defineProperty(Storage.prototype, 'length', { get: function() { return Object.keys(this._data).length; }, configurable: true });
-
-const _mkStore = () => {
+// The backing store is Rust, keyed by origin, because the realm is rebuilt on
+// every navigation and a realm-local object loses every entry with it
+// (issue #678). The slot records which op owns the store so a same-origin frame
+// realm and the top document share the data while a cross-origin frame lands in
+// its own origin's bucket.
+const _storageSlots = new WeakMap();
+const _storageSlot = (value) => {
+ const slot = _storageSlots.get(value);
+ if (!slot) throw new TypeError('Illegal invocation');
+ return slot;
+};
+const _storageOp = (slot) => slot.local ? __obscuraCore.ops.op_local_storage : __obscuraCore.ops.op_session_storage;
+const _storageCall = (slot, command, key, value) => {
+ // The WebIDL string conversions stay outside the try: a Symbol argument has
+ // to raise TypeError, not fall through to the null that means "no backend".
+ const k = String(key);
+ const v = value === undefined ? '' : String(value);
+ try { return JSON.parse(_storageOp(slot)(command, k, v)); }
+ catch (_) { return null; }
+};
+// [key, value] pairs in insertion order, which is the order Storage.key() is
+// defined over.
+const _storageEntries = (slot) => {
+ const entries = _storageCall(slot, 'snapshot', '');
+ return Array.isArray(entries) ? entries : [];
+};
+Storage.prototype.getItem = function(k) {
+ const value = _storageCall(_storageSlot(this), 'get', k, '');
+ return typeof value === 'string' ? value : null;
+};
+Storage.prototype.setItem = function(k, v) {
+ const stored = _storageCall(_storageSlot(this), 'set', k, v);
+ if (stored !== true) throw new DOMException('Setting the value exceeded the quota.', 'QuotaExceededError');
+};
+Storage.prototype.removeItem = function(k) { _storageCall(_storageSlot(this), 'remove', k, ''); };
+Storage.prototype.clear = function() { _storageCall(_storageSlot(this), 'clear', '', ''); };
+Storage.prototype.key = function(i) {
+ const entries = _storageEntries(_storageSlot(this));
+ i = i >>> 0;
+ return i < entries.length ? entries[i][0] : null;
+};
+Object.defineProperty(Storage.prototype, 'length', {
+ get: function() { return _storageEntries(_storageSlot(this)).length; },
+ configurable: true,
+});
+
+const _mkStore = (local) => {
const target = Object.create(Storage.prototype);
- Object.defineProperty(target, '_data', { value: Object.create(null), writable: true, enumerable: false, configurable: true });
- const isReal = (p) => p === '_data' || p === 'constructor' || (p in Storage.prototype);
- return new Proxy(target, {
+ const slot = { local: !!local };
+ const isReal = (p) => p === 'constructor' || (p in Storage.prototype);
+ const proxy = new Proxy(target, {
get(t, p, recv) { if (typeof p === 'symbol' || isReal(p)) return Reflect.get(t, p, recv); const v = t.getItem(p); return v === null ? undefined : v; },
set(t, p, v, recv) { if (typeof p === 'symbol' || isReal(p)) return Reflect.set(t, p, v, recv); t.setItem(p, v); return true; },
- has(t, p) { if (typeof p === 'symbol' || isReal(p)) return true; return Object.prototype.hasOwnProperty.call(t._data, p); },
+ has(t, p) { if (typeof p === 'symbol' || isReal(p)) return true; return t.getItem(p) !== null; },
deleteProperty(t, p) { if (typeof p === 'symbol' || isReal(p)) return Reflect.deleteProperty(t, p); t.removeItem(p); return true; },
- ownKeys(t) { return Object.keys(t._data); },
+ ownKeys() { return _storageEntries(slot).map((entry) => entry[0]); },
getOwnPropertyDescriptor(t, p) {
- if (typeof p !== 'symbol' && Object.prototype.hasOwnProperty.call(t._data, p))
- return { value: t._data[p], writable: true, enumerable: true, configurable: true };
+ if (typeof p !== 'symbol') {
+ const value = t.getItem(p);
+ if (value !== null)
+ return { value, writable: true, enumerable: true, configurable: true };
+ }
return Reflect.getOwnPropertyDescriptor(t, p);
},
});
+ // Both the target and the proxy resolve to the slot: property access can
+ // arrive on either depending on how the receiver is threaded.
+ _storageSlots.set(target, slot);
+ _storageSlots.set(proxy, slot);
+ return proxy;
};
-globalThis.localStorage = _mkStore();
-globalThis.sessionStorage = _mkStore();
+globalThis.localStorage = _mkStore(true);
+globalThis.sessionStorage = _mkStore(false);
globalThis.btoa = globalThis.btoa || ((s) => { s = String(s); const b = new Uint8Array(s.length); for (let i = 0; i < s.length; i++) { const cp = s.charCodeAt(i); if (cp > 0xFF) throw new DOMException("The string to be encoded contains characters outside of the Latin1 range.", "InvalidCharacterError"); b[i] = cp; } const c="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; let r=""; for(let i=0;i<b.length;i+=3){const a=b[i],bb=b[i+1]??0,cc=b[i+2]??0; r+=c[a>>2]+c[((a&3)<<4)|(bb>>4)]+(i+1<b.length?c[((bb&15)<<2)|(cc>>6)]:"=")+(i+2<b.length?c[cc&63]:"=");} return r; });
globalThis.atob = globalThis.atob || ((s) => {
@@ -15209,129 +15257,810 @@ globalThis.RTCPeerConnection = class RTCPeerConnection {
globalThis.RTCSessionDescription = class RTCSessionDescription { constructor(d){this.type=d?.type;this.sdp=d?.sdp;} };
globalThis.RTCIceCandidate = class RTCIceCandidate { constructor(d){this.candidate=d?.candidate||'';} };
-// Minimal but spec-shape-correct IndexedDB shim. We don't persist anything,
-// but authentication libraries (Firebase, Supabase, dexie) hang forever on
-// the first `get` because their request's `onsuccess` is never called. Fire
-// `onsuccess` asynchronously with `null` so reads complete-but-empty, which
-// most libraries treat as a cache miss and fall back to the network.
-function _idbRequest(produceResult) {
- const req = {
- result: undefined,
- error: null,
- source: null,
- transaction: null,
- readyState: 'pending',
- onsuccess: null,
- onerror: null,
- addEventListener(type, fn) { req['on' + type] = fn; },
- removeEventListener(type, fn) { if (req['on' + type] === fn) req['on' + type] = null; },
- };
- Promise.resolve().then(() => {
+// IndexedDB. The object graph, the event ordering and the key handling live
+// here; the records and the schema live in Rust, keyed by origin, so they
+// survive the realm rebuild that every navigation performs and a profile
+// reload. The previous shim handed each object store its own Map and never
+// fired onupgradeneeded, so a schema-created database was unreachable and its
+// first read threw.
+(() => {
+ const _idbBackend = (payload) => {
try {
- req.result = produceResult();
- req.readyState = 'done';
- if (typeof req.onsuccess === 'function') {
- try { req.onsuccess({ target: req, type: 'success' }); } catch (e) {}
- }
+ const reply = JSON.parse(__obscuraCore.ops.op_indexed_db(JSON.stringify(payload)));
+ if (reply && reply.ok) return reply;
+ return { ok: false, error: (reply && reply.error) || 'IndexedDB request failed' };
} catch (e) {
- req.error = e; req.readyState = 'done';
- if (typeof req.onerror === 'function') {
- try { req.onerror({ target: req, type: 'error' }); } catch (e2) {}
+ return { ok: false, error: 'IndexedDB backend is unavailable' };
+ }
+ };
+ const _idbFail = (name, message) => new DOMException(message, name);
+
+ // Key ordering follows the spec's type order, so a numeric key sorts before a
+ // string one and an array key after both.
+ const _keyRank = (value) => {
+ if (typeof value === 'number') return 0;
+ if (value instanceof Date) return 1;
+ if (typeof value === 'string') return 2;
+ if (value instanceof ArrayBuffer || ArrayBuffer.isView(value)) return 3;
+ if (Array.isArray(value)) return 4;
+ return 5;
+ };
+ const _idbCmp = (a, b) => {
+ const ra = _keyRank(a);
+ const rb = _keyRank(b);
+ if (ra !== rb) return ra < rb ? -1 : 1;
+ if (ra === 0) return a === b ? 0 : (a < b ? -1 : 1);
+ if (ra === 1) {
+ const ta = a.getTime();
+ const tb = b.getTime();
+ return ta === tb ? 0 : (ta < tb ? -1 : 1);
+ }
+ if (ra === 2) return a === b ? 0 : (a < b ? -1 : 1);
+ if (ra === 4) {
+ const length = Math.max(a.length, b.length);
+ for (let i = 0; i < length; i++) {
+ if (i >= a.length) return -1;
+ if (i >= b.length) return 1;
+ const inner = _idbCmp(a[i], b[i]);
+ if (inner !== 0) return inner;
}
+ return 0;
}
- });
- return req;
-}
+ return 0;
+ };
+ const _idbValidKey = (value) => {
+ const rank = _keyRank(value);
+ if (rank === 0) return Number.isFinite(value);
+ if (rank === 2) return true;
+ if (rank === 4) return value.every(_idbValidKey);
+ return false;
+ };
+ const _idbInRange = (key, query) => {
+ if (query === undefined || query === null) return true;
+ if (typeof query === 'number' || typeof query === 'string' || query instanceof Date || Array.isArray(query)) {
+ return _idbCmp(key, query) === 0;
+ }
+ if (query.lower !== undefined && query.lower !== null) {
+ const lower = _idbCmp(key, query.lower);
+ if (query.lowerOpen ? lower <= 0 : lower < 0) return false;
+ }
+ if (query.upper !== undefined && query.upper !== null) {
+ const upper = _idbCmp(key, query.upper);
+ if (query.upperOpen ? upper >= 0 : upper > 0) return false;
+ }
+ return true;
+ };
+ // Key path: dotted, with numeric segments indexing into arrays, matching the
+ // spec's evaluation order for in-line keys.
+ const _idbExtractKey = (keyPath, value) => {
+ if (keyPath === undefined || keyPath === null || keyPath === '') return undefined;
+ let current = value;
+ for (const segment of String(keyPath).split('.')) {
+ if (current === undefined || current === null) return undefined;
+ current = current[segment];
+ }
+ return current;
+ };
+ const _idbSortedEntries = (records, query, direction, count) => {
+ const parsed = records.map((record) => ({
+ key: JSON.parse(record.key),
+ value: JSON.parse(record.value),
+ }));
+ parsed.sort((a, b) => _idbCmp(a.key, b.key));
+ if (direction === 'prev' || direction === 'previous') parsed.reverse();
+ if (query !== undefined && query !== null) {
+ return parsed.filter((entry) => _idbInRange(entry.key, query));
+ }
+ return parsed;
+ };
-function _idbObjectStore(name) {
- const data = new Map();
- return {
- name,
- keyPath: null,
- autoIncrement: false,
- indexNames: { contains() { return false; }, length: 0, item() { return null; } },
- transaction: null,
- add(value, key) { const k = key ?? Date.now(); data.set(k, value); return _idbRequest(() => k); },
- put(value, key) { const k = key ?? Date.now(); data.set(k, value); return _idbRequest(() => k); },
- get(key) { return _idbRequest(() => data.get(key) ?? undefined); },
- getAll() { return _idbRequest(() => Array.from(data.values())); },
- getAllKeys() { return _idbRequest(() => Array.from(data.keys())); },
- getKey(key) { return _idbRequest(() => (data.has(key) ? key : undefined)); },
- delete(key) { return _idbRequest(() => { data.delete(key); return undefined; }); },
- clear() { return _idbRequest(() => { data.clear(); return undefined; }); },
- count() { return _idbRequest(() => data.size); },
- openCursor() { return _idbRequest(() => null); },
- openKeyCursor() { return _idbRequest(() => null); },
- createIndex() { return { name: '', keyPath: '', unique: false, multiEntry: false, get() { return _idbRequest(() => undefined); } }; },
- index() { return { get() { return _idbRequest(() => undefined); }, getAll() { return _idbRequest(() => []); }, count() { return _idbRequest(() => 0); }, openCursor() { return _idbRequest(() => null); } }; },
- deleteIndex() {},
+ // ── IDBRequest ───────────────────────────────────────────────────────────
+ function IDBRequest() {}
+ IDBRequest.prototype = {
+ addEventListener(type, fn) {
+ if (typeof fn !== 'function') return;
+ (this._listeners[type] || (this._listeners[type] = [])).push(fn);
+ },
+ removeEventListener(type, fn) {
+ const list = this._listeners[type];
+ if (!list) return;
+ const at = list.indexOf(fn);
+ if (at >= 0) list.splice(at, 1);
+ },
+ _fire(type, event) {
+ const handler = this['on' + type];
+ if (typeof handler === 'function') { try { handler.call(this, event); } catch (e) {} }
+ for (const fn of (this._listeners[type] || []).slice()) {
+ try { fn.call(this, event); } catch (e) {}
+ }
+ },
+ };
+ Object.defineProperty(IDBRequest.prototype, 'IDBRequest', { value: IDBRequest, configurable: true });
+
+ const _newRequest = (transaction, source) => {
+ const request = Object.create(IDBRequest.prototype);
+ request._listeners = {};
+ request.result = undefined;
+ request.error = null;
+ request.source = source || null;
+ request.transaction = transaction || null;
+ request.readyState = 'pending';
+ request.onsuccess = null;
+ request.onerror = null;
+ return request;
+ };
+ const _settle = (request, work) => {
+ Promise.resolve().then(() => {
+ if (request.readyState !== 'pending') return;
+ try {
+ request.result = work();
+ request.readyState = 'done';
+ request._fire('success', { type: 'success', target: request });
+ } catch (error) {
+ request.error = error;
+ request.readyState = 'done';
+ request._fire('error', { type: 'error', target: request });
+ }
+ if (request.transaction) request.transaction._requestSettled();
+ });
+ };
+ const _fail = (request, name, message) => {
+ request.error = _idbFail(name, message);
+ request.readyState = 'done';
+ request._fire('error', { type: 'error', target: request });
+ if (request.transaction) request.transaction._requestSettled();
};
-}
-function _idbTransaction(storeNames) {
- const stores = new Map();
- const names = Array.isArray(storeNames) ? storeNames : [storeNames];
- for (const n of names) stores.set(String(n), _idbObjectStore(String(n)));
- const tx = {
- db: null,
- mode: 'readonly',
- objectStoreNames: { contains: (n) => stores.has(String(n)), length: stores.size },
- onabort: null, oncomplete: null, onerror: null,
- error: null,
+ // ── IDBTransaction ───────────────────────────────────────────────────────
+ function IDBTransaction() {}
+ IDBTransaction.prototype = {
+ addEventListener(type, fn) {
+ if (typeof fn !== 'function') return;
+ (this._listeners[type] || (this._listeners[type] = [])).push(fn);
+ },
+ removeEventListener(type, fn) {
+ const list = this._listeners[type];
+ if (!list) return;
+ const at = list.indexOf(fn);
+ if (at >= 0) list.splice(at, 1);
+ },
+ _fire(type, event) {
+ const handler = this['on' + type];
+ if (typeof handler === 'function') { try { handler.call(this, event); } catch (e) {} }
+ for (const fn of (this._listeners[type] || []).slice()) {
+ try { fn.call(this, event); } catch (e) {}
+ }
+ },
objectStore(name) {
- let s = stores.get(name);
- if (!s) { s = _idbObjectStore(name); stores.set(name, s); }
- s.transaction = tx;
- return s;
+ const key = String(name);
+ if (!this._storeNames.has(key)) {
+ throw _idbFail('NotFoundError', "no object store named '" + key + "' in this transaction");
+ }
+ return this._store(key);
+ },
+ abort() {
+ if (this._finished) throw _idbFail('InvalidStateError', 'the transaction is already finished');
+ this._finished = true;
+ this.error = this.error || _idbFail('AbortError', 'the transaction was aborted');
+ this._fire('abort', { type: 'abort', target: this });
},
- abort() {},
- commit() {},
- addEventListener(type, fn) { tx['on' + type] = fn; },
- removeEventListener(type, fn) { if (tx['on' + type] === fn) tx['on' + type] = null; },
+ commit() { this._committed = true; },
};
- Promise.resolve().then(() => {
- if (typeof tx.oncomplete === 'function') {
- try { tx.oncomplete({ target: tx, type: 'complete' }); } catch (e) {}
+ Object.defineProperty(IDBTransaction.prototype, 'IDBTransaction', { value: IDBTransaction, configurable: true });
+
+ const _newTransaction = (db, storeNames, mode) => {
+ const transaction = Object.create(IDBTransaction.prototype);
+ transaction._listeners = {};
+ transaction.db = db;
+ transaction.mode = mode || 'readonly';
+ transaction.error = null;
+ transaction.onabort = null;
+ transaction.oncomplete = null;
+ transaction.onerror = null;
+ transaction._storeNames = new Set(storeNames);
+ transaction._stores = new Map();
+ transaction._pending = 0;
+ transaction._finished = false;
+ transaction._committed = false;
+ transaction.objectStoreNames = {
+ get length() { return transaction._storeNames.size; },
+ item: (index) => [...transaction._storeNames][index] ?? null,
+ contains: (name) => transaction._storeNames.has(String(name)),
+ };
+ return transaction;
+ };
+ IDBTransaction.prototype._store = function(name) {
+ let store = this._stores.get(name);
+ if (!store) {
+ store = _newObjectStore(this, name);
+ this._stores.set(name, store);
}
- });
- return tx;
-}
+ return store;
+ };
+ // The spec completes a transaction once its last request has settled, not on a
+ // fixed microtask, so a caller that chains requests in oncomplete still sees
+ // a live transaction.
+ IDBTransaction.prototype._requestStarted = function() {
+ if (this._finished) throw _idbFail('TransactionInactiveError', 'the transaction has already finished');
+ this._pending += 1;
+ };
+ IDBTransaction.prototype._requestSettled = function() {
+ if (this._finished) return;
+ this._pending -= 1;
+ if (this._pending > 0) return;
+ // Completion waits for a macrotask, not a microtask. The spec keeps a
+ // transaction alive while requests are still being queued in the same task,
+ // and the normal pattern is exactly that: chain a get after a getAll. With a
+ // microtask the transaction was already finished before the second request
+ // existed, so every chained call raised TransactionInactiveError.
+ setTimeout(() => {
+ if (this._finished || this._pending > 0) return;
+ this._finished = true;
+ this._fire('complete', { type: 'complete', target: this });
+ }, 0);
+ };
-function _idbDatabase(name, version) {
- return {
- name,
- version,
- objectStoreNames: { contains() { return false; }, length: 0, item() { return null; } },
- createObjectStore(n) { return _idbObjectStore(n); },
- deleteObjectStore() {},
- transaction(storeNames, mode) {
- const tx = _idbTransaction(storeNames);
- tx.mode = mode || 'readonly';
- return tx;
+ // ── IDBCursor ────────────────────────────────────────────────────────────
+ function IDBCursor() {}
+ IDBCursor.prototype = {
+ addEventListener(type, fn) {
+ if (typeof fn !== 'function') return;
+ (this._listeners[type] || (this._listeners[type] = [])).push(fn);
},
- close() {},
- onversionchange: null, onabort: null, onerror: null, onclose: null,
+ removeEventListener(type, fn) {
+ const list = this._listeners[type];
+ if (!list) return;
+ const at = list.indexOf(fn);
+ if (at >= 0) list.splice(at, 1);
+ },
+ continue(key) {
+ if (key !== undefined) this._pendingKey = key;
+ this._advance(1);
+ },
+ continuePrimaryKey(key, primaryKey) { this.continue(key); },
+ advance(count) { this._advance(count); },
+ update(value) {
+ this._objectStore._write(this.primaryKey, value, false);
+ },
+ delete() {
+ this._objectStore._request('delete', () => ({ key: this.primaryKey }), undefined);
+ },
+ _advance(step) {
+ this._index += step;
+ this._emit();
+ },
+ _emit() {
+ const entry = this._entries[this._index];
+ // Running past the last record has to publish a null result and fire
+ // success again, otherwise a `while (cursor) cursor.continue()` loop never
+ // ends: the request kept its old cursor and nothing was dispatched.
+ if (!entry) {
+ this.request.result = null;
+ this._emitEvent();
+ return;
+ }
+ // `key` is the index key when the cursor came from an index, and the
+ // primary key otherwise; `primaryKey` is always the record's own key.
+ this.primaryKey = entry.primaryKey === undefined ? entry.key : entry.primaryKey;
+ this.key = this._keyOnly ? this.primaryKey : entry.key;
+ this.value = this._keyOnly ? undefined : entry.value;
+ this.request.result = this;
+ this._emitEvent();
+ },
+ _emitEvent() {
+ const handler = this.request.onsuccess;
+ const event = { type: 'success', target: this.request };
+ if (typeof handler === 'function') { try { handler.call(this.request, event); } catch (e) {} }
+ for (const fn of (this.request._listeners.success || []).slice()) {
+ try { fn.call(this.request, event); } catch (e) {}
+ }
+ },
+ _indexKey() { return this.key; },
+ // Unused now that _emit reads entry.key and entry.primaryKey directly, kept
+ // so nothing external depends on the old helper.
+ _indexKeyOf(entry) { return entry.key; },
+ };
+ Object.defineProperty(IDBCursor.prototype, 'IDBCursor', { value: IDBCursor, configurable: true });
+
+ const _newCursor = (request, objectStore, entries, keyOnly) => {
+ const cursor = Object.create(IDBCursor.prototype);
+ cursor._listeners = {};
+ cursor.request = request;
+ cursor._objectStore = objectStore;
+ cursor._entries = entries;
+ cursor._keyOnly = keyOnly;
+ cursor.direction = 'next';
+ cursor._index = -1;
+ cursor.primaryKey = undefined;
+ cursor.key = undefined;
+ cursor.value = undefined;
+ return cursor;
+ };
+
+ // ── IDBObjectStore and IDBIndex ───────────────────────────────────────────
+ function IDBObjectStore() {}
+ function IDBIndex() {}
+ IDBIndex.prototype = {
addEventListener() {}, removeEventListener() {},
+ get(key) { return this._objectStore._request('get', () => ({ key, index: this }), undefined); },
+ getKey(key) { return this._objectStore._request('get', () => ({ key, index: this }), undefined); },
+ getAll(query, count) {
+ return this._objectStore._request('entries', () => ({ query, count, index: this }), undefined);
+ },
+ getAllKeys(query, count) {
+ return this._objectStore._request('entries', () => ({ query, count, keysOnly: true, index: this }), undefined);
+ },
+ count(query) { return this._objectStore._request('entries', () => ({ query, index: this, countOnly: true }), undefined); },
+ openCursor(query, direction) {
+ return this._objectStore._request('entries', () => ({ query, direction, index: this, cursor: true }), undefined);
+ },
+ openKeyCursor(query, direction) {
+ return this._objectStore._request('entries', () => ({ query, direction, keysOnly: true, index: this, cursor: true }), undefined);
+ },
};
-}
+ Object.defineProperty(IDBIndex.prototype, 'IDBIndex', { value: IDBIndex, configurable: true });
-globalThis.indexedDB = {
- open(name, version) {
- return _idbRequest(() => _idbDatabase(name, version || 1));
- },
- deleteDatabase(_name) { return _idbRequest(() => undefined); },
- databases() { return Promise.resolve([]); },
- cmp(a, b) { return a < b ? -1 : a > b ? 1 : 0; },
-};
-globalThis.IDBKeyRange = {
- only(v) { return { lower: v, upper: v, lowerOpen: false, upperOpen: false, includes(x) { return x === v; } }; },
- lowerBound(v, open) { return { lower: v, upper: null, lowerOpen: !!open, upperOpen: false, includes(x) { return open ? x > v : x >= v; } }; },
- upperBound(v, open) { return { lower: null, upper: v, lowerOpen: false, upperOpen: !!open, includes(x) { return open ? x < v : x <= v; } }; },
- bound(l, u, lo, uo) { return { lower: l, upper: u, lowerOpen: !!lo, upperOpen: !!uo, includes(x) { return (lo ? x > l : x >= l) && (uo ? x < u : x <= u); } }; },
-};
+ IDBObjectStore.prototype = {
+ addEventListener() {}, removeEventListener() {},
+ get name() { return this._name; },
+ get keyPath() { return this._keyPath ?? null; },
+ get autoIncrement() { return !!this._autoIncrement; },
+ get transaction() { return this._transaction; },
+ get indexNames() {
+ const names = Object.keys(this._indexes);
+ return {
+ get length() { return names.length; },
+ item: (index) => names[index] ?? null,
+ contains: (name) => Object.prototype.hasOwnProperty.call(this._indexes, String(name)),
+ };
+ },
+ put(value, key) { return this._write(key, value, false); },
+ add(value, key) { return this._write(key, value, true); },
+ get(key) { return this._request('get', () => ({ key }), undefined); },
+ getKey(key) { return this._request('get', () => ({ key }), undefined); },
+ getAll(query, count) { return this._request('entries', () => ({ query, count }), undefined); },
+ getAllKeys(query, count) { return this._request('entries', () => ({ query, count, keysOnly: true }), undefined); },
+ count(query) { return this._request('entries', () => ({ query, countOnly: true }), undefined); },
+ delete(key) { return this._request('delete', () => ({ key }), undefined); },
+ clear() { return this._request('clear', () => ({}), undefined); },
+ openCursor(query, direction) {
+ return this._cursor(query, direction, false);
+ },
+ openKeyCursor(query, direction) {
+ return this._cursor(query, direction, true);
+ },
+ createIndex(name, keyPath, options) {
+ if (this._transaction.mode !== 'versionchange') {
+ throw _idbFail('InvalidStateError', 'createIndex requires a versionchange transaction');
+ }
+ const index = Object.create(IDBIndex.prototype);
+ index._objectStore = this;
+ index.name = String(name);
+ index.keyPath = String(keyPath);
+ index.unique = !!(options && options.unique);
+ index.multiEntry = !!(options && options.multiEntry);
+ this._indexes[index.name] = index;
+ this._transaction._schemaChanged();
+ return index;
+ },
+ index(name) {
+ const index = this._indexes[String(name)];
+ if (!index) throw _idbFail('NotFoundError', "no index named '" + name + "'");
+ return index;
+ },
+ deleteIndex(name) {
+ delete this._indexes[String(name)];
+ this._transaction._schemaChanged();
+ },
+ // Resolve the key the spec would use: explicit key first, then the key path,
+ // then the generator when the store is auto-incrementing.
+ _resolveKey(value, explicitKey) {
+ if (explicitKey !== undefined && explicitKey !== null) {
+ if (!_idbValidKey(explicitKey)) throw _idbFail('DataError', 'the key is not a valid IndexedDB key');
+ return explicitKey;
+ }
+ const fromPath = this._keyPath ? _idbExtractKey(this._keyPath, value) : undefined;
+ if (fromPath !== undefined) {
+ if (!_idbValidKey(fromPath)) throw _idbFail('DataError', 'the key path did not yield a valid key');
+ return fromPath;
+ }
+ if (this._autoIncrement) {
+ this._nextKey += 1;
+ return this._nextKey;
+ }
+ throw _idbFail('DataError', 'the store needs an explicit key or a key path');
+ },
+ _write(key, value, mustBeNew) {
+ return this._request('put', () => ({ key: this._resolveKey(value, key), value, mustBeNew }), undefined);
+ },
+ _cursor(query, direction, keyOnly) {
+ return this._request('entries', () => ({ query, direction, keysOnly: keyOnly, cursor: true }));
+ },
+ // Every operation is one request: the spec allows the caller to read
+ // `transaction` and the store's metadata while a request is pending.
+ _request(command, args, initial) {
+ const request = _newRequest(this._transaction, this);
+ if (command === 'entries' && args().cursor) {
+ // A cursor request starts empty and is filled in by the body below, so
+ // `request.result` can be replaced by the first `continue`.
+ request.result = null;
+ }
+ if (initial !== null && initial !== undefined && command !== 'entries') {
+ request.result = initial;
+ return request;
+ }
+ this._transaction._requestStarted();
+ Promise.resolve().then(() => {
+ try {
+ const payload = args();
+ const base = { db: this._dbName, store: this._name, cmd: command };
+ let reply;
+ if (command === 'entries') {
+ reply = _idbBackend(Object.assign({}, base, { cmd: 'entries' }));
+ if (!reply.ok) return _fail(request, 'UnknownError', reply.error);
+ const entries = reply.records || [];
+ const parsed = entries.map((record) => ({ key: JSON.parse(record.key), value: JSON.parse(record.value) }));
+ const index = payload.index;
+ const scoped = index
+ ? parsed
+ .map((entry) => ({ key: _idbExtractKey(index.keyPath, entry.value), value: entry.value, primaryKey: entry.key }))
+ .filter((entry) => entry.key !== undefined && _idbInRange(entry.key, payload.query))
+ .sort((a, b) => _idbCmp(a.key, b.key))
+ : parsed.sort((a, b) => _idbCmp(a.key, b.key));
+ if (payload.direction === 'prev' || payload.direction === 'previous') scoped.reverse();
+ const limited = typeof payload.count === 'number' ? scoped.slice(0, payload.count) : scoped;
+ if (payload.cursor) {
+ const cursor = _newCursor(request, this, limited, !!payload.keysOnly);
+ cursor.direction = payload.direction || 'next';
+ request.result = cursor;
+ cursor._index = -1;
+ cursor._advance(1);
+ request.readyState = 'done';
+ this._transaction._requestSettled();
+ return;
+ }
+ if (payload.countOnly) { request.result = limited.length; request.readyState = 'done'; request._fire('success', { type: 'success', target: request }); this._transaction._requestSettled(); return; }
+ if (payload.keysOnly) { request.result = limited.map((entry) => (index ? entry.key : entry.key)); }
+ else if (index) { request.result = limited.map((entry) => entry.value); }
+ else { request.result = limited.map((entry) => entry.value); }
+ request.readyState = 'done';
+ request._fire('success', { type: 'success', target: request });
+ this._transaction._requestSettled();
+ return;
+ }
+ if (command === 'get') {
+ const keyJson = JSON.stringify(payload.key);
+ reply = _idbBackend(Object.assign({}, base, { cmd: 'get', key: payload.key }));
+ if (!reply.ok) return _fail(request, 'UnknownError', reply.error);
+ if (!reply.found) {
+ request.result = undefined;
+ } else {
+ const value = JSON.parse(reply.value);
+ if (payload.index) {
+ const indexKey = _idbExtractKey(payload.index.keyPath, value);
+ request.result = indexKey !== undefined && _idbCmp(indexKey, payload.key) === 0 ? value : undefined;
+ } else if (_idbCmp(JSON.parse(keyJson), payload.key) === 0) {
+ request.result = value;
+ } else {
+ request.result = undefined;
+ }
+ }
+ request.readyState = 'done';
+ request._fire('success', { type: 'success', target: request });
+ this._transaction._requestSettled();
+ return;
+ }
+ if (command === 'put') {
+ reply = _idbBackend(Object.assign({}, base, { cmd: 'put', key: payload.key, value: payload.value }));
+ if (!reply.ok) return _fail(request, 'QuotaExceededError', reply.error);
+ if (payload.mustBeNew && reply.replaced) {
+ return _fail(request, 'ConstraintError', 'the key already exists');
+ }
+ if (payload.index) {
+ this._keySeq += 1;
+ const keyJson = JSON.stringify(payload.key);
+ }
+ if (this._autoIncrement && typeof payload.key === 'number' && payload.key >= this._nextKey) {
+ this._nextKey = payload.key;
+ }
+ request.result = payload.key;
+ request.readyState = 'done';
+ request._fire('success', { type: 'success', target: request });
+ this._transaction._requestSettled();
+ return;
+ }
+ reply = _idbBackend(Object.assign({}, base, { cmd: command, key: payload.key }));
+ if (!reply.ok) return _fail(request, 'UnknownError', reply.error);
+ request.result = undefined;
+ request.readyState = 'done';
+ request._fire('success', { type: 'success', target: request });
+ this._transaction._requestSettled();
+ } catch (e) {
+ // A throw inside the body used to leave the request pending and the
+ // transaction never completing, which reads as a hung page.
+ _fail(request, 'UnknownError', String(e));
+ }
+ });
+ return request;
+ },
+ };
+ Object.defineProperty(IDBObjectStore.prototype, 'IDBObjectStore', { value: IDBObjectStore, configurable: true });
+
+ const _newObjectStore = (transaction, name) => {
+ const store = Object.create(IDBObjectStore.prototype);
+ const definition = transaction._schema[name] || {};
+ store._name = name;
+ store._dbName = transaction.db.name;
+ store._transaction = transaction;
+ store._keyPath = definition.keyPath ?? null;
+ store._autoIncrement = !!definition.autoIncrement;
+ store._indexes = {};
+ for (const stored of definition.indexes || []) {
+ const index = Object.create(IDBIndex.prototype);
+ index._objectStore = store;
+ index.name = stored.name;
+ index.keyPath = stored.keyPath;
+ index.unique = !!stored.unique;
+ index.multiEntry = !!stored.multiEntry;
+ store._indexes[index.name] = index;
+ }
+ store._nextKey = 0;
+ store._keySeq = 0;
+ return store;
+ };
+
+ // ── IDBDatabase ──────────────────────────────────────────────────────────
+ function IDBDatabase() {}
+ IDBDatabase.prototype = {
+ addEventListener(type, fn) {
+ if (typeof fn !== 'function') return;
+ (this._listeners[type] || (this._listeners[type] = [])).push(fn);
+ },
+ removeEventListener(type, fn) {
+ const list = this._listeners[type];
+ if (!list) return;
+ const at = list.indexOf(fn);
+ if (at >= 0) list.splice(at, 1);
+ },
+ _fire(type, event) {
+ const handler = this['on' + type];
+ if (typeof handler === 'function') { try { handler.call(this, event); } catch (e) {} }
+ for (const fn of (this._listeners[type] || []).slice()) {
+ try { fn.call(this, event); } catch (e) {}
+ }
+ },
+ get name() { return this._name; },
+ get version() { return this._version; },
+ get objectStoreNames() {
+ const names = Object.keys(this._schema);
+ return {
+ get length() { return names.length; },
+ item: (index) => names[index] ?? null,
+ contains: (name) => Object.prototype.hasOwnProperty.call(this._schema, String(name)),
+ };
+ },
+ createObjectStore(name, options) {
+ if (this._closed) throw _idbFail('InvalidStateError', 'the database is closed');
+ const key = String(name);
+ if (this._schema[key]) throw _idbFail('ConstraintError', "an object store named '" + key + "' already exists");
+ this._schema[key] = {
+ keyPath: (options && options.keyPath) ?? null,
+ autoIncrement: !!(options && options.autoIncrement),
+ indexes: [],
+ };
+ this._upgradeTransaction._schemaChanged();
+ return this._upgradeTransaction._store(key);
+ },
+ deleteObjectStore(name) {
+ const key = String(name);
+ if (!this._schema[key]) throw _idbFail('NotFoundError', "no object store named '" + key + "'");
+ delete this._schema[key];
+ this._upgradeTransaction._schemaChanged();
+ },
+ transaction(storeNames, mode) {
+ if (this._closed) throw _idbFail('InvalidStateError', 'the database is closed');
+ const names = (Array.isArray(storeNames) ? storeNames : [storeNames]).map(String);
+ for (const name of names) {
+ if (!this._schema[name]) {
+ throw _idbFail('NotFoundError', "no object store named '" + name + "'");
+ }
+ }
+ const transaction = _newTransaction(this, names, mode);
+ transaction._schema = this._schema;
+ return transaction;
+ },
+ close() { this._closed = true; },
+ };
+ Object.defineProperty(IDBDatabase.prototype, 'IDBDatabase', { value: IDBDatabase, configurable: true });
+
+ const _newDatabase = (name, version, schema, upgradeTransaction) => {
+ const db = Object.create(IDBDatabase.prototype);
+ db._listeners = {};
+ db._name = name;
+ db._version = version;
+ db._schema = schema;
+ db._upgradeTransaction = upgradeTransaction || null;
+ db._closed = false;
+ db.onversionchange = null;
+ db.onabort = null;
+ db.onerror = null;
+ db.onclose = null;
+ return db;
+ };
+
+ const _serializeSchema = (db) => {
+ const stores = {};
+ for (const [name, definition] of Object.entries(db._schema)) {
+ stores[name] = {
+ keyPath: definition.keyPath ?? null,
+ autoIncrement: !!definition.autoIncrement,
+ indexes: Object.values(definition.indexes || {}).map((index) => ({
+ name: index.name, keyPath: index.keyPath, unique: !!index.unique, multiEntry: !!index.multiEntry,
+ })),
+ };
+ }
+ return stores;
+ };
+ const _deserializeSchema = (raw) => {
+ const schema = {};
+ for (const [name, definition] of Object.entries(raw || {})) {
+ const indexes = {};
+ for (const index of definition.indexes || []) indexes[index.name] = index;
+ schema[name] = {
+ keyPath: definition.keyPath ?? null,
+ autoIncrement: !!definition.autoIncrement,
+ indexes,
+ };
+ }
+ return schema;
+ };
+
+ // ── IDBKeyRange ──────────────────────────────────────────────────────────
+ function IDBKeyRange(lower, upper, lowerOpen, upperOpen) {
+ this.lower = lower === undefined ? null : lower;
+ this.upper = upper === undefined ? null : upper;
+ this.lowerOpen = !!lowerOpen;
+ this.upperOpen = !!upperOpen;
+ }
+ IDBKeyRange.prototype.includes = function(key) { return _idbInRange(key, this); };
+ Object.defineProperty(IDBKeyRange.prototype, 'IDBKeyRange', { value: IDBKeyRange, configurable: true });
+
+ const _keyRangeCheck = (value) => {
+ if (!_idbValidKey(value)) throw _idbFail('DataError', 'not a valid IndexedDB key');
+ return value;
+ };
+
+ // ── IDBFactory ───────────────────────────────────────────────────────────
+ function IDBFactory() {}
+ IDBFactory.prototype = {
+ open(name, version) {
+ const dbName = String(name);
+ const requested = Math.max(1, Math.trunc(version === undefined ? 1 : version) || 1);
+ const request = _newRequest(null, null);
+ request.onupgradeneeded = null;
+ request.onblocked = null;
+ request.onupgradeneeded_elsewhere = null;
+ Promise.resolve().then(() => {
+ try {
+ const reply = _idbBackend({ db: dbName, cmd: 'open', version: requested });
+ if (!reply.ok) {
+ request.error = _idbFail('UnknownError', reply.error);
+ request.readyState = 'done';
+ request._fire('error', { type: 'error', target: request });
+ return;
+ }
+ const schema = _deserializeSchema(reply.stores);
+ if (!reply.upgradeNeeded) {
+ request.result = _newDatabase(dbName, reply.version || requested, schema, null);
+ request.readyState = 'done';
+ request._fire('success', { type: 'success', target: request });
+ return;
+ }
+ // Upgrade path: hand the page a versionchange transaction whose
+ // createObjectStore calls land in the schema, then commit it.
+ const oldVersion = reply.version || 0;
+ const database = _newDatabase(dbName, requested, schema, null);
+ const transaction = _newTransaction(database, [], 'versionchange');
+ transaction._schema = schema;
+ transaction._upgrade = true;
+ transaction._schemaChanged = function() { this._schemaDirty = true; };
+ database._upgradeTransaction = transaction;
+ request.transaction = transaction;
+ request.result = database;
+ request.readyState = 'done';
+ request._fire('upgradeneeded', {
+ type: 'upgradeneeded',
+ target: request,
+ oldVersion,
+ newVersion: requested,
+ transaction,
+ });
+ Promise.resolve().then(() => {
+ if (!reply.exists && Object.keys(schema).length === 0 && !transaction._schemaDirty) {
+ // No schema was declared, which is a legitimate empty database.
+ }
+ const commit = _idbBackend({
+ db: dbName,
+ cmd: 'schema',
+ version: requested,
+ stores: _serializeSchema(database),
+ });
+ if (!commit.ok) {
+ request.error = _idbFail('UnknownError', commit.error);
+ request._fire('error', { type: 'error', target: request });
+ return;
+ }
+ transaction._fire('complete', { type: 'complete', target: transaction });
+ request._fire('success', { type: 'success', target: request });
+ });
+ } catch (e) {
+ request.error = _idbFail('UnknownError', String(e));
+ request.readyState = 'done';
+ request._fire('error', { type: 'error', target: request });
+ }
+ });
+ return request;
+ },
+ deleteDatabase(name) {
+ const dbName = String(name);
+ const request = _newRequest(null, null);
+ request.onblocked = null;
+ Promise.resolve().then(() => {
+ const reply = _idbBackend({ db: dbName, cmd: 'deleteDatabase' });
+ request.result = undefined;
+ request.readyState = 'done';
+ if (!reply.ok) {
+ request.error = _idbFail('UnknownError', reply.error);
+ request._fire('error', { type: 'error', target: request });
+ return;
+ }
+ request._fire('success', { type: 'success', target: request });
+ });
+ return request;
+ },
+ // The spec has IDBFactory.databases() return a Promise of
+ // IDBDatabaseInfo records, not a request. Returning the request left
+ // `await indexedDB.databases()` resolving to the request itself, so callers
+ // that read `.result` off the awaited value saw undefined and a boot that
+ // waits on that list never finished.
+ databases() {
+ const request = _newRequest(null, null);
+ const promise = Promise.resolve().then(() => {
+ const reply = _idbBackend({ cmd: 'list' });
+ const databases = reply.ok ? (reply.databases || []) : [];
+ request.result = databases;
+ request.readyState = 'done';
+ request._fire('success', { type: 'success', target: request });
+ return databases;
+ });
+ promise.request = request;
+ return promise;
+ },
+ cmp(a, b) { return _idbCmp(a, b); },
+ };
+ Object.defineProperty(IDBFactory.prototype, 'IDBFactory', { value: IDBFactory, configurable: true });
+
+ const _idbOpenRequests = new WeakMap();
+ const factory = new IDBFactory();
+ _idbOpenRequests.set(factory, factory);
+ globalThis.IDBFactory = IDBFactory;
+ globalThis.IDBRequest = IDBRequest;
+ globalThis.IDBTransaction = IDBTransaction;
+ globalThis.IDBDatabase = IDBDatabase;
+ globalThis.IDBObjectStore = IDBObjectStore;
+ globalThis.IDBIndex = IDBIndex;
+ globalThis.IDBCursor = IDBCursor;
+ globalThis.IDBKeyRange = IDBKeyRange;
+ globalThis.IDBKeyRange.only = (value) => new IDBKeyRange(_keyRangeCheck(value), _keyRangeCheck(value), false, false);
+ globalThis.IDBKeyRange.lowerBound = (value, open) => new IDBKeyRange(_keyRangeCheck(value), null, !!open, false);
+ globalThis.IDBKeyRange.upperBound = (value, open) => new IDBKeyRange(null, _keyRangeCheck(value), false, !!open);
+ globalThis.IDBKeyRange.bound = (lower, upper, lowerOpen, upperOpen) =>
+ new IDBKeyRange(_keyRangeCheck(lower), _keyRangeCheck(upper), !!lowerOpen, !!upperOpen);
+ globalThis.indexedDB = factory;
+})();
// Do not advertise CacheStorage until it can retain responses. A successful
-// no-op cache selects broken persistence paths instead of normal fetch fallbacks.
+// no-op cache selects broken persistence paths instead of normal fetch fallbacks.ch fallbacks.
_markNative(AudioContext); _markNative(OfflineAudioContext);
_markNative(SpeechSynthesisUtterance);
diff --git a/crates/obscura-js/src/ops.rs b/crates/obscura-js/src/ops.rs
index d1863686..5923e4c1 100644
--- a/crates/obscura-js/src/ops.rs
+++ b/crates/obscura-js/src/ops.rs
@@ -149,6 +149,519 @@ impl NavigationTiming {
}
}
+/// Per-origin key/value store behind `localStorage` and `sessionStorage`.
+///
+/// Web Storage used to be a plain JS object inside the V8 realm, and
+/// `Page::init_js` builds a new realm on every navigation, so every entry was
+/// lost on the next document load (issue #678). Keeping the data here, keyed by
+/// origin, makes an entry survive realm teardown: `localStorage` on the
+/// BrowserContext so every page in a context shares it, `sessionStorage` on the
+/// Page so it crosses same-origin navigation without ever leaving the tab.
+///
+/// Insertion order is preserved because `Storage.key(i)` is defined in insertion
+/// order, not sorted order.
+const LOCAL_STORAGE_ORIGIN_LIMIT: usize = 5 * 1024 * 1024;
+const LOCAL_STORAGE_TOTAL_LIMIT: usize = 32 * 1024 * 1024;
+const LOCAL_STORAGE_ORIGIN_COUNT_LIMIT: usize = 256;
+
+#[derive(Default)]
+struct OriginStorageInner {
+ origins: HashMap<String, Vec<(String, String)>>,
+ bytes: usize,
+}
+
+#[derive(Default)]
+pub struct OriginStorage {
+ inner: std::sync::Mutex<OriginStorageInner>,
+ /// Set by every mutation, cleared by the disk writer. Without it a
+ /// navigation would rewrite every origin file even when nothing changed,
+ /// and `--storage-dir` would turn each page load into a few dozen writes.
+ dirty: std::sync::atomic::AtomicBool,
+ /// Origins touched since the last successful write. The writer only has to
+ /// look at these, and an origin that lost its last entry is in here too, so
+ /// its file can be removed instead of resurrected on the next load.
+ changed: std::sync::Mutex<HashSet<String>>,
+}
+
+impl OriginStorage {
+ pub fn snapshot(&self, origin: &str) -> Vec<(String, String)> {
+ self.inner
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner())
+ .origins
+ .get(origin)
+ .cloned()
+ .unwrap_or_default()
+ }
+
+ pub fn get(&self, origin: &str, key: &str) -> Option<String> {
+ self.inner
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner())
+ .origins
+ .get(origin)
+ .and_then(|items| items.iter().find(|(name, _)| name == key))
+ .map(|(_, value)| value.clone())
+ }
+
+ /// Returns false when the write would exceed a quota, which the caller
+ /// surfaces as a `QuotaExceededError` the way a real browser does.
+ pub fn set(&self, origin: &str, key: String, value: String) -> bool {
+ let mut inner = self
+ .inner
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner());
+ if !inner.origins.contains_key(origin)
+ && inner.origins.len() >= LOCAL_STORAGE_ORIGIN_COUNT_LIMIT
+ {
+ return false;
+ }
+
+ let items = inner.origins.get(origin);
+ let previous = items
+ .and_then(|items| items.iter().find(|(name, _)| name == &key))
+ .map(|(name, value)| name.len() + value.len())
+ .unwrap_or(0);
+ let origin_bytes = items
+ .map(|items| {
+ items
+ .iter()
+ .map(|(name, value)| name.len() + value.len())
+ .sum::<usize>()
+ })
+ .unwrap_or(0);
+ let new_bytes = key.len() + value.len();
+ let next_origin_bytes = origin_bytes.saturating_sub(previous) + new_bytes;
+ let next_total_bytes = inner.bytes.saturating_sub(previous) + new_bytes;
+ if next_origin_bytes > LOCAL_STORAGE_ORIGIN_LIMIT
+ || next_total_bytes > LOCAL_STORAGE_TOTAL_LIMIT
+ {
+ return false;
+ }
+
+ let items = inner.origins.entry(origin.to_string()).or_default();
+ if let Some((_, old_value)) = items.iter_mut().find(|(name, _)| name == &key) {
+ *old_value = value;
+ } else {
+ items.push((key, value));
+ }
+ inner.bytes = next_total_bytes;
+ drop(inner);
+ self.mark_changed(origin);
+ true
+ }
+
+ pub fn remove(&self, origin: &str, key: &str) {
+ let mut inner = self
+ .inner
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner());
+ let removed = inner.origins.get_mut(origin).and_then(|items| {
+ items
+ .iter()
+ .position(|(name, _)| name == key)
+ .map(|index| items.remove(index))
+ });
+ if let Some((name, value)) = removed {
+ inner.bytes -= name.len() + value.len();
+ }
+ if inner.origins.get(origin).is_some_and(Vec::is_empty) {
+ inner.origins.remove(origin);
+ }
+ drop(inner);
+ self.mark_changed(origin);
+ }
+
+ /// Every origin with entries, in a stable order so a disk write produces a
+ /// reproducible file set.
+ pub fn entries(&self) -> Vec<(String, Vec<(String, String)>)> {
+ let inner = self
+ .inner
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner());
+ let mut out: Vec<(String, Vec<(String, String)>)> = inner
+ .origins
+ .iter()
+ .filter(|(_, items)| !items.is_empty())
+ .map(|(origin, items)| (origin.clone(), items.clone()))
+ .collect();
+ out.sort_by(|a, b| a.0.cmp(&b.0));
+ out
+ }
+
+ /// Replace an origin's store wholesale. Used when reloading a profile from
+ /// `--storage-dir`, and by tests that assert a round trip.
+ pub fn load(&self, origin: &str, items: Vec<(String, String)>) {
+ let mut inner = self
+ .inner
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner());
+ let bytes: usize = items
+ .iter()
+ .map(|(name, value)| name.len() + value.len())
+ .sum();
+ inner.bytes = inner.bytes.saturating_sub(
+ inner
+ .origins
+ .get(origin)
+ .map(|old| old.iter().map(|(name, value)| name.len() + value.len()).sum::<usize>())
+ .unwrap_or(0),
+ ) + bytes;
+ if items.is_empty() {
+ inner.origins.remove(origin);
+ } else {
+ inner.origins.insert(origin.to_string(), items);
+ }
+ drop(inner);
+ self.mark_changed(origin);
+ }
+
+ fn mark_changed(&self, origin: &str) {
+ self.dirty.store(true, std::sync::atomic::Ordering::Release);
+ self.changed
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner())
+ .insert(origin.to_string());
+ }
+
+ /// Origins written to since the last successful flush, in a stable order.
+ pub fn changed_origins(&self) -> Vec<String> {
+ let changed = self
+ .changed
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner());
+ let mut out: Vec<String> = changed.iter().cloned().collect();
+ out.sort();
+ out
+ }
+
+ /// Called by the disk writer once every touched origin reached the disk, so
+ /// a failed write leaves the store dirty and is retried.
+ pub fn take_changed(&self) {
+ self.changed
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner())
+ .clear();
+ self.dirty.store(false, std::sync::atomic::Ordering::Release);
+ }
+
+ pub fn is_dirty(&self) -> bool {
+ self.dirty.load(std::sync::atomic::Ordering::Acquire)
+ }
+
+ pub fn clear(&self, origin: &str) {
+ let mut inner = self
+ .inner
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner());
+ let removed = inner.origins.remove(origin);
+ if let Some(items) = removed {
+ inner.bytes -= items
+ .iter()
+ .map(|(name, value)| name.len() + value.len())
+ .sum::<usize>();
+ }
+ drop(inner);
+ // Marked as changed, not just dirty: the writer only inspects origins in
+ // this set, so a clear that only set the flag left the file on disk and
+ // the next load resurrected the entries the user had cleared.
+ self.mark_changed(origin);
+ }
+}
+
+/// One object store's durable state. Keys and values are JSON so they cross the
+/// op boundary without a native value type; a `Date`, `Map` or `Blob` therefore
+/// does not survive a reload, which is a documented limitation rather than a
+/// silent one.
+#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
+struct StoredIdbStore {
+ #[serde(default)]
+ key_path: Option<String>,
+ #[serde(default)]
+ auto_increment: bool,
+ #[serde(default)]
+ indexes: Vec<StoredIdbIndex>,
+ /// (JSON key, JSON value) in insertion order.
+ #[serde(default)]
+ records: Vec<(String, String)>,
+}
+
+#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
+struct StoredIdbIndex {
+ name: String,
+ key_path: String,
+ #[serde(default)]
+ unique: bool,
+}
+
+#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
+struct StoredIdbDatabase {
+ version: u64,
+ #[serde(default)]
+ stores: std::collections::BTreeMap<String, StoredIdbStore>,
+}
+
+#[derive(Default)]
+struct IndexedDbInner {
+ /// origin -> database name -> database.
+ origins: HashMap<String, HashMap<String, StoredIdbDatabase>>,
+}
+
+/// IndexedDB backing store, keyed by origin the same way `localStorage` is.
+///
+/// The shim in `bootstrap.js` used to hand every object store its own `Map`, so
+/// `createObjectStore` results were unreachable and a database's data died with
+/// the realm. Records live here instead, so they survive navigation and a
+/// profile reload.
+#[derive(Default)]
+pub struct IndexedDbStorage {
+ inner: std::sync::Mutex<IndexedDbInner>,
+}
+
+impl IndexedDbStorage {
+ fn lock(&self) -> std::sync::MutexGuard<'_, IndexedDbInner> {
+ self.inner.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
+ }
+
+ fn databases(&self, origin: &str) -> HashMap<String, StoredIdbDatabase> {
+ self.lock().origins.get(origin).cloned().unwrap_or_default()
+ }
+}
+
+/// Total records one origin may hold, so a runaway page cannot grow without
+/// bound inside one session.
+const IDB_ORIGIN_RECORD_LIMIT: usize = 100_000;
+
+fn idb_fail(message: &str) -> String {
+ let mut out = String::from("{\"ok\":false,\"error\":");
+ out.push_str(&serde_json::to_string(message).unwrap_or_else(|_| "\"error\"".to_string()));
+ out.push('}');
+ out
+}
+
+/// Handle one IndexedDB command. `payload` is a JSON object with at least a
+/// `cmd`; the reply is always a JSON object with `ok`, so the shim can tell a
+/// real failure from a malformed request.
+fn indexed_db_command(
+ storage: &Option<Arc<IndexedDbStorage>>,
+ origin: &str,
+ payload: &str,
+) -> String {
+ let Some(storage) = storage else {
+ return idb_fail("no IndexedDB storage is attached");
+ };
+ let Ok(request) = serde_json::from_str::<serde_json::Value>(payload) else {
+ return idb_fail("malformed IndexedDB request");
+ };
+ let command = request.get("cmd").and_then(|v| v.as_str()).unwrap_or("");
+ let db_name = request.get("db").and_then(|v| v.as_str()).unwrap_or("");
+ let store_name = request.get("store").and_then(|v| v.as_str()).unwrap_or("");
+
+ match command {
+ // Read the schema, and report whether an upgrade transaction is needed.
+ "open" => {
+ let requested = request
+ .get("version")
+ .and_then(|v| v.as_u64())
+ .unwrap_or(1)
+ .max(1);
+ let databases = storage.databases(origin);
+ let existing = databases.get(db_name);
+ let version = existing.map(|db| db.version).unwrap_or(0);
+ let stores = existing
+ .map(|db| {
+ serde_json::to_value(&db.stores).unwrap_or_else(|_| serde_json::Value::Null)
+ })
+ .unwrap_or_else(|| serde_json::json!({}));
+ return serde_json::json!({
+ "ok": true,
+ "exists": existing.is_some(),
+ "version": version,
+ "upgradeNeeded": existing.is_none() || requested > version,
+ "stores": stores,
+ })
+ .to_string();
+ }
+ // Write the schema and the version once an upgrade transaction finished.
+ "schema" => {
+ let version = request.get("version").and_then(|v| v.as_u64()).unwrap_or(1);
+ let stores: std::collections::BTreeMap<String, StoredIdbStore> = request
+ .get("stores")
+ .and_then(|v| serde_json::from_value(v.clone()).ok())
+ .unwrap_or_default();
+ let mut inner = storage.lock();
+ let entry = inner
+ .origins
+ .entry(origin.to_string())
+ .or_default()
+ .entry(db_name.to_string())
+ .or_default();
+ entry.version = version;
+ // Stores removed by the upgrade are dropped, and the rest keep their
+ // records unless the key path or key generator changed.
+ let dropped: Vec<String> = entry
+ .stores
+ .keys()
+ .filter(|name| !stores.contains_key(*name))
+ .cloned()
+ .collect();
+ for name in dropped {
+ entry.stores.remove(&name);
+ }
+ for (name, store) in stores {
+ match entry.stores.get_mut(&name) {
+ Some(existing) => {
+ if existing.key_path != store.key_path
+ || existing.auto_increment != store.auto_increment
+ {
+ *existing = StoredIdbStore {
+ key_path: store.key_path,
+ auto_increment: store.auto_increment,
+ indexes: store.indexes,
+ records: existing.records.clone(),
+ };
+ } else {
+ existing.indexes = store.indexes;
+ }
+ }
+ None => {
+ entry.stores.insert(name, store);
+ }
+ }
+ }
+ return serde_json::json!({ "ok": true }).to_string();
+ }
+ "put" => {
+ let key = request.get("key").cloned().unwrap_or(serde_json::Value::Null);
+ let value = request.get("value").cloned().unwrap_or(serde_json::Value::Null);
+ let key_json = key.to_string();
+ let value_json = value.to_string();
+ let mut inner = storage.lock();
+ let total: usize = inner
+ .origins
+ .get(origin)
+ .map(|databases| {
+ databases
+ .values()
+ .flat_map(|db| db.stores.values())
+ .map(|store| store.records.len())
+ .sum()
+ })
+ .unwrap_or(0);
+ let Some(store) = inner
+ .origins
+ .get_mut(origin)
+ .and_then(|databases| databases.get_mut(db_name))
+ .and_then(|db| db.stores.get_mut(store_name))
+ else {
+ return idb_fail("object store not found");
+ };
+ if let Some(slot) = store
+ .records
+ .iter_mut()
+ .find(|(existing, _)| *existing == key_json)
+ {
+ slot.1 = value_json;
+ return serde_json::json!({ "ok": true, "replaced": true }).to_string();
+ }
+ if total >= IDB_ORIGIN_RECORD_LIMIT {
+ return idb_fail("quota exceeded");
+ }
+ store.records.push((key_json, value_json));
+ serde_json::json!({ "ok": true, "replaced": false }).to_string()
+ }
+ "get" => {
+ let key_json = request
+ .get("key")
+ .map(|v| v.to_string())
+ .unwrap_or_else(|| "null".to_string());
+ let inner = storage.lock();
+ let store = inner
+ .origins
+ .get(origin)
+ .and_then(|databases| databases.get(db_name))
+ .and_then(|db| db.stores.get(store_name));
+ let found = store.and_then(|store| {
+ store
+ .records
+ .iter()
+ .find(|(key, _)| *key == key_json)
+ .map(|(_, value)| value.clone())
+ });
+ match found {
+ Some(value) => serde_json::json!({ "ok": true, "found": true, "value": value }).to_string(),
+ None => serde_json::json!({ "ok": true, "found": false }).to_string(),
+ }
+ }
+ "delete" => {
+ let key_json = request
+ .get("key")
+ .map(|v| v.to_string())
+ .unwrap_or_else(|| "null".to_string());
+ let mut inner = storage.lock();
+ let Some(store) = inner
+ .origins
+ .get_mut(origin)
+ .and_then(|databases| databases.get_mut(db_name))
+ .and_then(|db| db.stores.get_mut(store_name))
+ else {
+ return idb_fail("object store not found");
+ };
+ store.records.retain(|(key, _)| *key != key_json);
+ serde_json::json!({ "ok": true }).to_string()
+ }
+ "clear" => {
+ let mut inner = storage.lock();
+ if let Some(store) = inner
+ .origins
+ .get_mut(origin)
+ .and_then(|databases| databases.get_mut(db_name))
+ .and_then(|db| db.stores.get_mut(store_name))
+ {
+ store.records.clear();
+ }
+ serde_json::json!({ "ok": true }).to_string()
+ }
+ // Every read returns the whole store in one op call: getAll, getAllKeys,
+ // count and get are all projections of the same list, and a page that
+ // asks twice should not pay two round trips through V8.
+ "entries" => {
+ let inner = storage.lock();
+ let store = inner
+ .origins
+ .get(origin)
+ .and_then(|databases| databases.get(db_name))
+ .and_then(|db| db.stores.get(store_name));
+ let records = store.map(|store| store.records.clone()).unwrap_or_default();
+ serde_json::json!({
+ "ok": true,
+ "records": records
+ .into_iter()
+ .map(|(key, value)| serde_json::json!({ "key": key, "value": value }))
+ .collect::<Vec<_>>(),
+ "keyPath": store.and_then(|store| store.key_path.clone()),
+ })
+ .to_string()
+ }
+ "deleteDatabase" => {
+ let mut inner = storage.lock();
+ if let Some(databases) = inner.origins.get_mut(origin) {
+ databases.remove(db_name);
+ }
+ serde_json::json!({ "ok": true }).to_string()
+ }
+ "list" => {
+ let databases = storage.lock().origins.get(origin).cloned().unwrap_or_default();
+ let names: Vec<serde_json::Value> = databases
+ .into_iter()
+ .map(|(name, db)| serde_json::json!({ "name": name, "version": db.version }))
+ .collect();
+ serde_json::json!({ "ok": true, "databases": names }).to_string()
+ }
+ _ => idb_fail("unknown IndexedDB command"),
+ }
+}
+
pub struct ObscuraState {
pub dom: Option<DomTree>,
pub url: String,
@@ -167,6 +680,16 @@ pub struct ObscuraState {
pub navigation_timing: NavigationTiming,
pub blocked_urls: Vec<String>,
pub cookie_jar: Option<Arc<CookieJar>>,
+ /// BrowserContext-scoped `localStorage`. Shared by every page of one
+ /// context and keyed by origin, so a realm rebuild cannot lose it.
+ pub local_storage: Option<Arc<OriginStorage>>,
+ /// Browsing-context-scoped `sessionStorage`. Owned by the Page and keyed by
+ /// origin: an entry survives realm teardown on a same-origin navigation but
+ /// never leaves the tab (issue #678).
+ pub session_storage: Option<Arc<OriginStorage>>,
+ /// BrowserContext-scoped IndexedDB records and schema. Shared by every page
+ /// of one context and keyed by origin, so a realm rebuild cannot lose them.
+ pub indexed_db: Option<Arc<IndexedDbStorage>>,
pub http_client: Option<Arc<ObscuraHttpClient>>,
/// The owning page's passive on_request/on_response callbacks (issue
/// #408). Page-scoped, so scripted fetch()/XHR observation stays local to
@@ -398,6 +921,12 @@ pub struct PendingFrameMessage {
impl ObscuraState {
pub(crate) fn inherit_resources(&mut self, parent: &Self) {
self.cookie_jar = parent.cookie_jar.clone();
+ // A frame shares its page's Web Storage Arcs. The ops key by the frame
+ // realm's own document URL, so a cross-origin frame still lands in its
+ // own bucket instead of the top document's.
+ self.local_storage = parent.local_storage.clone();
+ self.session_storage = parent.session_storage.clone();
+ self.indexed_db = parent.indexed_db.clone();
self.http_client = parent.http_client.clone();
self.callbacks = parent.callbacks.clone();
self.encoding = parent.encoding.clone();
@@ -428,6 +957,9 @@ impl ObscuraState {
navigation_timing: NavigationTiming::default(),
blocked_urls: Vec::new(),
cookie_jar: None,
+ local_storage: Some(Arc::new(OriginStorage::default())),
+ session_storage: Some(Arc::new(OriginStorage::default())),
+ indexed_db: Some(Arc::new(IndexedDbStorage::default())),
http_client: None,
callbacks: None,
#[cfg(feature = "stealth")]
@@ -4486,7 +5018,9 @@ pub(crate) fn glob_match(pattern: &str, url: &str) -> bool {
#[cfg(test)]
mod tests {
use super::{
- FetchCredentials, ObscuraState, cors_response_allows, cors_unsafe_request_header_names,
+ FetchCredentials, LOCAL_STORAGE_ORIGIN_COUNT_LIMIT, LOCAL_STORAGE_ORIGIN_LIMIT,
+ LOCAL_STORAGE_TOTAL_LIMIT, ObscuraState, OriginStorage, cors_response_allows,
+ cors_unsafe_request_header_names,
glob_match, is_cors_safelisted_content_type, is_cors_safelisted_request_header,
parse_cors_header_list, preflight_allows_header, preflight_allows_method,
sanitize_redirect_headers, validate_fetch_url,
@@ -4494,6 +5028,111 @@ mod tests {
use crate::runtime::ObscuraJsRuntime;
use obscura_dom::parse_html;
+ // #678: Web Storage lives in Rust, keyed by origin, so these pin the
+ // behaviour the realm-local object could not provide.
+ #[test]
+ fn origin_storage_keeps_origins_apart_and_preserves_insertion_order() {
+ let store = OriginStorage::default();
+ assert!(store.set("https://a.example", "k1".into(), "one".into()));
+ assert!(store.set("https://a.example", "k2".into(), "two".into()));
+ assert!(store.set("https://b.example", "k1".into(), "other".into()));
+
+ // Storage.key() is defined in insertion order, not sorted order.
+ let order: Vec<String> = store
+ .snapshot("https://a.example")
+ .into_iter()
+ .map(|(key, _)| key)
+ .collect();
+ assert_eq!(order, vec!["k1".to_string(), "k2".to_string()]);
+
+ assert_eq!(store.get("https://a.example", "k1"), Some("one".to_string()));
+ assert_eq!(store.get("https://b.example", "k1"), Some("other".to_string()));
+ assert_eq!(store.get("https://c.example", "k1"), None);
+ }
+
+ #[test]
+ fn origin_storage_set_replaces_in_place_without_growing_the_quota() {
+ let store = OriginStorage::default();
+ let origin = "https://a.example";
+ assert!(store.set(origin, "k".into(), "x".repeat(1024).into()));
+ // Overwriting an existing key must not count the old bytes twice: a
+ // replacement stays within quota where a second key of the same size
+ // would still fit, and the entry count must not change.
+ assert!(store.set(origin, "k".into(), "y".repeat(1024).into()));
+ assert_eq!(store.snapshot(origin).len(), 1);
+ assert_eq!(store.get(origin, "k").map(|v| v.len()), Some(1024));
+
+ // A single value over the per-origin limit is rejected, and the
+ // rejected write leaves the store untouched.
+ let too_big = "z".repeat(LOCAL_STORAGE_ORIGIN_LIMIT + 1);
+ assert!(!store.set(origin, "big1".into(), too_big));
+ assert_eq!(store.snapshot(origin).len(), 1);
+ assert_eq!(store.get(origin, "k").map(|v| v.len()), Some(1024));
+ }
+
+ #[test]
+ fn origin_storage_remove_and_clear_return_the_quota() {
+ let store = OriginStorage::default();
+ let origin = "https://a.example";
+ assert!(store.set(origin, "k1".into(), "x".repeat(2048).into()));
+ assert!(store.set(origin, "k2".into(), "x".repeat(2048).into()));
+
+ store.remove(origin, "k1");
+ assert_eq!(store.get(origin, "k1"), None);
+ // The freed bytes are usable again, which is the part a naive counter
+ // gets wrong.
+ assert!(store.set(origin, "k3".into(), "x".repeat(2048).into()));
+
+ store.clear(origin);
+ assert!(store.snapshot(origin).is_empty());
+ assert!(store.set(origin, "after-clear".into(), "small".into()));
+ }
+
+ #[test]
+ fn origin_storage_total_and_origin_count_limits_are_enforced() {
+ let store = OriginStorage::default();
+
+ // Distinct origins share one total budget.
+ let per_origin = LOCAL_STORAGE_TOTAL_LIMIT / LOCAL_STORAGE_ORIGIN_COUNT_LIMIT + 1024;
+ let mut rejected = 0;
+ for index in 0..LOCAL_STORAGE_ORIGIN_COUNT_LIMIT {
+ let origin = format!("https://o{index}.example");
+ if !store.set(&origin, "k".into(), "q".repeat(per_origin).into()) {
+ rejected += 1;
+ }
+ }
+ assert!(
+ rejected > 0,
+ "the total budget must stop writes once {LOCAL_STORAGE_TOTAL_LIMIT} bytes are used"
+ );
+
+ // And the origin count is capped even when each origin is tiny.
+ let store = OriginStorage::default();
+ for index in 0..LOCAL_STORAGE_ORIGIN_COUNT_LIMIT {
+ assert!(store.set(&format!("https://o{index}.example"), "k".into(), "v".into()));
+ }
+ assert!(
+ !store.set("https://one-too-many.example", "k".into(), "v".into()),
+ "an origin past the count limit must be rejected"
+ );
+ }
+
+ #[test]
+ fn clearing_an_origin_marks_it_changed() {
+ let store = OriginStorage::default();
+ let origin = "https://a.example";
+ assert!(store.set(origin, "k".into(), "v".into()));
+ store.take_changed();
+ assert!(!store.is_dirty());
+ store.clear(origin);
+ assert!(store.is_dirty(), "a clear must mark the store dirty");
+ assert_eq!(
+ store.changed_origins(),
+ vec![origin.to_string()],
+ "a clear must name the origin so its file is removed, not left behind"
+ );
+ }
+
// #967 — a redirect must not forward the caller's credentials to a
// different origin, and a 301/302/303 GET downgrade drops the body headers.
#[test]
@@ -5637,6 +6276,104 @@ fn op_get_cookies(scope: &mut v8::PinScope, state: &OpState) -> String {
jar.get_js_visible_cookies(&url)
}
+/// Origin of the calling realm's document. A cross-origin frame must land in
+/// its own origin's bucket rather than the top document's, so this resolves the
+/// realm that made the call instead of reading page state directly.
+fn storage_origin(state: &ObscuraState) -> String {
+ state.inherited_origin.clone().unwrap_or_else(|| {
+ url::Url::parse(&state.url)
+ .map(|url| url.origin().ascii_serialization())
+ .unwrap_or_else(|_| "null".to_string())
+ })
+}
+
+fn origin_storage_command(
+ storage: &Option<Arc<OriginStorage>>,
+ origin: &str,
+ command: &str,
+ key: &str,
+ value: &str,
+) -> String {
+ let Some(storage) = storage else {
+ return "null".to_string();
+ };
+
+ match command {
+ "snapshot" => serde_json::to_string(&storage.snapshot(origin))
+ .unwrap_or_else(|_| "[]".to_string()),
+ "get" => serde_json::to_string(&storage.get(origin, key))
+ .unwrap_or_else(|_| "null".to_string()),
+ "set" => storage.set(origin, key.to_string(), value.to_string()).to_string(),
+ "remove" => {
+ storage.remove(origin, key);
+ "true".to_string()
+ }
+ "clear" => {
+ storage.clear(origin);
+ "true".to_string()
+ }
+ _ => "null".to_string(),
+ }
+}
+
+/// `localStorage` backend. Returns JSON: an array of `[key, value]` pairs for
+/// "snapshot", a string or null for "get", and a boolean for the mutations so
+/// the shim can raise `QuotaExceededError` exactly where a browser would.
+#[op2]
+#[string]
+fn op_local_storage(
+ scope: &mut v8::PinScope,
+ state: &OpState,
+ #[string] command: &str,
+ #[string] key: &str,
+ #[string] value: &str,
+) -> String {
+ let gs = realm_state(scope, state);
+ let gs = gs.borrow();
+ origin_storage_command(
+ &gs.local_storage,
+ &storage_origin(&gs),
+ command,
+ key,
+ value,
+ )
+}
+
+/// IndexedDB backend. One command per call, JSON in and JSON out, so the shim
+/// keeps the spec's object graph and only the data lives in Rust.
+#[op2]
+#[string]
+fn op_indexed_db(
+ scope: &mut v8::PinScope,
+ state: &OpState,
+ #[string] payload: &str,
+) -> String {
+ let gs = realm_state(scope, state);
+ let gs = gs.borrow();
+ indexed_db_command(&gs.indexed_db, &storage_origin(&gs), payload)
+}
+
+/// `sessionStorage` backend, page-scoped in exactly the same way.
+#[op2]
+#[string]
+fn op_session_storage(
+ scope: &mut v8::PinScope,
+ state: &OpState,
+ #[string] command: &str,
+ #[string] key: &str,
+ #[string] value: &str,
+) -> String {
+ let gs = realm_state(scope, state);
+ let gs = gs.borrow();
+ origin_storage_command(
+ &gs.session_storage,
+ &storage_origin(&gs),
+ command,
+ key,
+ value,
+ )
+}
+
#[op2(fast)]
fn op_set_cookie(scope: &mut v8::PinScope, state: &OpState, #[string] cookie_str: &str) {
let gs = realm_state(scope, state);
@@ -6881,6 +7618,9 @@ pub fn build_extension() -> Extension {
op_fetch_body(),
op_get_cookies(),
op_set_cookie(),
+ op_local_storage(),
+ op_session_storage(),
+ op_indexed_db(),
op_navigate(),
op_session_history(),
op_history_traverse(),
diff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rs
index 462153a3..87a9cd95 100644
--- a/crates/obscura-js/src/runtime.rs
+++ b/crates/obscura-js/src/runtime.rs
@@ -20,7 +20,7 @@ use crate::module_loader::{ModuleLoadActivity, ObscuraModuleLoader};
#[cfg(all(test, feature = "render"))]
use crate::ops::ensure_prepared_render;
use crate::ops::{
- ObscuraState, RuntimeEvent, StoredNetworkResponseBody,
+ IndexedDbStorage, ObscuraState, OriginStorage, RuntimeEvent, StoredNetworkResponseBody,
begin_animation_task, build_extension, node_is_script,
};
#[cfg(feature = "render")]
@@ -1168,6 +1168,25 @@ impl ObscuraJsRuntime {
self.state.borrow_mut().cookie_jar = Some(jar);
}
+ /// Install the context-scoped `localStorage` backing store. The Arc lives on
+ /// the BrowserContext, so entries outlive the V8 realm that wrote them.
+ pub fn set_local_storage(&self, storage: std::sync::Arc<OriginStorage>) {
+ self.state.borrow_mut().local_storage = Some(storage);
+ }
+
+ /// Install the page-owned `sessionStorage` backing store, so an entry
+ /// survives realm teardown on a same-origin navigation and on CDP target
+ /// switching while staying inside the tab (issue #678).
+ pub fn set_session_storage(&self, storage: std::sync::Arc<OriginStorage>) {
+ self.state.borrow_mut().session_storage = Some(storage);
+ }
+
+ /// Install the context-scoped IndexedDB backing store, so records and the
+ /// schema outlive the realm that wrote them.
+ pub fn set_indexed_db(&self, storage: std::sync::Arc<IndexedDbStorage>) {
+ self.state.borrow_mut().indexed_db = Some(storage);
+ }
+
pub fn set_http_client(&self, client: std::sync::Arc<obscura_net::ObscuraHttpClient>) {
let mut state = self.state.borrow_mut();
state.http_client = Some(client);
diff --git a/crates/obscura-mcp/src/lib.rs b/crates/obscura-mcp/src/lib.rs
index 1bde0238..b1c9de39 100644
--- a/crates/obscura-mcp/src/lib.rs
+++ b/crates/obscura-mcp/src/lib.rs
@@ -82,11 +82,23 @@ pub struct BrowserState {
impl BrowserState {
pub fn new(proxy: Option<String>, user_agent: Option<String>, stealth: bool) -> Self {
+ // `--storage-dir` is a global flag, so the profile arrives through the
+ // environment rather than through every constructor call. Without this
+ // the MCP path silently ignored the flag and persisted nothing, cookies
+ // included.
+ let storage_dir = std::env::var_os("OBSCURA_STORAGE_DIR").map(std::path::PathBuf::from);
+ let context = BrowserContext::with_storage_full(
+ "mcp".to_string(),
+ proxy,
+ stealth,
+ None,
+ storage_dir,
+ );
BrowserState {
tabs: std::collections::BTreeMap::new(),
active_tab: None,
tab_counter: 0,
- context: Arc::new(BrowserContext::with_options("mcp".to_string(), proxy, stealth)),
+ context: Arc::new(context),
user_agent,
operator_network_hints: false,
console_messages: Vec::new(),
@@ -246,6 +258,8 @@ pub async fn run(proxy: Option<String>, user_agent: Option<String>, stealth: boo
let mut state = BrowserState::new(proxy, user_agent, stealth);
state.operator_network_hints = true;
+ // Cookies and Web Storage are written on every navigation; this covers the
+ // writes an agent makes after a page has settled, on the way out.
let mut runtime_pump_armed = false;
loop {
@@ -273,6 +287,7 @@ pub async fn run(proxy: Option<String>, user_agent: Option<String>, stealth: boo
continue;
};
if n == 0 {
+ state.context.save_storage();
return Ok(());
}
@@ -415,11 +430,25 @@ fn handle_tools_list(id: Value) -> RpcResponse {
"inputSchema": {
"type": "object",
"properties": {
- "expression": { "type": "string", "description": "JavaScript expression to evaluate" }
+ "expression": { "type": "string", "description": "JavaScript expression to evaluate; a promise it returns is awaited" },
+ "timeoutMs": { "type": "number", "description": "How long to wait for a returned promise, in milliseconds (default: 5000)" }
},
"required": ["expression"]
}
},
+ {
+ "name": "browser_wait_for_function",
+ "description": "Wait until a JavaScript expression returns true, polling the page",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "function": { "type": "string", "description": "JavaScript expression that must become truthy" },
+ "timeout": { "type": "number", "description": "Timeout in milliseconds (default: 30000)" },
+ "pollIntervalMs": { "type": "number", "description": "Poll interval in milliseconds (default: 100)" }
+ },
+ "required": ["function"]
+ }
+ },
{
"name": "browser_wait_for",
"description": "Wait for a CSS selector to appear in the DOM",
@@ -771,6 +800,7 @@ async fn handle_tool_call(id: Value, params: &Value, state: &mut BrowserState) -
"browser_select_option" => tool_select_option(args, state),
"browser_evaluate" => tool_evaluate(args, state).await,
"browser_wait_for" => tool_wait_for(args, state).await,
+ "browser_wait_for_function" => tool_wait_for_function(args, state).await,
"browser_network_requests" => tool_network_requests(state),
"browser_console_messages" => tool_console_messages(state),
"browser_close" => tool_close(state),
@@ -1136,11 +1166,104 @@ fn tool_select_option(args: &Value, state: &mut BrowserState) -> Result<String,
}
}
+/// Wrap an expression so a thenable it returns can be polled to settlement.
+/// Separate from the polling loop so its shape can be asserted directly: a
+/// wrapper that dereferences its slot before creating it turns every
+/// synchronous expression into "did not settle".
+fn expression_wrapper(expression: &str) -> String {
+ const SLOT: &str = "__obscura_mcp_expression";
+ format!(
+ r#"(function() {{
+ var slot = globalThis.{SLOT} || (globalThis.{SLOT} = {{}});
+ slot.state = 'pending';
+ try {{
+ var value = ({expression});
+ if (value && typeof value.then === 'function') {{
+ value.then(
+ function (resolved) {{ slot.state = 'done'; slot.value = resolved; }},
+ function (rejected) {{ slot.state = 'failed'; slot.error = String(rejected); }}
+ );
+ return null;
+ }}
+ slot.state = 'sync';
+ slot.value = value;
+ return null;
+ }} catch (e) {{ slot.state = 'sync'; slot.value = null; slot.error = String(e); return null; }}
+ }})()"#,
+ SLOT = SLOT,
+ expression = expression,
+ )
+}
+/// Resolve a promise that a page expression produced.
+///
+/// `Page::evaluate` is synchronous, so an agent that wrote `await fetch(...)`
+/// or an async IIFE used to get `{}` back and no way to tell that from an empty
+/// object. The expression is evaluated once, and if the result is a thenable its
+/// settlement is polled until it resolves, fails, or the timeout runs out.
+async fn settle_expression_promise(
+ state: &mut BrowserState,
+ expression: &str,
+ timeout: std::time::Duration,
+) -> Option<Value> {
+ let wrapped = expression_wrapper(expression);
+ const SLOT: &str = "__obscura_mcp_expression";
+ let seed = state.page_mut().evaluate(&wrapped);
+ if seed.is_null() && !state.page_mut().has_js() {
+ // No realm: nothing can produce a thenable here.
+ return None;
+ }
+ let deadline = std::time::Instant::now() + timeout;
+ let mut last: Option<Value> = None;
+ loop {
+ let snapshot = state.page_mut().evaluate(&format!(
+ "JSON.stringify((function() {{ var s = globalThis.{SLOT}; return s ? {{state: s.state, value: s.value, error: s.error}} : null; }})())"
+ ));
+ let parsed = snapshot
+ .as_str()
+ .and_then(|raw| serde_json::from_str::<Value>(raw).ok());
+ if let Some(slot) = parsed {
+ match slot.get("state").and_then(Value::as_str) {
+ Some("pending") => last = slot.get("value").cloned(),
+ Some("sync") => return slot.get("value").cloned(),
+ Some("done") => return slot.get("value").cloned(),
+ Some("failed") => return Some(Value::String(
+ slot.get("error").and_then(Value::as_str).unwrap_or("rejected").to_string(),
+ )),
+ _ => {}
+ }
+ }
+ if std::time::Instant::now() >= deadline {
+ return Some(Value::String(format!(
+ "{{\"error\":\"the expression did not settle within {} ms\"}}",
+ timeout.as_millis()
+ )));
+ }
+ tokio::time::sleep(std::time::Duration::from_millis(20)).await;
+ // A promise that settles in a network callback needs the page's own
+ // task queue to turn. Polling evaluate alone leaves it pending forever,
+ // which is how `await fetch(...)` looked like a hang.
+ let _ = state.advance_active_page_tasks().await;
+ let _ = last;
+ }
+}
+
async fn tool_evaluate(args: &Value, state: &mut BrowserState) -> Result<String, String> {
let expression = args.get("expression").and_then(Value::as_str)
.ok_or("Missing expression parameter")?;
-
- let result = state.page_mut().evaluate(expression);
+ let timeout_ms = args.get("timeoutMs").and_then(Value::as_u64).unwrap_or(5_000);
+
+ let result = match settle_expression_promise(
+ state,
+ expression,
+ std::time::Duration::from_millis(timeout_ms),
+ )
+ .await
+ {
+ Some(value) => value,
+ // Fall back to the synchronous reading if the promise machinery was
+ // unavailable, so this can only ever return more than before.
+ None => state.page_mut().evaluate(expression),
+ };
state.settle_synthetic_navigation().await?;
Ok(match &result {
Value::String(s) => s.clone(),
@@ -1149,6 +1272,41 @@ async fn tool_evaluate(args: &Value, state: &mut BrowserState) -> Result<String,
})
}
+/// Poll a JavaScript predicate until it returns something truthy.
+///
+/// Agents otherwise express "wait until the app finished loading" as a loop of
+/// `browser_evaluate` plus a sleep, which costs a round trip per iteration and
+/// is where flaky automation comes from.
+async fn tool_wait_for_function(args: &Value, state: &mut BrowserState) -> Result<String, String> {
+ let expression = args.get("function").or_else(|| args.get("expression"))
+ .and_then(Value::as_str)
+ .ok_or("Missing function parameter")?;
+ let timeout_ms = args.get("timeout").and_then(Value::as_u64).unwrap_or(30_000);
+ let poll_ms = args.get("pollIntervalMs").and_then(Value::as_u64).unwrap_or(100).max(10);
+
+ let deadline = tokio::time::Instant::now() + tokio::time::Duration::from_millis(timeout_ms);
+ let mut attempts: u64 = 0;
+ loop {
+ attempts += 1;
+ let value = state
+ .page_mut()
+ .evaluate(&format!("JSON.stringify((function(){{ try {{ return (function(){{ return !!({expression}); }})(); }} catch (e) {{ return false; }} }})())"));
+ let truthy = value
+ .as_str()
+ .map(|raw| raw == "true")
+ .unwrap_or(value.as_bool().unwrap_or(false));
+ if truthy {
+ return Ok(format!("condition met after {attempts} poll(s)"));
+ }
+ if tokio::time::Instant::now() >= deadline {
+ return Err(format!(
+ "condition not met within {timeout_ms} ms after {attempts} poll(s): {expression}"
+ ));
+ }
+ tokio::time::sleep(tokio::time::Duration::from_millis(poll_ms)).await;
+ }
+}
+
async fn tool_wait_for(args: &Value, state: &mut BrowserState) -> Result<String, String> {
let selector = args.get("selector").and_then(Value::as_str)
.ok_or("Missing selector parameter")?;
@@ -2063,19 +2221,39 @@ fn tool_storage_state(state: &mut BrowserState) -> Result<String, String> {
"same_site": c.same_site,
"expires": c.expires,
})).collect();
- // Pull localStorage + sessionStorage for the current page's origin.
+ // Web Storage now lives in the context, so every origin the browser has
+ // seen is reported, not only the page's current one. That is the whole point
+ // of an exported session state: an agent stashes it and restores it later.
let storage_js = r#"(function(){
var ls = [], ss = [];
try { for (var i = 0; i < localStorage.length; i++) { var k = localStorage.key(i); ls.push([k, localStorage.getItem(k)]); } } catch(e) {}
try { for (var j = 0; j < sessionStorage.length; j++) { var k2 = sessionStorage.key(j); ss.push([k2, sessionStorage.getItem(k2)]); } } catch(e) {}
return { origin: location.origin || '', localStorage: ls, sessionStorage: ss };
})()"#;
- let storage = if state.active_tab.is_some() {
- state.page_mut().evaluate(storage_js)
- } else {
- Value::Null
- };
- let origins = if storage.is_object() { vec![storage] } else { vec![] };
+ let mut origins: Vec<Value> = Vec::new();
+ if state.active_tab.is_some() {
+ let storage = state.page_mut().evaluate(storage_js);
+ if storage.is_object() {
+ origins.push(storage);
+ }
+ }
+ // Any origin written by a page that has since navigated away still counts.
+ for (origin, entries) in state.context.local_storage.entries() {
+ if entries.is_empty() {
+ continue;
+ }
+ if origins
+ .iter()
+ .any(|entry| entry.get("origin").and_then(Value::as_str) == Some(origin.as_str()))
+ {
+ continue;
+ }
+ origins.push(json!({
+ "origin": origin,
+ "localStorage": entries,
+ "sessionStorage": [],
+ }));
+ }
let out = json!({ "cookies": cookies, "origins": origins });
serde_json::to_string_pretty(&out).map_err(|e| e.to_string())
}
@@ -2150,6 +2328,24 @@ fn tool_set_storage_state(args: &Value, state: &mut BrowserState) -> Result<Stri
mod tests {
use super::*;
+ // The promise wrapper has to work on a page that has never been evaluated
+ // on: the slot is created lazily, so the first synchronous expression must
+ // not throw on an undefined global. This caught a regression where every
+ // browser_evaluate answered "the expression did not settle".
+ #[test]
+ fn expression_promise_wrapper_creates_its_slot_before_writing_to_it() {
+ let wrapped = expression_wrapper("1 + 1");
+ // A wrapper that dereferences the slot before creating it throws on the
+ // first synchronous expression, which surfaced as every
+ // browser_evaluate answering "the expression did not settle".
+ assert!(
+ wrapped.contains("globalThis.__obscura_mcp_expression || (globalThis.__obscura_mcp_expression = {})"),
+ "the slot must be created on demand: {wrapped}"
+ );
+ assert!(wrapped.contains("slot.state = 'sync'"), "sync results must be recorded: {wrapped}");
+ assert!(wrapped.contains("typeof value.then === 'function'"), "thenables must be awaited: {wrapped}");
+ }
+
// #1015: case-folding can change byte length (Turkish "İ" -> "i̇"), so a
// match offset found in the lowercased haystack must be translated back to
// the original body's byte offset.
diff --git a/docs/Architecture-overview.md b/docs/Architecture-overview.md
index c0172dcb..16ed9f91 100644
--- a/docs/Architecture-overview.md
+++ b/docs/Architecture-overview.md
@@ -137,7 +137,7 @@ init → commit → domcontentloaded → load → networkidle2 → networkidle0
## Storage
-`--storage-dir` persists cookies (`cookies.json`) and localStorage (`localStorage/<origin>.json`). Reads on process start, writes on every navigation and on graceful shutdown.
+`--storage-dir` persists cookies to `cookies.json` and `localStorage` to `localStorage/<origin>-<digest>.json`: read on process start, written after each navigation that changed something and on graceful shutdown. `sessionStorage` is origin-keyed in memory only, per tab.
## Stealth
diff --git a/docs/Persist-cookies-and-storage.md b/docs/Persist-cookies-and-storage.md
index fe942453..153f31f0 100644
--- a/docs/Persist-cookies-and-storage.md
+++ b/docs/Persist-cookies-and-storage.md
@@ -1,4 +1,4 @@
-`--storage-dir` persists cookies and localStorage to disk so they survive across runs.
+`--storage-dir` persists cookies and `localStorage` so they survive across runs.
## CLI
@@ -7,7 +7,7 @@ obscura fetch https://example.com --storage-dir ./obscura-data
obscura fetch https://example.com --storage-dir ./obscura-data
```
-The second invocation starts with the cookies and localStorage left by the first.
+The second invocation starts with the cookies and `localStorage` left by the first.
## Server
@@ -17,12 +17,26 @@ obscura serve --storage-dir ./obscura-data
All CDP sessions read and write to the same directory. Run separate `obscura serve` processes with different `--storage-dir` paths for isolated profiles.
+`--storage-dir` is a global flag, so it applies to `obscura mcp` as well. The MCP
+server picks it up from `OBSCURA_STORAGE_DIR`, which `obscura mcp` sets from the
+flag, and it flushes the profile on exit.
+
## Layout
Inside `./obscura-data`:
- `cookies.json`: cookie jar in a stable format with `same_site`, `expires`, `http_only`, `secure`.
-- `localStorage/<origin>.json`: one file per origin.
+- `localStorage/<origin>-<digest>.json`: one file per origin, holding
+ `{"origin": "...", "entries": [["key", "value"], ...]}`. The digest is an FNV-1a
+ hash of the origin, so two origins that sanitize to the same filename cannot
+ collide. Entries stay in insertion order because `Storage.key(i)` is defined
+ in insertion order.
+
+Inspect one with `jq`:
+
+```bash
+jq '.entries' ./obscura-data/localStorage/*.json
+```
The format is stable. Inspect with `jq`:
@@ -32,10 +46,16 @@ jq '.[] | select(.domain == "example.com")' ./obscura-data/cookies.json
## When state is written
+- After every navigation completes (CDP `Page.navigate`, MCP `browser_navigate`),
+ and only when something actually changed.
- On clean process exit (Ctrl-C, SIGTERM).
-- After every navigation completes (CDP `Page.navigate`).
- Manually via CDP `Network.setCookie` and `Network.deleteCookies`.
+`sessionStorage` is deliberately not written to disk. It belongs to one tab and
+is dropped when the tab goes away, the same as a real browser, but it does
+survive navigation and CDP target switching within the process
+([#678](https://github.com/h4ckf0r0day/obscura/issues/678)).
+
## Login once, scrape many
```bash