The headless browser for AI agents and web scraping
fix: preserve binary fetch request bodies
hongde7826dbb56d74
diff --git a/crates/obscura-js/js/bootstrap.js b/crates/obscura-js/js/bootstrap.jsindex d7e69040..d7b4aff8 100644--- a/crates/obscura-js/js/bootstrap.js+++ b/crates/obscura-js/js/bootstrap.js@@ -325,7 +325,7 @@ async function __fetchDynClassicScript(task) {body = _decodeDataScriptUrl(task.url);} else {const raw = await Deno.core.ops.op_fetch_url(- task.url, "GET", "{}", "", task.pageOrigin, "no-cors", "same-origin"+ task.url, "GET", "{}", new Uint8Array(0), task.pageOrigin, "no-cors", "same-origin");const parsed = JSON.parse(raw);// The HTML script-fetch algorithm treats an unsuccessful HTTP response@@ -551,7 +551,7 @@ async function _fetchLinkedCss(url, pageOrigin, depth = 0, seen = new Set()) {if (depth > 4 || seen.has(url)) return "";seen.add(url);const raw = await Deno.core.ops.op_fetch_url(- url, "GET", "{}", "", pageOrigin, "no-cors", "same-origin"+ url, "GET", "{}", new Uint8Array(0), pageOrigin, "no-cors", "same-origin");const parsed = JSON.parse(raw);if (parsed.blocked || parsed.status >= 400 || parsed.status === 0) {@@ -6682,28 +6682,41 @@ function _formDataToMultipart(fd) {const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';let bnd = '----WebKitFormBoundary';for (let i = 0; i < 16; i++) bnd += chars[Math.floor(Math.random() * chars.length)];- let out = '';+ const encoder = new TextEncoder();+ const chunks = [];+ let length = 0;+ const append = (chunk) => {+ const bytes = typeof chunk === 'string' ? encoder.encode(chunk) : _bodyToUint8Array(chunk);+ chunks.push(bytes);+ length += bytes.byteLength;+ };const entries = fd._d || [];for (let i = 0; i < entries.length; i++) {const k = entries[i][0], v = entries[i][1];- out += '--' + bnd + '\r\n';+ append('--' + bnd + '\r\n');if (v != null && typeof v === 'object' && v._bytes != null) {- out += 'Content-Disposition: form-data; name="' + k + '"; filename="' + (v.name || 'blob') + '"\r\n';- out += 'Content-Type: ' + (v.type || 'application/octet-stream') + '\r\n\r\n';- try { out += new TextDecoder().decode(v._bytes); } catch (e) {}- out += '\r\n';+ append('Content-Disposition: form-data; name="' + k + '"; filename="' + (v.name || 'blob') + '"\r\n');+ append('Content-Type: ' + (v.type || 'application/octet-stream') + '\r\n\r\n');+ append(v._bytes);+ append('\r\n');} else {- out += 'Content-Disposition: form-data; name="' + k + '"\r\n\r\n' + String(v) + '\r\n';+ append('Content-Disposition: form-data; name="' + k + '"\r\n\r\n' + String(v) + '\r\n');}}- out += '--' + bnd + '--\r\n';+ append('--' + bnd + '--\r\n');+ const out = new Uint8Array(length);+ let offset = 0;+ for (const chunk of chunks) {+ out.set(chunk, offset);+ offset += chunk.byteLength;+ }return { boundary: bnd, body: out };}-// Coerce a fetch()/XHR body into the string op_fetch_url expects, attaching a+// Coerce a fetch()/XHR body into the bytes op_fetch_url expects, attaching a// Content-Type header for body types that need one (FormData, URLSearchParams).function _serializeBody(initBody, headers) {- if (initBody == null || initBody === '') return '';+ if (initBody == null || initBody === '') return new Uint8Array(0);if (initBody instanceof FormData) {const mp = _formDataToMultipart(initBody);headers['Content-Type'] = 'multipart/form-data; boundary=' + mp.boundary;@@ -6713,25 +6726,21 @@ function _serializeBody(initBody, headers) {if (!Object.keys(headers).some(k => k.toLowerCase() === 'content-type')) {headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';}- return initBody.toString();+ return new TextEncoder().encode(initBody.toString());}if (typeof Blob !== 'undefined' && initBody instanceof Blob) {if (initBody.type && !Object.keys(headers).some(k => k.toLowerCase() === 'content-type')) {headers['Content-Type'] = initBody.type;}- return _bytesToBinaryString(_bodyToUint8Array(initBody));+ return _bodyToUint8Array(initBody);}if (typeof ArrayBuffer !== 'undefined' && initBody instanceof ArrayBuffer) {- const bytes = new Uint8Array(initBody);- let s = ''; for (let i = 0; i < bytes.length; i++) s += String.fromCharCode(bytes[i]);- return s;+ return new Uint8Array(initBody);}if (typeof ArrayBuffer !== 'undefined' && ArrayBuffer.isView(initBody) && initBody.buffer instanceof ArrayBuffer) {- const bytes = new Uint8Array(initBody.buffer, initBody.byteOffset, initBody.byteLength);- let s = ''; for (let i = 0; i < bytes.length; i++) s += String.fromCharCode(bytes[i]);- return s;+ return new Uint8Array(initBody.buffer, initBody.byteOffset, initBody.byteLength);}- return typeof initBody === 'string' ? initBody : String(initBody);+ return new TextEncoder().encode(typeof initBody === 'string' ? initBody : String(initBody));}globalThis.fetch = async (input, init = {}) => {@@ -6747,7 +6756,10 @@ globalThis.fetch = async (input, init = {}) => {url = _resolveUrl(url);const method = init.method || (input instanceof Request ? input.method : "GET");let _h = init.headers instanceof Headers ? Object.fromEntries(init.headers.entries()) : (init.headers || {});- const body = _serializeBody(init.body, _h);+ const initBody = init.body !== undefined+ ? init.body+ : (input instanceof Request ? input.body : undefined);+ const body = _serializeBody(initBody, _h);const hdrs = JSON.stringify(_h);const fetchMode = init.mode || (input instanceof Request ? input.mode : "cors");const fetchCredentials = init.credentials !== undefineddiff --git a/crates/obscura-js/src/ops.rs b/crates/obscura-js/src/ops.rsindex 7597a997..c42e0a33 100644--- a/crates/obscura-js/src/ops.rs+++ b/crates/obscura-js/src/ops.rs@@ -6,7 +6,6 @@ use std::sync::Arc;use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};use deno_core::op2;use deno_core::Extension;-#[cfg(feature = "render")]use deno_core::JsBuffer;use deno_core::v8;use deno_core::OpState;@@ -2160,11 +2159,12 @@ async fn op_fetch_url(#[string] url: String,#[string] method: String,#[string] headers_json: String,- #[string] body: String,+ #[buffer] body: JsBuffer,#[string] origin: String,#[string] mode: String,#[string] credentials: String,) -> Result<String, deno_error::JsErrorBox> {+ let body = body.to_vec();tracing::debug!("op_fetch_url called: {} {} (intercept check pending)",method,@@ -2257,7 +2257,7 @@ async fn op_fetch_url(let mut override_url: Option<String> = None;let mut override_method: Option<String> = None;let mut override_headers: Option<HashMap<String, String>> = None;- let mut override_body: Option<String> = None;+ let mut override_body: Option<Vec<u8>> = None;if let Some((tx, request_id)) = intercept_tx {let custom_headers: HashMap<String, String> =@@ -2307,7 +2307,7 @@ async fn op_fetch_url(override_url = url;override_method = method;override_headers = headers;- override_body = body;+ override_body = body.map(String::into_bytes);tracing::debug!("Interception: continue (overrides url={} method={} headers={} body={})",override_url.is_some(),@@ -2760,7 +2760,7 @@ async fn stealth_fetch_all(url: String,method: String,custom_headers: HashMap<String, String>,- body: String,+ body: Vec<u8>,page_origin: String,mode: String,credentials: FetchCredentials,diff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rsindex f36f742e..34df2818 100644--- a/crates/obscura-js/src/runtime.rs+++ b/crates/obscura-js/src/runtime.rs@@ -14077,6 +14077,207 @@ mod tests {}));}++ #[tokio::test(flavor = "current_thread")]+ async fn fetch_preserves_binary_body_sources_at_the_op_boundary() {+ let mut rt = setup_runtime("<html><body></body></html>");+ let result = rt+ .call_function_on_for_cdp(+ r#"async () => {+ const originalFetchOp = Deno.core.ops.op_fetch_url;+ const calls = [];+ try {+ Deno.core.ops.op_fetch_url =+ (url, method, headers, body) => {+ calls.push({+ path: new URL(url).pathname,+ isUint8Array: body instanceof Uint8Array,+ bytes: Array.from(+ body instanceof Uint8Array+ ? body+ : new TextEncoder().encode(body),+ ),+ });+ return JSON.stringify({+ status: 200,+ headers: {},+ body: "ok",+ url,+ });+ };++ const sentinel = [0, 128, 255, 16];+ await fetch("/blob", {+ method: "POST",+ body: new Blob([new Uint8Array(sentinel)]),+ });++ const arrayBuffer = new Uint8Array(sentinel).buffer;+ await fetch("/array-buffer", { method: "POST", body: arrayBuffer });++ const backing = new Uint8Array([9, ...sentinel, 8]);+ await fetch("/typed-array-view", {+ method: "POST",+ body: backing.subarray(1, 5),+ });++ await fetch(new Request("/request", {+ method: "POST",+ body: new Uint8Array(sentinel),+ }));++ return calls;+ } finally {+ Deno.core.ops.op_fetch_url = originalFetchOp;+ }+ }"#,+ None,+ &[],+ true,+ true,+ )+ .await+ .unwrap();++ assert_eq!(+ result.value.unwrap(),+ serde_json::json!([+ { "path": "/blob", "isUint8Array": true, "bytes": [0, 128, 255, 16] },+ { "path": "/array-buffer", "isUint8Array": true, "bytes": [0, 128, 255, 16] },+ { "path": "/typed-array-view", "isUint8Array": true, "bytes": [0, 128, 255, 16] },+ { "path": "/request", "isUint8Array": true, "bytes": [0, 128, 255, 16] },+ ])+ );+ }++ #[tokio::test(flavor = "current_thread")]+ async fn fetch_form_urlencoded_and_xhr_bodies_reach_the_op_as_bytes() {+ let mut rt = setup_runtime("<html><body></body></html>");+ let result = rt+ .call_function_on_for_cdp(+ r#"async () => {+ const originalFetchOp = Deno.core.ops.op_fetch_url;+ const calls = [];+ const includesBytes = (bytes, needle) => {+ outer: for (let i = 0; i <= bytes.length - needle.length; i++) {+ for (let j = 0; j < needle.length; j++) {+ if (bytes[i + j] !== needle[j]) continue outer;+ }+ return true;+ }+ return false;+ };+ try {+ Deno.core.ops.op_fetch_url =+ (url, method, headers, body) => {+ const bytes = Array.from(+ body instanceof Uint8Array+ ? body+ : new TextEncoder().encode(body),+ );+ calls.push({+ path: new URL(url).pathname,+ headers: JSON.parse(headers),+ isUint8Array: body instanceof Uint8Array,+ bytes,+ hasRawSentinel: includesBytes(bytes, [0, 128, 255, 16]),+ });+ return JSON.stringify({+ status: 200,+ headers: {},+ body: "ok",+ url,+ });+ };++ const form = new FormData();+ form.append("note", "snow \u96ea");+ form.append(+ "upload",+ new File([new Uint8Array([0, 128, 255, 16])], "sentinel.bin", {+ type: "application/octet-stream",+ }),+ );+ await fetch("/form-data", { method: "POST", body: form });++ const params = new URLSearchParams();+ params.append("greeting", "\u96ea space&");+ await fetch("/url-search-params", { method: "POST", body: params });++ await new Promise((resolve, reject) => {+ const xhr = new XMLHttpRequest();+ xhr.open("POST", "/xhr-typed-array");+ xhr.onload = resolve;+ xhr.onerror = reject;+ const backing = new Uint8Array([9, 0, 128, 255, 16, 8]);+ xhr.send(backing.subarray(1, 5));+ });++ const formCall = calls.find(call => call.path === "/form-data");+ const paramsCall = calls.find(call => call.path === "/url-search-params");+ const xhrCall = calls.find(call => call.path === "/xhr-typed-array");+ return {+ formData: {+ isUint8Array: formCall.isUint8Array,+ contentType: Object.entries(formCall.headers)+ .find(([name]) => name.toLowerCase() === "content-type")[1]+ .startsWith("multipart/form-data; boundary=----WebKitFormBoundary"),+ hasText: includesBytes(+ formCall.bytes,+ Array.from(new TextEncoder().encode("snow \u96ea")),+ ),+ hasFilename: includesBytes(+ formCall.bytes,+ Array.from(new TextEncoder().encode('filename="sentinel.bin"')),+ ),+ hasRawSentinel: formCall.hasRawSentinel,+ },+ urlSearchParams: {+ isUint8Array: paramsCall.isUint8Array,+ contentType: Object.entries(paramsCall.headers)+ .find(([name]) => name.toLowerCase() === "content-type")[1],+ bytes: paramsCall.bytes,+ },+ xhr: {+ isUint8Array: xhrCall.isUint8Array,+ bytes: xhrCall.bytes,+ },+ };+ } finally {+ Deno.core.ops.op_fetch_url = originalFetchOp;+ }+ }"#,+ None,+ &[],+ true,+ true,+ )+ .await+ .unwrap();++ assert_eq!(+ result.value.unwrap(),+ serde_json::json!({+ "formData": {+ "isUint8Array": true,+ "contentType": true,+ "hasText": true,+ "hasFilename": true,+ "hasRawSentinel": true,+ },+ "urlSearchParams": {+ "isUint8Array": true,+ "contentType": "application/x-www-form-urlencoded;charset=UTF-8",+ "bytes": "greeting=%E9%9B%AA+space%26".as_bytes(),+ },+ "xhr": {+ "isUint8Array": true,+ "bytes": [0, 128, 255, 16],+ },+ })+ );+ }+/// Serves a redirect chain across `connections` consecutive/// requests: `/hop/N` replies with 302 to `/hop/N-1`, `/hop/0` is the/// target. To a path the fixture cannot read it replies with 400diff --git a/crates/obscura-net/src/wreq_client.rs b/crates/obscura-net/src/wreq_client.rsindex 3d4e8305..88ec29cf 100644--- a/crates/obscura-net/src/wreq_client.rs+++ b/crates/obscura-net/src/wreq_client.rs@@ -433,7 +433,7 @@ impl StealthHttpClient {method: &str,url: &Url,headers: &HashMap<String, String>,- body: &str,+ body: &[u8],send_cookies: bool,store_cookies: bool,) -> Result<Response, ObscuraNetError> {@@ -468,7 +468,7 @@ impl StealthHttpClient {req = req.header(k.as_str(), v.as_str());}if !body.is_empty() {- req = req.body(body.to_string());+ req = req.body(body.to_vec());}let in_flight = InFlightGuard::new(&self.in_flight);@@ -631,7 +631,7 @@ mod tests {"POST",&url,&std::collections::HashMap::new(),- "payload",+ b"payload",false,false,)