The headless browser for AI agents and web scraping
fix(js): validate Response construction and static factories
SGavrlcbcafc11ebf9
diff --git a/crates/obscura-js/js/bootstrap.js b/crates/obscura-js/js/bootstrap.jsindex 0a815d4e..bd275339 100644--- a/crates/obscura-js/js/bootstrap.js+++ b/crates/obscura-js/js/bootstrap.js@@ -7782,7 +7782,7 @@ globalThis.fetch = async (input, init = {}) => {const responseBody = respType === "opaque"? null: (parsed.bodyBase64 ? _base64ToUint8Array(parsed.bodyBase64) : (parsed.body || ""));- const response = new Response(responseBody, {+ const response = _createInternalResponse(responseBody, {status: parsed.status,statusText: "",headers: parsed.headers || {},@@ -8235,13 +8235,36 @@ function _decodeBodyWithCharset(bytes, headers) {catch (e) { return new TextDecoder().decode(bytes); }}+let _createInternalResponse;if (typeof Response === 'undefined') {- globalThis.Response = class Response {- constructor(body, init = {}) {- this._bodyBytes = _bodyToUint8Array(body); this.status = init.status === undefined ? 200 : Number(init.status); this.statusText = init.statusText || '';+ const internalResponseInit = {};+ const _Response = globalThis.Response = class Response {+ constructor(body, init = {}, internalInit) {+ if (init == null) init = {};+ if (typeof init !== 'object' && typeof init !== 'function') {+ throw new TypeError('Response init must be a dictionary');+ }+ const internal = internalInit === internalResponseInit;+ const headers = init.headers;+ const status = init.status;+ const statusText = init.statusText;+ this.status = status === undefined ? 200 : (internal ? status : (+status & 0xffff));+ this.statusText = statusText === undefined ? '' : `${statusText}`;+ if (!internal) {+ if (this.status < 200 || this.status > 599) throw new RangeError('Invalid response status');+ if (/[^\t\x20-\x7e\x80-\xff]/.test(this.statusText)) throw new TypeError('Invalid response statusText');+ if (body != null && (this.status === 204 || this.status === 205 || this.status === 304)) {+ throw new TypeError('Response status cannot have a body');+ }+ } else if (this.status === 204 || this.status === 205 || this.status === 304) {+ body = null;+ }+ this._bodyBytes = _bodyToUint8Array(body);this.ok = this.status >= 200 && this.status < 300;- this.headers = new Headers(init.headers);- this.type = init.type || 'basic'; this.url = init.url || ''; this.redirected = !!init.redirected;+ this.headers = new Headers(headers);+ this.type = internal ? (init.type || 'default') : 'default';+ this.url = internal ? (init.url || '') : '';+ this.redirected = internal && !!init.redirected;// #818: body/bodyUsed. A null-body response (null or no body passed)// has body === null; every other body is a one-chunk stream, created// lazily so merely touching .body does not copy the bytes.@@ -8297,7 +8320,7 @@ if (typeof Response === 'undefined') {async arrayBuffer() { this._consumeBody(); return _arrayBufferFromBytes(this._fetchBody ? await this._fetchBody.promise : this._bodyBytes); }async blob() { this._consumeBody(); return new Blob([this._fetchBody ? await this._fetchBody.promise : this._bodyBytes]); }clone() {- const copy = new Response(this._bodyNull ? null : this._bodyBytes, { status: this.status, statusText: this.statusText, headers: this.headers, type: this.type, url: this.url, redirected: this.redirected });+ const copy = _createInternalResponse(this._bodyNull ? null : this._bodyBytes, { status: this.status, statusText: this.statusText, headers: this.headers, type: this.type, url: this.url, redirected: this.redirected });if (this._fetchBody) {const promise = this._fetchBody.promise.then(bytes => bytes.slice());promise.catch(() => {});@@ -8306,10 +8329,25 @@ if (typeof Response === 'undefined') {}return copy;}- static error() { return new Response(null, { status: 0 }); }- static redirect(url, status) { return new Response(null, { status: status || 302, headers: { Location: url } }); }- static json(data, init) { return new Response(JSON.stringify(data), { ...init, headers: { 'content-type': 'application/json', ...(init?.headers || {}) } }); }+ static error() { return _createInternalResponse(null, { status: 0, type: 'error' }); }+ static redirect(url, status = 302) {+ url = `${url}`;+ status = +status & 0xffff;+ const parsed = new URL(url, document.baseURI);+ if (![301,302,303,307,308].includes(status)) throw new RangeError('Invalid redirect status');+ return new Response(null, { status, headers: { Location: parsed.href } });+ }+ static json(data, init) {+ const json = JSON.stringify(data);+ if (json === undefined) throw new TypeError('Value is not JSON serializable');+ const response = new Response(new TextEncoder().encode(json), init);+ if (!response.headers.has('content-type')) response.headers.set('content-type', 'application/json');+ return response;+ }};+ _createInternalResponse = (body, init) => new _Response(body, init, internalResponseInit);+} else {+ _createInternalResponse = (body, init) => new Response(body, init);}if (!Element.prototype.replaceWith) {diff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rsindex e712c961..14c751da 100644--- a/crates/obscura-js/src/runtime.rs+++ b/crates/obscura-js/src/runtime.rs@@ -17583,6 +17583,70 @@ mod tests {);}+ #[tokio::test(flavor = "current_thread")]+ async fn response_constructor_validates_public_init_without_forging_network_metadata() {+ let mut rt = setup_runtime("<html><body></body></html>");+ let result = rt.evaluate(r#"+ const error = callback => { try { callback(); return null; } catch (e) { return e.name; } };+ const response = new Response(null, {type:'opaque',url:'https://example.com/',redirected:true});+ let statusReads = 0;+ const singleRead = new Response(null, {get status(){statusReads++;return 201;}});+ return {+ ordinary:[response.type,response.url,response.redirected,String(response.status)],+ invalidStatus:[0,100,199,600,1000].map(status=>error(()=>new Response('',{status}))),+ conversion:[65736,200.9,'201'].map(status=>String(new Response(null,{status}).status)),+ invalidStatusText:['\n','\r','\0','\u0100'].map(statusText=>error(()=>new Response(null,{statusText}))),+ validStatusText:['\tOK','\u0080'].map(statusText=>new Response(null,{statusText}).statusText),+ nullBodyStatus:[204,205,304].map(status=>error(()=>new Response('',{status}))),+ nullBodyAllowed:[204,205,304].map(status=>new Response(null,{status}).body),+ nullInit:String(new Response(null,null).status),+ getter:[String(singleRead.status),String(statusReads)]+ };+ "#).unwrap();+ assert_eq!(result, serde_json::json!({+ "ordinary":["default","",false,"200"],+ "invalidStatus":["RangeError","RangeError","RangeError","RangeError","RangeError"],+ "conversion":["200","200","201"],+ "invalidStatusText":["TypeError","TypeError","TypeError","TypeError"],+ "validStatusText":["\tOK","\u{0080}"],+ "nullBodyStatus":["TypeError","TypeError","TypeError"],+ "nullBodyAllowed":[null,null,null],+ "nullInit":"200",+ "getter":["201","1"]+ }));+ }++ #[tokio::test(flavor = "current_thread")]+ async fn response_factories_validate_redirects_and_json_and_preserve_error_clones() {+ let mut rt = setup_runtime("<html><body></body></html>");+ let result = rt.evaluate(r#"+ const error = callback => { try { callback(); return null; } catch (e) { return e.name; } };+ const networkError = Response.error();+ const copy = networkError.clone();+ const redirect = Response.redirect('https://example.com/a/../b');+ const json = Response.json({ok:true},{headers:new Headers({'x-check':'preserved'})});+ return {+ error:[networkError.type,String(networkError.status),networkError.body],+ clone:[copy.type,String(copy.status),copy.body],+ redirect:[redirect.type,String(redirect.status),redirect.headers.get('location')],+ invalidRedirectStatus:[0,200,309,400,500].map(status=>error(()=>Response.redirect('https://example.com/',status))),+ invalidRedirectUrl:error(()=>Response.redirect('https://[invalid')),+ json:[json.type,json.headers.get('content-type'),json.headers.get('x-check')],+ jsonUndefined:error(()=>Response.json(undefined)),+ jsonSymbol:error(()=>Response.json(Symbol('value'))),+ jsonNullBodyStatus:[204,205,304].map(status=>error(()=>Response.json('body',{status})))+ };+ "#).unwrap();+ assert_eq!(result, serde_json::json!({+ "error":["error","0",null], "clone":["error","0",null],+ "redirect":["default","302","https://example.com/b"],+ "invalidRedirectStatus":["RangeError","RangeError","RangeError","RangeError","RangeError"],+ "invalidRedirectUrl":"TypeError", "json":["default","application/json","preserved"],+ "jsonUndefined":"TypeError", "jsonSymbol":"TypeError",+ "jsonNullBodyStatus":["TypeError","TypeError","TypeError"]+ }));+ }+#[tokio::test(flavor = "current_thread")]async fn response_body_exposes_stream_and_consumption_state() {// #818: a non-null Response body must expose a ReadableStream through