decodeBase64 regex overflows the stack on large payloads (fullPage screenshot, response.body)
Summary
page.screenshot() (and response.body()) throw RangeError: Maximum call stack size exceeded once the base64 payload returned over RPC exceeds roughly 4–8 MiB, e.g. a fullPage: true screenshot of a long page such as https://en.wikipedia.org/wiki/Tokyo at a 1280 px wide viewport.
The overflow comes from the validation regex in src/base64.ts, not from the capture:
const BASE64_PATTERN = /^(?:[A-Za-z\d+/]{4})*(?:[A-Za-z\d+/]{2}==|[A-Za-z\d+/]{3}=)?$/;
function decodeBase64(value, source) {
if (value.length % 4 !== 0 || !BASE64_PATTERN.test(value)) throw new Error(`${source} returned invalid base64`);V8's backtracking engine keeps one frame per iteration of the quantified group (?:...{4})*, so the test itself overflows the stack on large inputs.
Stack trace (4.1.0):
RangeError: Maximum call stack size exceeded
at RegExp.test (<anonymous>)
at decodeBase64 (@browserbasehq/stagehand/dist/index.mjs:2517:48)
at Page.screenshot (@browserbasehq/stagehand/dist/index.mjs:3056:17)Versions
@browserbasehq/stagehand4.1.0 (latest). The same code is in4.2.0-alpha-70f4e91f….- Node 22.23.2, Browserbase remote browser.
Minimal reproduction (no browser needed)
const BASE64_PATTERN = /^(?:[A-Za-z\d+/]{4})*(?:[A-Za-z\d+/]{2}==|[A-Za-z\d+/]{3}=)?$/;
for (const mb of [1, 2, 4, 8, 16]) {
const s = Buffer.alloc(mb * 1024 * 1024 * 3 / 4, 7).toString("base64");
try { console.log(`${mb} MiB base64: test() = ${BASE64_PATTERN.test(s)}`); }
catch (e) { console.log(`${mb} MiB base64: ${e.name}: ${e.message}`); }
}1 MiB base64: test() = true
2 MiB base64: test() = true
4 MiB base64: test() = true
8 MiB base64: RangeError: Maximum call stack size exceeded
16 MiB base64: RangeError: Maximum call stack size exceededIn practice the failing fullPage screenshot also takes ~50 s before it throws.
Suggested fix
decodeBase64 already checks length % 4 and that btoa(atob(value)) === value, which rejects non-canonical input. The regex therefore only needs to check the alphabet and padding, which a linear pattern without a quantified group can do:
const BASE64_PATTERN = /^[A-Za-z\d+/]*={0,2}$/;That tests 48 MiB in ~30 ms and still rejects ab=c, abc! and a=bc, with the round trip catching anything else.
Workaround
For screenshots, we grow the viewport to the page height (bounded) with page.setViewportSize(), take a viewport screenshot and then restore the viewport, instead of using fullPage: true.
Source: browserbase/stagehand