Skip to content

The headless browser for AI agents and web scraping

Fix replaceable window origin and bounded asynchronous PBKDF2

SGavrlc0495ed86ab3
diff --git a/crates/obscura-js/js/bootstrap.js b/crates/obscura-js/js/bootstrap.js
index 721f3fd4..43c314c4 100644
--- a/crates/obscura-js/js/bootstrap.js
+++ b/crates/obscura-js/js/bootstrap.js
@@ -8066,6 +8066,30 @@ Object.defineProperty(globalThis, 'location', {
enumerable: true,
});
+// Window.origin is replaceable and reads the document origin, including
+// inherited about:blank/srcdoc origins, rather than a pending navigation URL.
+const _windowOriginDescriptor = Object.getOwnPropertyDescriptor({
+ get origin() {
+ if (this === globalThis) return _realmOrigin();
+ const get = _documentRealmMember(this, 'windowOrigin');
+ if (get) return get.call(this);
+ throw new TypeError('Illegal invocation');
+ },
+ set origin(value) {
+ if (this !== globalThis) {
+ const set = _documentRealmMember(this, 'setWindowOrigin');
+ if (set) return set.call(this, value);
+ throw new TypeError('Illegal invocation');
+ }
+ Object.defineProperty(this, 'origin', {
+ value, writable: true, enumerable: true, configurable: true,
+ });
+ },
+}, 'origin');
+_markNative(_windowOriginDescriptor.get);
+_markNative(_windowOriginDescriptor.set);
+Object.defineProperty(globalThis, 'origin', _windowOriginDescriptor);
+
globalThis.window = globalThis;
globalThis.self = globalThis;
globalThis.top = globalThis;
@@ -17502,6 +17526,13 @@ if (!globalThis.crypto.subtle) {
throw new DOMException(String((e && e.message) || e), "OperationError");
}
}
+ async function runOpAsync(fn) {
+ try { return await fn(); }
+ catch (e) {
+ if (e instanceof DOMException) throw e;
+ throw new DOMException(String((e && e.message) || e), "OperationError");
+ }
+ }
// The JWK `alg` of an AES or HMAC key, or undefined for the others.
function jwkAlg(key, bytes) {
@@ -17627,7 +17658,7 @@ if (!globalThis.crypto.subtle) {
const hash = normalizeHash(alg.hash);
const salt = toBytes(alg.salt);
const iterations = alg.iterations >>> 0;
- return bufferOf(runOp(() => __obscuraCore.ops.op_subtle_pbkdf2(hash, bytes, salt, iterations, lenBytes)));
+ return bufferOf(await runOpAsync(() => __obscuraCore.ops.op_subtle_pbkdf2(hash, bytes, salt, iterations, lenBytes)));
}
if (alg.name === "HKDF") {
const hash = normalizeHash(alg.hash);
@@ -18790,6 +18821,8 @@ const _documentMembers = Object.freeze(Object.fromEntries([
}],
['checkVisibility', Element.prototype.checkVisibility],
['elementStyle', function() { return _elementStyle(this); }],
+ ['windowOrigin', _windowOriginDescriptor.get],
+ ['setWindowOrigin', _windowOriginDescriptor.set],
]));
globalThis.__obscura_init_frames = function() {
diff --git a/crates/obscura-js/src/ops.rs b/crates/obscura-js/src/ops.rs
index 66f68a7e..7536e7dc 100644
--- a/crates/obscura-js/src/ops.rs
+++ b/crates/obscura-js/src/ops.rs
@@ -5188,7 +5188,8 @@ mod tests {
use super::read_body_capped;
use super::url_set_inner;
- use super::{PBKDF2_MAX_ITERATIONS, PBKDF2_MAX_OUTPUT_BYTES, pbkdf2_derive, push_capped};
+ use super::{PBKDF2_MAX_ITERATIONS, PBKDF2_MAX_OUTPUT_BYTES, pbkdf2_blocks, pbkdf2_can_inline, pbkdf2_derive,
+ pbkdf2_derive_with, validate_pbkdf2, CancelPbkdf2OnDrop, push_capped};
use super::{intercept_fulfill_response, visible_response_headers};
use base64::{Engine as _, engine::general_purpose::STANDARD as FULFILL_BASE64};
@@ -5475,6 +5476,76 @@ mod tests {
assert_eq!(dk.len(), 32, "derived key must have the requested length");
}
+ #[test]
+ fn pbkdf2_bounds_the_combined_work_before_deriving() {
+ let error = validate_pbkdf2("SHA-1", PBKDF2_MAX_ITERATIONS, PBKDF2_MAX_OUTPUT_BYTES)
+ .expect_err("iteration and output caps alone must not permit unbounded work");
+ assert!(error.to_string().contains("work"), "{error}");
+ assert!(validate_pbkdf2("SHA-256", PBKDF2_MAX_ITERATIONS, 32).is_ok());
+ assert!(validate_pbkdf2("SHA-256", 0, 32).is_err());
+ }
+
+ #[test]
+ fn pbkdf2_native_fast_path_is_bounded_by_work_and_input_size() {
+ assert!(pbkdf2_can_inline(4096, 512, 512));
+ assert!(!pbkdf2_can_inline(4097, 8, 8));
+ assert!(!pbkdf2_can_inline(1, 512, 513));
+ assert!(!pbkdf2_can_inline(1, usize::MAX, 1));
+ }
+
+ #[test]
+ fn pbkdf2_cancelled_work_stops_even_with_few_or_no_output_blocks() {
+ let cancelled = std::sync::atomic::AtomicBool::new(true);
+ for iterations in [1, 2, 4096, 4097, PBKDF2_MAX_ITERATIONS] {
+ for length in [0, 32, 65] {
+ let error = pbkdf2_derive_with(
+ "SHA-256", b"password", b"salt", iterations, length, &cancelled,
+ ).expect_err("cancellation must be checked before every derivation");
+ assert!(error.to_string().contains("cancelled"), "{error}");
+ }
+ }
+ }
+
+ #[test]
+ fn pbkdf2_block_boundary_checks_cancellation_below_the_round_interval() {
+ let cancelled = std::sync::atomic::AtomicBool::new(true);
+ let mut output = [7; 65];
+ assert!(!pbkdf2_blocks::<hmac::Hmac<sha2::Sha256>>(
+ b"password", b"salt", 1, &mut output, &cancelled,
+ ));
+ assert_eq!(output, [7; 65], "cancelled work must not start its first block");
+ }
+
+ #[test]
+ fn pbkdf2_blocks_match_existing_primitives_and_rfc6070() {
+ let derived = pbkdf2_derive("SHA-1", b"password", b"salt", 4096, 20).unwrap();
+ let hex: String = derived.iter().map(|byte| format!("{byte:02x}")).collect();
+ assert_eq!(hex, "4b007901b765489abead49d926f721d065a429c1");
+ for (hash, length) in [("SHA-1", 45), ("SHA-256", 70), ("SHA-384", 49), ("SHA-512", 130)] {
+ for iterations in [1, 2, 5000] {
+ let derived = pbkdf2_derive(hash, b"password", b"salt", iterations, length).unwrap();
+ let mut expected = vec![0; length as usize];
+ match hash {
+ "SHA-1" => pbkdf2::pbkdf2_hmac::<sha1::Sha1>(b"password", b"salt", iterations, &mut expected),
+ "SHA-256" => pbkdf2::pbkdf2_hmac::<sha2::Sha256>(b"password", b"salt", iterations, &mut expected),
+ "SHA-384" => pbkdf2::pbkdf2_hmac::<sha2::Sha384>(b"password", b"salt", iterations, &mut expected),
+ "SHA-512" => pbkdf2::pbkdf2_hmac::<sha2::Sha512>(b"password", b"salt", iterations, &mut expected),
+ _ => unreachable!(),
+ }
+ assert_eq!(derived, expected, "{hash}, iterations={iterations}, length={length}");
+ }
+ }
+ }
+
+ #[test]
+ fn dropping_a_pbkdf2_waiter_signals_cancellation() {
+ let cancelled = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
+ let guard = CancelPbkdf2OnDrop(cancelled.clone());
+ assert!(!cancelled.load(std::sync::atomic::Ordering::Relaxed));
+ drop(guard);
+ assert!(cancelled.load(std::sync::atomic::Ordering::Relaxed));
+ }
+
// HKDF and the CSPRNG draw share the same DoS shape: both size an output
// buffer straight from an untrusted u32 length. Each must reject a length
// above its fixed maximum before allocating, and still work for ordinary
@@ -7227,24 +7298,24 @@ fn op_subtle_jwk_parse(#[buffer] bytes: &[u8]) -> Result<serde_json::Value, deno
parse_jwk(bytes)
}
-/// Generous upper bounds on PBKDF2 parameters. WebCrypto imposes no limit, but
-/// page JS drives this op on the single-threaded runtime: an unbounded
-/// iteration count pins the V8 isolate (blocking every other CDP command on the
-/// connection) and a huge output length forces an unbounded `vec![0u8; length]`
-/// allocation. Both caps sit far above any legitimate use — OWASP recommends
-/// ~600k iterations and derived keys are tens of bytes.
+/// Bound page-controlled PBKDF2 CPU work and output allocation. Normal derived
+/// keys use tens of bytes; each hash-sized output block repeats every round.
const PBKDF2_MAX_ITERATIONS: u32 = 10_000_000;
const PBKDF2_MAX_OUTPUT_BYTES: u32 = 1024 * 1024;
+const PBKDF2_MAX_WORK: u64 = 1_000_000_000;
-/// PBKDF2 key derivation with DoS guards. Split out from the op so the bounds
-/// are unit-testable without the `#[op2]` wrapper.
-fn pbkdf2_derive(
+fn pbkdf2_can_inline(work: u64, password_length: usize, salt_length: usize) -> bool {
+ work <= 4096 && password_length.saturating_add(salt_length) <= 1024
+}
+
+fn validate_pbkdf2(
hash: &str,
- password: &[u8],
- salt: &[u8],
iterations: u32,
length: u32,
-) -> Result<Vec<u8>, deno_error::JsErrorBox> {
+) -> Result<u64, deno_error::JsErrorBox> {
+ if iterations == 0 {
+ return Err(crypto_err("PBKDF2 iteration count must be positive"));
+ }
if iterations > PBKDF2_MAX_ITERATIONS {
return Err(crypto_err(format!(
"PBKDF2 iteration count {iterations} exceeds the supported maximum of {PBKDF2_MAX_ITERATIONS}"
@@ -7255,29 +7326,137 @@ fn pbkdf2_derive(
"PBKDF2 output length {length} bytes exceeds the supported maximum of {PBKDF2_MAX_OUTPUT_BYTES}"
)));
}
- use pbkdf2::pbkdf2_hmac;
+ let block_length = match hash {
+ "SHA-1" => 20,
+ "SHA-256" => 32,
+ "SHA-384" => 48,
+ "SHA-512" => 64,
+ _ => return Err(crypto_err("unsupported PBKDF2 hash")),
+ };
+ let work = u64::from(iterations) * u64::from(length).div_ceil(block_length);
+ if work > PBKDF2_MAX_WORK {
+ return Err(crypto_err(format!(
+ "PBKDF2 work of {iterations} iterations over {length} bytes exceeds the supported maximum of {PBKDF2_MAX_WORK}"
+ )));
+ }
+ Ok(work)
+}
+
+#[cfg(test)]
+fn pbkdf2_derive(
+ hash: &str,
+ password: &[u8],
+ salt: &[u8],
+ iterations: u32,
+ length: u32,
+) -> Result<Vec<u8>, deno_error::JsErrorBox> {
+ let cancelled = std::sync::atomic::AtomicBool::new(false);
+ pbkdf2_derive_with(hash, password, salt, iterations, length, &cancelled)
+}
+
+fn pbkdf2_derive_with(
+ hash: &str,
+ password: &[u8],
+ salt: &[u8],
+ iterations: u32,
+ length: u32,
+ cancelled: &std::sync::atomic::AtomicBool,
+) -> Result<Vec<u8>, deno_error::JsErrorBox> {
+ validate_pbkdf2(hash, iterations, length)?;
+ if cancelled.load(std::sync::atomic::Ordering::Relaxed) {
+ return Err(crypto_err("PBKDF2 derivation was cancelled"));
+ }
let mut dk = vec![0u8; length as usize];
- match hash {
- "SHA-1" => pbkdf2_hmac::<sha1::Sha1>(password, salt, iterations, &mut dk),
- "SHA-256" => pbkdf2_hmac::<sha2::Sha256>(password, salt, iterations, &mut dk),
- "SHA-384" => pbkdf2_hmac::<sha2::Sha384>(password, salt, iterations, &mut dk),
- "SHA-512" => pbkdf2_hmac::<sha2::Sha512>(password, salt, iterations, &mut dk),
+ let completed = match hash {
+ "SHA-1" => pbkdf2_blocks::<hmac::Hmac<sha1::Sha1>>(password, salt, iterations, &mut dk, cancelled),
+ "SHA-256" => pbkdf2_blocks::<hmac::Hmac<sha2::Sha256>>(password, salt, iterations, &mut dk, cancelled),
+ "SHA-384" => pbkdf2_blocks::<hmac::Hmac<sha2::Sha384>>(password, salt, iterations, &mut dk, cancelled),
+ "SHA-512" => pbkdf2_blocks::<hmac::Hmac<sha2::Sha512>>(password, salt, iterations, &mut dk, cancelled),
_ => return Err(crypto_err("unsupported PBKDF2 hash")),
+ };
+ if !completed {
+ return Err(crypto_err("PBKDF2 derivation was cancelled"));
}
Ok(dk)
}
-/// PBKDF2 key derivation. `length` is the derived-bits output in bytes.
+fn pbkdf2_blocks<M>(
+ password: &[u8],
+ salt: &[u8],
+ iterations: u32,
+ output: &mut [u8],
+ cancelled: &std::sync::atomic::AtomicBool,
+) -> bool
+where
+ M: hmac::Mac + hmac::digest::KeyInit + Clone,
+{
+ use std::sync::atomic::Ordering;
+ let prf = <M as hmac::digest::KeyInit>::new_from_slice(password)
+ .expect("HMAC accepts a key of any length");
+ for (index, block) in output.chunks_mut(<M as hmac::digest::OutputSizeUser>::output_size()).enumerate() {
+ if cancelled.load(Ordering::Relaxed) {
+ return false;
+ }
+ let mut mac = prf.clone();
+ mac.update(salt);
+ mac.update(&(index as u32 + 1).to_be_bytes());
+ let mut value = mac.finalize().into_bytes();
+ block.copy_from_slice(&value[..block.len()]);
+ for round in 1..iterations {
+ if round % 4096 == 0 && cancelled.load(Ordering::Relaxed) {
+ return false;
+ }
+ let mut mac = prf.clone();
+ mac.update(&value);
+ value = mac.finalize().into_bytes();
+ for (byte, next) in block.iter_mut().zip(value.iter()) {
+ *byte ^= next;
+ }
+ }
+ }
+ true
+}
+
+struct CancelPbkdf2OnDrop(std::sync::Arc<std::sync::atomic::AtomicBool>);
+
+impl Drop for CancelPbkdf2OnDrop {
+ fn drop(&mut self) {
+ self.0.store(true, std::sync::atomic::Ordering::Relaxed);
+ }
+}
+
+fn pbkdf2_slots() -> &'static std::sync::Arc<tokio::sync::Semaphore> {
+ static SLOTS: std::sync::OnceLock<std::sync::Arc<tokio::sync::Semaphore>> = std::sync::OnceLock::new();
+ SLOTS.get_or_init(|| {
+ let cores = std::thread::available_parallelism().map_or(1, |count| count.get());
+ std::sync::Arc::new(tokio::sync::Semaphore::new((cores / 2).max(1)))
+ })
+}
+
+/// Keep large derivations off the page thread, retaining their permits until
+/// workers exit. Small bounded work avoids blocking-pool scheduling overhead.
#[op2]
#[buffer]
-fn op_subtle_pbkdf2(
- #[string] hash: &str,
- #[buffer] password: &[u8],
- #[buffer] salt: &[u8],
+async fn op_subtle_pbkdf2(
+ #[string] hash: String,
+ #[buffer(copy)] password: Vec<u8>,
+ #[buffer(copy)] salt: Vec<u8>,
iterations: u32,
length: u32,
) -> Result<Vec<u8>, deno_error::JsErrorBox> {
- pbkdf2_derive(hash, password, salt, iterations, length)
+ let work = validate_pbkdf2(&hash, iterations, length)?;
+ if pbkdf2_can_inline(work, password.len(), salt.len()) {
+ let cancelled = std::sync::atomic::AtomicBool::new(false);
+ return pbkdf2_derive_with(&hash, &password, &salt, iterations, length, &cancelled);
+ }
+ let slot = pbkdf2_slots().clone().acquire_owned().await
+ .map_err(|error| crypto_err(format!("PBKDF2 unavailable: {error}")))?;
+ let cancelled = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
+ let _cancel_on_drop = CancelPbkdf2OnDrop(cancelled.clone());
+ tokio::task::spawn_blocking(move || {
+ let _slot = slot;
+ pbkdf2_derive_with(&hash, &password, &salt, iterations, length, &cancelled)
+ }).await.map_err(|error| crypto_err(format!("PBKDF2 task failed: {error}")))?
}
/// Generous DoS backstop on HKDF output length. HKDF itself rejects output
diff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rs
index 208a9518..a47571e3 100644
--- a/crates/obscura-js/src/runtime.rs
+++ b/crates/obscura-js/src/runtime.rs
@@ -19234,6 +19234,107 @@ mod tests {
assert_eq!(href, serde_json::json!("http://example.com/test"));
}
+ #[test]
+ fn window_origin_is_replaceable_without_changing_the_document_origin() {
+ let mut rt = setup_runtime("<html><body></body></html>");
+ assert_eq!(rt.evaluate(r#"(() => {
+ const descriptor = Object.getOwnPropertyDescriptor(window, 'origin');
+ const initial = origin;
+ const value = { replaced: true };
+ origin = value;
+ const replaced = Object.getOwnPropertyDescriptor(window, 'origin');
+ const errors = [];
+ for (const member of [descriptor.get, descriptor.set]) {
+ try { member.call({}, 'fake'); errors.push('allowed'); }
+ catch (error) { errors.push(error.name); }
+ }
+ location.href = 'https://destination.example/next';
+ return [initial, descriptor.configurable, descriptor.enumerable,
+ descriptor.get.name, descriptor.set.name,
+ descriptor.get.length, descriptor.set.length,
+ origin === value, replaced.writable, replaced.configurable,
+ replaced.enumerable, descriptor.get.call(window), location.origin, errors];
+ })()"#).unwrap(), serde_json::json!([
+ "http://example.com", true, true, "get origin", "set origin", 0, 1,
+ true, true, true, true, "http://example.com", "https://destination.example",
+ ["TypeError", "TypeError"]
+ ]));
+ }
+
+ #[test]
+ fn window_origin_uses_the_receiver_realm_and_inherits_blank_frame_origins() {
+ let mut rt = setup_runtime("<html><body></body></html>");
+ assert_eq!(rt.evaluate(r#"(() => {
+ const frame = document.createElement('iframe');
+ document.body.append(frame);
+ const child = frame.contentWindow;
+ const descriptor = Object.getOwnPropertyDescriptor(window, 'origin');
+ const initial = [origin, child.origin, child.location.origin,
+ descriptor.get.call(child)];
+ const value = { child: true };
+ descriptor.set.call(child, value);
+ const replaced = child.origin === value;
+ const parentUnchanged = origin === 'http://example.com';
+ const deleted = delete child.origin;
+ return [initial, replaced, parentUnchanged, deleted,
+ descriptor.get.call(child), Object.hasOwn(child, 'origin')];
+ })()"#).unwrap(), serde_json::json!([
+ ["http://example.com", "http://example.com", "null", "http://example.com"],
+ true, true, true, "http://example.com", false
+ ]));
+ }
+
+ #[tokio::test(flavor = "current_thread")]
+ async fn pbkdf2_derivation_does_not_block_page_timers() {
+ let mut rt = setup_runtime("<html><body></body></html>");
+ let result = rt.call_function_on_for_cdp(r#"async () => {
+ const key = await crypto.subtle.importKey(
+ 'raw', new TextEncoder().encode('password'), 'PBKDF2', false, ['deriveBits']);
+ const derivation = crypto.subtle.deriveBits({
+ name: 'PBKDF2', hash: 'SHA-256',
+ salt: new TextEncoder().encode('salt'), iterations: 1000000,
+ }, key, 256);
+ const first = await Promise.race([
+ derivation.then(() => 'derivation'),
+ new Promise(resolve => setTimeout(() => resolve('timer'), 0)),
+ ]);
+ return [first, (await derivation).byteLength];
+ }"#, None, &[], true, true).await.unwrap();
+ assert_eq!(result.value, Some(serde_json::json!(["timer", 32])));
+ }
+
+ #[tokio::test(flavor = "current_thread")]
+ async fn pbkdf2_async_derivation_snapshots_buffers_and_reports_operation_errors() {
+ let mut rt = setup_runtime("<html><body></body></html>");
+ let result = rt.call_function_on_for_cdp(r#"async () => {
+ const key = await crypto.subtle.importKey(
+ 'raw', new TextEncoder().encode('password'), 'PBKDF2', false, ['deriveBits']);
+ const salt = new TextEncoder().encode('salt');
+ const derivation = crypto.subtle.deriveBits({
+ name: 'PBKDF2', hash: 'SHA-1', salt, iterations: 4096,
+ }, key, 160);
+ salt.fill(0);
+ const hex = Array.from(new Uint8Array(await derivation),
+ byte => byte.toString(16).padStart(2, '0')).join('');
+ const errors = [];
+ for (const [iterations, bits] of [[0, 256], [10000001, 256], [10000000, 8388608]]) {
+ try {
+ await crypto.subtle.deriveBits({
+ name: 'PBKDF2', hash: 'SHA-1', salt, iterations,
+ }, key, bits);
+ errors.push('allowed');
+ } catch (error) {
+ errors.push([error instanceof DOMException, error.name]);
+ }
+ }
+ return [hex, errors];
+ }"#, None, &[], true, true).await.unwrap();
+ assert_eq!(result.value, Some(serde_json::json!([
+ "4b007901b765489abead49d926f721d065a429c1",
+ [[true, "OperationError"], [true, "OperationError"], [true, "OperationError"]]
+ ])));
+ }
+
#[test]
fn test_button_click_dispatches_listener() {
let mut rt = setup_runtime(r#"<button id="go">Go</button>"#);
diff --git a/docs/Architecture-overview.md b/docs/Architecture-overview.md
index 8be53852..0ac1393e 100644
--- a/docs/Architecture-overview.md
+++ b/docs/Architecture-overview.md
@@ -115,6 +115,17 @@ for Playwright frame locators or iframe screenshot fidelity.
`obscura-js/js/bootstrap.js` provides the browser globals: `document`, `window`, `navigator`, `location`, observers, fetch, indexedDB, etc.
+`window.origin` (including the bare `origin` identifier) reports the owning
+document's origin, including inherited blank-frame origins. Page assignment
+replaces this property without changing the document's actual origin.
+
+Short, bounded PBKDF2 derivations retain a native fast path. Larger derivations
+run on bounded blocking workers rather than the page thread. Dropping an
+awaiting future cancels that background work; the worker retains its admission
+permit until it exits. Limits are 10 million iterations, 1 MiB of output, and
+1 billion iterations multiplied by hash-sized output blocks. Zero-iteration
+or over-limit derivations reject with `OperationError`.
+
`obscura-js/src/ops.rs` registers Rust ops that the bootstrap calls into:
```js