Skip to content

The headless browser for AI agents and web scraping

Use native UTF-8 decoding and preserve explicit encodings

SGavrl004bcddef910
diff --git a/crates/obscura-js/js/bootstrap.js b/crates/obscura-js/js/bootstrap.js
index 43488792..ea99c1b5 100644
--- a/crates/obscura-js/js/bootstrap.js
+++ b/crates/obscura-js/js/bootstrap.js
@@ -50,7 +50,7 @@ const __obscuraCore = globalThis.Deno.core;
'_resolveUrl', '_registerIframe', '_base64ToUint8Array',
'_bodyToUint8Array', '_arrayBufferFromBytes',
'_installWasmStreamingFallback', '_urlParseOp', '_urlSetOp',
- '_urlResolveOp', '_decodeBodyWithCharset', '_utf8DecodeBytes',
+ '_urlResolveOp', '_decodeBodyWithCharset',
'_selectionFor', '_isConstructorCE', '_isValidCustomElementName', '_shadowRootForHost',
'_blobPartToBytes', '_bytesToBinaryString', '_formEncode', '_hexv',
'_commonFonts', '_isXMLDocument', '_isValidPITarget', '_isHTMLEl',
@@ -9532,20 +9532,6 @@ if (typeof TextEncoder === 'undefined') {
encodeInto(str, dest) { const enc = this.encode(str); dest.set(enc.slice(0, dest.length)); return { read: str.length, written: Math.min(enc.length, dest.length) }; }
};
}
-// Fast pure-JS UTF-8 decode (the common case: Response/Blob .text(), most
-// pages). Avoids the op + JSON round trip for plain UTF-8.
-function _utf8DecodeBytes(bytes, start) {
- let str = '', i = start | 0;
- const n = bytes.length;
- while (i < n) {
- let c = bytes[i++];
- if (c < 0x80) str += String.fromCharCode(c);
- else if (c < 0xE0) str += String.fromCharCode(((c & 0x1F) << 6) | (bytes[i++] & 0x3F));
- else if (c < 0xF0) { const b1 = bytes[i++], b2 = bytes[i++]; str += String.fromCharCode(((c & 0x0F) << 12) | ((b1 & 0x3F) << 6) | (b2 & 0x3F)); }
- else { const b1 = bytes[i++], b2 = bytes[i++], b3 = bytes[i++]; const cp = ((c & 0x07) << 18) | ((b1 & 0x3F) << 12) | ((b2 & 0x3F) << 6) | (b3 & 0x3F); if (cp > 0xFFFF) { const s = cp - 0x10000; str += String.fromCharCode(0xD800 + (s >> 10), 0xDC00 + (s & 0x3FF)); } else str += String.fromCharCode(cp); }
- }
- return str;
-}
if (typeof TextDecoder === 'undefined') {
globalThis.TextDecoder = class TextDecoder {
constructor(label, options) {
@@ -9568,11 +9554,9 @@ if (typeof TextDecoder === 'undefined') {
const bytes = ArrayBuffer.isView(input)
? new Uint8Array(input.buffer, input.byteOffset, input.byteLength)
: new Uint8Array(input);
- // Fast path: plain UTF-8, non-fatal (Response/Blob text, most pages).
- if (this.encoding === 'utf-8' && !this.fatal) {
- let off = 0;
- if (!this.ignoreBOM && bytes.length >= 3 && bytes[0] === 0xEF && bytes[1] === 0xBB && bytes[2] === 0xBF) off = 3;
- return _utf8DecodeBytes(bytes, off);
+ // The native UTF-8 decoder also replaces malformed sequences, without JSON or per-byte JS work.
+ if (this.encoding === 'utf-8' && !this.fatal && !this.ignoreBOM) {
+ return __obscuraCore.ops.op_decode(bytes);
}
// Legacy encodings / fatal mode: encoding_rs via the op.
const r = JSON.parse(__obscuraCore.ops.op_text_decode(this.encoding, bytes, this.fatal, this.ignoreBOM));
diff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rs
index e0dd5ef4..e72e65b4 100644
--- a/crates/obscura-js/src/runtime.rs
+++ b/crates/obscura-js/src/runtime.rs
@@ -23502,6 +23502,40 @@ mod tests {
assert_eq!(result.as_str().unwrap(), "B");
}
+ #[test]
+ fn text_decoder_replaces_malformed_utf8_and_preserves_bom_options() {
+ let mut rt = setup_runtime("<html><body></body></html>");
+ let result = rt.evaluate(r#"(() => {
+ const cases = [
+ [[0x80], '\ufffd'],
+ [[0xc0, 0xaf], '\ufffd\ufffd'],
+ [[0xe0, 0x80, 0xaf], '\ufffd\ufffd\ufffd'],
+ [[0xed, 0xa0, 0x80], '\ufffd\ufffd\ufffd'],
+ [[0xf4, 0x90, 0x80, 0x80], '\ufffd\ufffd\ufffd\ufffd'],
+ [[0xf5, 0x80, 0x80, 0x80], '\ufffd\ufffd\ufffd\ufffd'],
+ [[0xe2, 0x82], '\ufffd'],
+ [[0xf0, 0x9f, 0x92], '\ufffd'],
+ [[0xc2, 0x41], '\ufffdA'],
+ [[0xe2, 0x28, 0xa1], '\ufffd(\ufffd'],
+ ];
+ for (const [bytes, expected] of cases) {
+ const buffer = new Uint8Array([99, ...bytes, 99]);
+ const view = new DataView(buffer.buffer, 1, bytes.length);
+ const actual = new TextDecoder().decode(view);
+ if (actual !== expected) return {bytes, actual, expected};
+ try { new TextDecoder('utf-8', {fatal:true}).decode(view); return 'fatal accepted'; }
+ catch (error) { if (!(error instanceof TypeError)) return error.name; }
+ }
+ const bytes = new Uint8Array([0xef,0xbb,0xbf,65,0,34,92,10,0xc3,0xa9,0xf0,0x9f,0x98,0x80]);
+ const expected = 'A\0"\\\n\u00e9\ud83d\ude00';
+ const decoder = new TextDecoder('utf8', {fatal:true});
+ return [new TextDecoder().decode(bytes) === expected,
+ new TextDecoder('utf8', {ignoreBOM:true}).decode(bytes) === '\ufeff' + expected,
+ decoder.decode(bytes) === expected, decoder.decode(new Uint8Array()) === ''];
+ })()"#).unwrap();
+ assert_eq!(result, serde_json::json!([true, true, true, true]));
+ }
+
#[test]
fn test_document_doctype() {
let mut rt = setup_runtime("<!DOCTYPE html><html><body></body></html>");
diff --git a/crates/obscura-net/src/encoding.rs b/crates/obscura-net/src/encoding.rs
index 39003fd7..58f50986 100644
--- a/crates/obscura-net/src/encoding.rs
+++ b/crates/obscura-net/src/encoding.rs
@@ -30,7 +30,7 @@ pub fn decode_with_label(label: &str, bytes: &[u8], fatal: bool, ignore_bom: boo
let mut dec = if ignore_bom {
enc.new_decoder_without_bom_handling()
} else {
- enc.new_decoder()
+ enc.new_decoder_with_bom_removal()
};
// Both decode calls write only into the string's spare capacity and stop
// with OutputFull when it runs out. Legacy encodings can expand one byte into
@@ -341,6 +341,22 @@ fn sniff_meta_charset(bytes: &[u8]) -> Option<&'static Encoding> {
mod tests {
use super::*;
+ #[test]
+ fn text_decoder_bom_does_not_override_the_selected_encoding() {
+ assert_eq!(decode_with_label("utf-8", &[0xff, 0xfe, 65, 0], false, false).as_deref(),
+ Some("\u{fffd}\u{fffd}A\0"));
+ assert_eq!(decode_with_label("utf-8", &[0xff, 0xfe, 65, 0], true, false), None);
+ assert_eq!(decode_with_label("windows-1252", &[0xef, 0xbb, 0xbf, 65], false, false).as_deref(),
+ Some("\u{ef}\u{bb}\u{bf}A"));
+ for fatal in [false, true] {
+ assert_eq!(decode_with_label("utf-8", &[0xef, 0xbb, 0xbf, 65], fatal, false).as_deref(), Some("A"));
+ assert_eq!(decode_with_label("utf-8", &[0xef, 0xbb, 0xbf, 65], fatal, true).as_deref(), Some("\u{feff}A"));
+ assert_eq!(decode_with_label("utf-16le", &[0xff, 0xfe, 65, 0], fatal, false).as_deref(), Some("A"));
+ assert_eq!(decode_with_label("utf-16le", &[0xff, 0xfe, 65, 0], fatal, true).as_deref(), Some("\u{feff}A"));
+ assert_eq!(decode_with_label("utf-16le", &[0xfe, 0xff, 0, 65], fatal, false).as_deref(), Some("\u{fffe}\u{4100}"));
+ }
+ }
+
// Legacy single-byte encodings can expand one input byte into three UTF-8
// bytes (windows-1252 0x80 is U+20AC). The decoder only writes into spare
// capacity, so an undersized buffer used to truncate the text or, in fatal