Open-source AI browser agent for Chrome and Firefox (monorepo) ðŸ§
JavaScript ai-agentai-agentsai-toolsbrowser-aibrowser-automationbrowser-extensionchrome-aichrome-devtoolschrome-extensionchrome-extensionsfirefox-addonfirefox-addonsfirefox-extensionfirefox-extensionsgemmagemma4minimaxoffline-aioffline-llmqwen
Merge main into CAPTCHA bridge PR and preserve regression coverage
Codex release-state testab566ce7e107
diff --cc test/captcha-callback-bridge-ui.mjsindex 725966d08,7ae0259cb..6c772edee--- a/test/captcha-callback-bridge-ui.mjs+++ b/test/captcha-callback-bridge-ui.mjs@@@ -115,96 -114,153 +125,201 @@@ try{pageUrl:input.target.frameUrl,pageContent:'button Continue'}, {});return {injection,gate};},{input});- assert.equal(outcome.gate?.status, 'cleared', JSON.stringify(outcome));+ if (mode !== 'field-remove') assert.equal(outcome.gate?.status, 'cleared', JSON.stringify(outcome));assertProgress('chrome',type,mode,outcome.injection,JSON.parse(await page.evaluate(probe)));}+ {+ // Remediation proof: the widget renders 1200ms after injection starts,+ // so only the settle retry can capture its closure.+ const type = 'hcaptcha', mode = 'callback';+ await page.goto(`${origin}/fixture?type=${type}&mode=${mode}&render=late`);+ const input = payload(type);input.target.frameUrl=page.url();+ await page.evaluate('window.renderWidgetDelayed(1200)');+ const outcome = await control.evaluate(async ({input}) => {+ const tabs = await chrome.tabs.query({});const tab=tabs.find(tab=>tab.url===input.target.frameUrl);+ const {injectToken}=await import(chrome.runtime.getURL('src/agent/captcha-solver.js'));+ const injection = await injectToken(tab.id,input);+ const { Agent } = await import(chrome.runtime.getURL('src/agent/agent.js'));+ const agent = new Agent({ getActive: () => ({ promptTier: 'full' }) });+ agent._captchaGateStates.set(tab.id, { pageUrl: input.target.frameUrl, status: 'verification_pending',+ publicGate: { status: 'verification_pending', solveAttempted: true }, captchaCandidateIdentity: { ...input.target } });+ const { gate } = await agent._observeCaptchaChallenge(tab.id, 'get_accessibility_tree',+ {pageUrl:input.target.frameUrl,pageContent:'button Continue'}, {});+ return {injection,gate};+ },{input});+ if (mode !== 'field-remove') assert.equal(outcome.gate?.status, 'cleared', JSON.stringify(outcome));+ assert.equal(outcome.injection.calledCallback, true, JSON.stringify(outcome.injection));+ assert.equal(outcome.injection.bridgeSettleRetried, true, 'late render must be captured by the settle retry');+ assertProgress('chrome',type,mode+'+late-render',outcome.injection,JSON.parse(await page.evaluate(probe)));+ }+ await control.evaluate(async () => {+ await chrome.storage.local.set({ twoCaptchaEnabled: false });+ for (let attempt = 0; attempt < 100; attempt += 1) {+ const [bridge] = await chrome.scripting.getRegisteredContentScripts({ ids: ['webbrain-captcha-callback-bridge'] });+ if (!bridge) return;+ await new Promise(resolve => setTimeout(resolve, 20));+ }+ throw new Error('CAPTCHA callback bridge stayed registered after disabling the provider');+ });+ await page.goto(`${origin}/fixture?type=turnstile&mode=callback®istration-probe=disabled-again`);+ assert.equal(JSON.parse(await page.evaluate(probe)).early, false, 'bridge should be removed when no provider is enabled');} finally {await context?.close();await rm(profile,{recursive:true,force:true});}- const profile2 = await mkdtemp(join(tmpdir(),'webbrain-captcha-firefox-'));- const child = spawn(process.env.FIREFOX_BINARY || (process.platform === 'darwin' ? '/Applications/Firefox.app/Contents/MacOS/firefox' : 'firefox'), ['--headless','--remote-allow-system-access','--no-remote','--profile',profile2,'--remote-debugging-port','0'], {stdio:['ignore','pipe','pipe']});- let session;- try {- const port = await new Promise((resolve,reject)=>{- const timer=setTimeout(()=>reject(Error('Firefox BiDi did not start')),20000);let output='';- child.stderr.on('data',data=>{output+=data;const match=output.match(/WebDriver BiDi listening on ws:\/\/127\.0\.0\.1:(\d+)/);if(match){clearTimeout(timer);resolve(Number(match[1]));}});- child.on('error',reject);- });- session=new BidiSession();await session.connect(port);- await session.send('webExtension.install',{extensionData:{type:'path',path:resolve('src/firefox')}});- let control;- for(let i=0;i<50&&!control;i++){- const tree=await session.send('browsingContext.getTree',{});control=tree.contexts.find(item=>item.url.startsWith('moz-extension://'));- if(!control)await new Promise(resolve=>setTimeout(resolve,100));- }- assert.ok(control,'extension onboarding context must exist');- const {context:page}=await session.send('browsingContext.create',{type:'tab'});- const evaluate=async(context,expression)=>{- const result=await session.send('script.evaluate',{target:{context},expression,awaitPromise:true});- if(result.type==='exception')throw Error(result.exceptionDetails.text);- return result.result.value;- };- for(const [type,mode] of scenarios){- const url=`${origin}/fixture?type=${type}&mode=${mode}`;- await session.send('browsingContext.navigate',{context:page,url,wait:'complete'});- const input=payload(type);input.target.frameUrl=url;- assert.equal(await evaluate(page,'!!window.__webbrainCaptchaCallbacks'), true, 'bridge must capture widgets before the solve');- const outcome=JSON.parse(await evaluate(control.context,`(async()=>{- const tabs=await browser.tabs.query({});const tab=tabs.find(tab=>tab.url===${JSON.stringify(url)});- const {injectToken}=await import(browser.runtime.getURL('src/agent/captcha-solver.js'));- const input=${JSON.stringify(input)};- const injection=await injectToken(tab.id,input);- const gate=await (${verifyGate.toString()})(tab.id,input,browser);- return JSON.stringify({injection,gate});- })()`));- if (mode !== 'field-remove') assert.equal(outcome.gate?.status, 'cleared', JSON.stringify(outcome));- assertProgress('firefox',type,mode,outcome.injection,JSON.parse(await evaluate(page,probe)));- }- {- // Remediation proof: the widget renders 1200ms after injection starts,- // so only the settle retry can capture its closure.- const type = 'hcaptcha', mode = 'callback';- const url=`${origin}/fixture?type=${type}&mode=${mode}&render=late`;- await session.send('browsingContext.navigate',{context:page,url,wait:'complete'});- const input=payload(type);input.target.frameUrl=url;- await evaluate(page,'window.renderWidgetDelayed(1200)');- const outcome=JSON.parse(await evaluate(control.context,`(async()=>{- const tabs=await browser.tabs.query({});const tab=tabs.find(tab=>tab.url===${JSON.stringify(url)});- const {injectToken}=await import(browser.runtime.getURL('src/agent/captcha-solver.js'));- const input=${JSON.stringify(input)};- const injection=await injectToken(tab.id,input);- const gate=await (${verifyGate.toString()})(tab.id,input,browser);- return JSON.stringify({injection,gate});- })()`));- if (mode !== 'field-remove') assert.equal(outcome.gate?.status, 'cleared', JSON.stringify(outcome));- assert.equal(outcome.injection.calledCallback, true, JSON.stringify(outcome.injection));- assert.equal(outcome.injection.bridgeSettleRetried, true, 'late render must be captured by the settle retry');- assertProgress('firefox',type,mode+'+late-render',outcome.injection,JSON.parse(await evaluate(page,probe)));- }- {- const url = `${origin}/fixture?type=hcaptcha&mode=callback&render=late`;- await session.send('browsingContext.navigate',{context:page,url,wait:'complete'});- await evaluate(page, `(async () => {- const outer = document.createElement('iframe'); outer.name = 'outer';- outer.srcdoc = '<iframe name="inner" srcdoc="<div id=widget data-sitekey=${sitekey}></div>"></iframe>';- const loaded = new Promise(resolve => outer.onload = resolve);- document.body.append(outer); await loaded;- const inner = outer.contentDocument.querySelector('iframe');- const child = window.descendant = inner.contentWindow;- child.resetFixture = () => {- // Simulate a document that never had the bridge, including its SDK- // property watchers, so reinstalling cannot reuse old registrations.- delete child.__webbrainCaptchaCallbacks;- delete child.hcaptcha; delete child.turnstile; delete child.grecaptcha;- child.document.getElementById('widget').replaceChildren();- child.accepted = null;- child.hcaptcha = {- render(id, params) {- const field = child.document.createElement('textarea');- field.name = 'h-captcha-response'; field.id = 'descendant-answer';- child.document.getElementById(id).append(field); return 'descendant-widget';- }, getResponse: () => ''- };- };- child.resetFixture();- child.renderFixture = () => child.hcaptcha.render('widget', {- sitekey: '${sitekey}', callback: token => { child.accepted = token; }- });+ const firefoxExecutable = process.env.FIREFOX_BINARY || (process.platform === 'darwin' ? '/Applications/Firefox.app/Contents/MacOS/firefox' : 'firefox');+ const firefoxProbe = spawnSync(firefoxExecutable, ['--version'], { stdio: 'ignore', timeout: 5000 });+ if (firefoxProbe.error?.code === 'ENOENT' && !process.env.FIREFOX_BINARY) {+ console.log('SKIP firefox CAPTCHA bridge UI test: Firefox is not installed or FIREFOX_BINARY is not on PATH');+ } else {+ if (firefoxProbe.error) throw firefoxProbe.error;+ if (firefoxProbe.status !== 0) throw new Error(`Firefox version check failed with status ${firefoxProbe.status}`);+ const profile2 = await mkdtemp(join(tmpdir(),'webbrain-captcha-firefox-'));+ const child = spawn(firefoxExecutable, ['--headless','--remote-allow-system-access','--no-remote','--profile',profile2,'--remote-debugging-port','0'], {stdio:['ignore','pipe','pipe']});+ let session;+ try {+ const port = await new Promise((resolve,reject)=>{+ const timer=setTimeout(()=>reject(Error('Firefox BiDi did not start')),20000);let output='';+ child.stderr.on('data',data=>{output+=data;const match=output.match(/WebDriver BiDi listening on ws:\/\/127\.0\.0\.1:(\d+)/);if(match){clearTimeout(timer);resolve(Number(match[1]));}});+ child.on('error',reject);+ });+ session=new BidiSession();await session.connect(port);+ await session.send('webExtension.install',{extensionData:{type:'path',path:resolve('src/firefox')}});+ let control;+ for(let i=0;i<50&&!control;i++){+ const tree=await session.send('browsingContext.getTree',{});control=tree.contexts.find(item=>item.url.startsWith('moz-extension://'));+ if(!control)await new Promise(resolve=>setTimeout(resolve,100));+ }+ assert.ok(control,'extension onboarding context must exist');+ const {context:page}=await session.send('browsingContext.create',{type:'tab'});+ const evaluate=async(context,expression)=>{+ const result=await session.send('script.evaluate',{target:{context},expression,awaitPromise:true});+ if(result.type==='exception')throw Error(result.exceptionDetails.text);+ return result.result.value;+ };+ await session.send('browsingContext.navigate',{context:page,url:`${origin}/fixture?type=turnstile&mode=callback®istration-probe=disabled`,wait:'complete'});+ assert.equal(JSON.parse(await evaluate(page,probe)).early,false,'bridge should stay absent when no provider is enabled');+ await evaluate(control.context, `(async()=>{+ await browser.storage.local.set({twoCaptchaApiKey:'00000000000000000000000000000000',twoCaptchaEnabled:true});+ return true;})()`);- const input = {fieldName:'h-captcha-response',token:'fixture-token',target:{- frameId:0,frameUrl:'about:srcdoc',websiteKey:sitekey,type:'hcaptcha',- responseFieldId:'descendant-answer',framePath:[- {index:0,frameUrl:'about:srcdoc',frameName:'outer'},- {index:0,frameUrl:'about:srcdoc',frameName:'inner'}- ]}};- for (const fallback of [false, true]) {- // Exercise MAIN scripting and the MV2 fallback in the actual descendant.- if (fallback) await evaluate(page, 'descendant.resetFixture()');- const installed = await evaluate(control.context, `(async () => {- const tab = (await browser.tabs.query({})).find(tab => tab.url === ${JSON.stringify(url)});- const {ensureCaptchaCallbackBridge} = await import(browser.runtime.getURL('src/agent/captcha-solver.js'));- const api = ${fallback ? '{runtime:browser.runtime,tabs:browser.tabs}' : 'browser'};- return ensureCaptchaCallbackBridge(tab.id, ${JSON.stringify(input.target)}, api);- })()`);- assert.equal(installed, true, `descendant bridge installation (fallback=${fallback})`);- assert.equal(await evaluate(page, '!!descendant.__webbrainCaptchaCallbacks'), true);- await evaluate(page, 'descendant.renderFixture()');- const result = JSON.parse(await evaluate(control.context, `(async () => {- const tab = (await browser.tabs.query({})).find(tab => tab.url === ${JSON.stringify(url)});- const {injectToken} = await import(browser.runtime.getURL('src/agent/captcha-solver.js'));- return JSON.stringify(await injectToken(tab.id, ${JSON.stringify(input)}));+ let bridgeReady=false;+ for(let attempt=0;attempt<30&&!bridgeReady;attempt++){+ await session.send('browsingContext.navigate',{context:page,url:`${origin}/fixture?type=turnstile&mode=callback®istration-probe=${attempt}`,wait:'complete'});+ bridgeReady=JSON.parse(await evaluate(page,probe)).early;+ if(!bridgeReady)await new Promise(resolve=>setTimeout(resolve,100));+ }+ assert.ok(bridgeReady,'CAPTCHA callback bridge should register after enabling a provider');+ for(const [type,mode] of scenarios){+ const url=`${origin}/fixture?type=${type}&mode=${mode}`;+ await session.send('browsingContext.navigate',{context:page,url,wait:'complete'});+ const input=payload(type);input.target.frameUrl=url;++ assert.equal(await evaluate(page,'!!window.__webbrainCaptchaCallbacks'), true, 'bridge must capture widgets before the solve');+ const outcome=JSON.parse(await evaluate(control.context,`(async()=>{+ const tabs=await browser.tabs.query({});const tab=tabs.find(tab=>tab.url===${JSON.stringify(url)});+ const {injectToken}=await import(browser.runtime.getURL('src/agent/captcha-solver.js'));+ const input=${JSON.stringify(input)};+ const injection=await injectToken(tab.id,input);+ const gate=await (${verifyGate.toString()})(tab.id,input,browser);+ return JSON.stringify({injection,gate});})()`));- assert.equal(outcome.gate?.status, 'cleared', JSON.stringify(outcome));- assert.equal(result.success, true, JSON.stringify(result));- assert.equal(result.calledCallback, true, JSON.stringify(result));- assert.equal(await evaluate(page, 'descendant.accepted'), 'fixture-token');++ if (mode !== 'field-remove') assert.equal(outcome.gate?.status, 'cleared', JSON.stringify(outcome));+ assertProgress('firefox',type,mode,outcome.injection,JSON.parse(await evaluate(page,probe)));+ }- console.log('PASS firefox: inherited-origin descendant bridge, MAIN and MV2 fallback, selected closure completion');++ {++ // Remediation proof: the widget renders 1200ms after injection starts,++ // so only the settle retry can capture its closure.++ const type = 'hcaptcha', mode = 'callback';++ const url=`${origin}/fixture?type=${type}&mode=${mode}&render=late`;++ await session.send('browsingContext.navigate',{context:page,url,wait:'complete'});++ const input=payload(type);input.target.frameUrl=url;++ await evaluate(page,'window.renderWidgetDelayed(1200)');++ const outcome=JSON.parse(await evaluate(control.context,`(async()=>{++ const tabs=await browser.tabs.query({});const tab=tabs.find(tab=>tab.url===${JSON.stringify(url)});++ const {injectToken}=await import(browser.runtime.getURL('src/agent/captcha-solver.js'));++ const input=${JSON.stringify(input)};++ const injection=await injectToken(tab.id,input);++ const gate=await (${verifyGate.toString()})(tab.id,input,browser);++ return JSON.stringify({injection,gate});++ })()`));++ if (mode !== 'field-remove') assert.equal(outcome.gate?.status, 'cleared', JSON.stringify(outcome));++ assert.equal(outcome.injection.calledCallback, true, JSON.stringify(outcome.injection));++ assert.equal(outcome.injection.bridgeSettleRetried, true, 'late render must be captured by the settle retry');++ assertProgress('firefox',type,mode+'+late-render',outcome.injection,JSON.parse(await evaluate(page,probe)));++ }++ {++ const url = `${origin}/fixture?type=hcaptcha&mode=callback&render=late`;++ await session.send('browsingContext.navigate',{context:page,url,wait:'complete'});++ await evaluate(page, `(async () => {++ const outer = document.createElement('iframe'); outer.name = 'outer';++ outer.srcdoc = '<iframe name="inner" srcdoc="<div id=widget data-sitekey=${sitekey}></div>"></iframe>';++ const loaded = new Promise(resolve => outer.onload = resolve);++ document.body.append(outer); await loaded;++ const inner = outer.contentDocument.querySelector('iframe');++ const child = window.descendant = inner.contentWindow;++ child.resetFixture = () => {++ // Simulate a document that never had the bridge, including its SDK++ // property watchers, so reinstalling cannot reuse old registrations.++ delete child.__webbrainCaptchaCallbacks;++ delete child.hcaptcha; delete child.turnstile; delete child.grecaptcha;++ child.document.getElementById('widget').replaceChildren();++ child.accepted = null;++ child.hcaptcha = {++ render(id, params) {++ const field = child.document.createElement('textarea');++ field.name = 'h-captcha-response'; field.id = 'descendant-answer';++ child.document.getElementById(id).append(field); return 'descendant-widget';++ }, getResponse: () => ''++ };++ };++ child.resetFixture();++ child.renderFixture = () => child.hcaptcha.render('widget', {++ sitekey: '${sitekey}', callback: token => { child.accepted = token; }++ });++ })()`);++ const input = {fieldName:'h-captcha-response',token:'fixture-token',target:{++ frameId:0,frameUrl:'about:srcdoc',websiteKey:sitekey,type:'hcaptcha',++ responseFieldId:'descendant-answer',framePath:[++ {index:0,frameUrl:'about:srcdoc',frameName:'outer'},++ {index:0,frameUrl:'about:srcdoc',frameName:'inner'}++ ]}};++ for (const fallback of [false, true]) {++ // Exercise MAIN scripting and the MV2 fallback in the actual descendant.++ if (fallback) await evaluate(page, 'descendant.resetFixture()');++ const installed = await evaluate(control.context, `(async () => {++ const tab = (await browser.tabs.query({})).find(tab => tab.url === ${JSON.stringify(url)});++ const {ensureCaptchaCallbackBridge} = await import(browser.runtime.getURL('src/agent/captcha-solver.js'));++ const api = ${fallback ? '{runtime:browser.runtime,tabs:browser.tabs}' : 'browser'};++ return ensureCaptchaCallbackBridge(tab.id, ${JSON.stringify(input.target)}, api);++ })()`);++ assert.equal(installed, true, `descendant bridge installation (fallback=${fallback})`);++ assert.equal(await evaluate(page, '!!descendant.__webbrainCaptchaCallbacks'), true);++ await evaluate(page, 'descendant.renderFixture()');++ const result = JSON.parse(await evaluate(control.context, `(async () => {++ const tab = (await browser.tabs.query({})).find(tab => tab.url === ${JSON.stringify(url)});++ const {injectToken} = await import(browser.runtime.getURL('src/agent/captcha-solver.js'));++ return JSON.stringify(await injectToken(tab.id, ${JSON.stringify(input)}));++ })()`));++ assert.equal(result.success, true, JSON.stringify(result));++ assert.equal(result.calledCallback, true, JSON.stringify(result));++ assert.equal(await evaluate(page, 'descendant.accepted'), 'fixture-token');++ }++ console.log('PASS firefox: inherited-origin descendant bridge, MAIN and MV2 fallback, selected closure completion');+ }+ await evaluate(control.context, `(async()=>{await browser.storage.local.set({twoCaptchaEnabled:false});return true;})()`);+ let bridgeRemoved=false;+ for(let attempt=0;attempt<30&&!bridgeRemoved;attempt++){+ await session.send('browsingContext.navigate',{context:page,url:`${origin}/fixture?type=turnstile&mode=callback®istration-probe=disabled-again-${attempt}`,wait:'complete'});+ bridgeRemoved=!JSON.parse(await evaluate(page,probe)).early;+ if(!bridgeRemoved)await new Promise(resolve=>setTimeout(resolve,100));+ }+ assert.ok(bridgeRemoved,'CAPTCHA callback bridge should be removed when no provider is enabled');+ } finally {+ session?.socket?.close();+ if (child.pid && child.exitCode === null && child.signalCode === null) {+ const exited = new Promise(resolve => child.once('exit', resolve));+ child.kill();+ await exited;+ }+ await rm(profile2,{recursive:true,force:true});}- } finally {session?.socket?.close();child.kill();await new Promise(resolve=>child.once('exit',resolve));await rm(profile2,{recursive:true,force:true});}+ }} finally {server.close();}diff --cc test/captcha-callback-bridge.mjsindex f1ecef60b,241357566..d7cc0d8af--- a/test/captcha-callback-bridge.mjs+++ b/test/captcha-callback-bridge.mjs@@@ -119,10 -120,100 +120,98 @@@ for (const build of ['chrome', 'firefoxassert.equal(f.inject().calledCallback, false);assert.equal(f.context.answers.length, 1);});- test(`${build}: bridge is not injected into every page by default`, async () => {+ for (const mode of ['field', 'removed', 'late-callback', 'navigated']) {+ test(`${build}: settle retry preserves ${mode} application without replaying field events`, async () => {+ const f = fixture();+ f.render('one', 'undefined');+ let events = 0, attempts = 0;+ f.fields[0].dispatchEvent = event => {+ events++;+ if (event.type === 'change' && mode === 'removed') f.fields.shift();+ };+ const input = { fieldName: f.name, token: 'paid-token', callbackHint: 'lateComplete',+ target: { frameId: 0, frameUrl: f.context.location.href, websiteKey: 'site-key',+ type: 'hcaptcha', responseFieldId: 'answer-one', documentTimeOrigin: 1000 } };+ const beforeAttempt = () => {+ attempts++;+ if (attempts === 2 && mode === 'navigated') throw new Error('frame navigated');+ if (attempts === 2 && mode === 'late-callback') f.evaluate('lateComplete = token => answers.push(token)');+ };+ const api = {+ scripting: { executeScript: async options => {+ if (options.files) return [];+ beforeAttempt();+ return [{ frameId: 0, result: options.func(options.args[0], { document: f.context.document, window: f.context }) }];+ } },+ tabs: { executeScript: async (_, options) => {+ beforeAttempt();+ return [f.evaluate(options.code)];+ } },+ };+ const namespace = build === 'firefox' ? 'browser' : 'chrome';+ const previous = globalThis[namespace];+ globalThis[namespace] = api;+ try {+ const result = await injectToken(1, input);+ assert.equal(result.success, true, JSON.stringify(result));+ assert.equal(result.fieldUpdated, true);+ assert.equal(result.fieldsTouched, 1);+ assert.equal(result.bridgeSettleRetried, true);+ assert.equal(result.calledCallback, mode === 'late-callback');+ assert.equal(events, 2, 'one input/change pair, even when callback discovery retries');+ assert.equal(attempts, 2);+ assert.deepEqual(JSON.parse(JSON.stringify(f.context.answers)), mode === 'late-callback' ? ['paid-token'] : []);+ } finally {+ if (previous === undefined) delete globalThis[namespace]; else globalThis[namespace] = previous;+ }+ });+ }+ if (build === 'firefox') for (const fallback of [false, true]) {+ test(`firefox: descendant installation validates the full frame path (fallback=${fallback})`, async () => {+ const f = fixture();+ f.context.location.href = 'about:srcdoc';+ f.context.name = 'inner';+ f.evaluate('delete window.__webbrainCaptchaCallbacks');+ let loads = 0;+ f.context.document.createElement = () => ({ remove() {} });+ f.context.document.head = { appendChild(script) { loads++; f.evaluate(source); script.onload(); } };+ const outerWindow = { location: { href: 'about:blank' }, name: 'outer' };+ const outerDocument = { querySelectorAll: () => [{ contentWindow: f.context, contentDocument: f.context.document }] };+ const rootDocument = { querySelectorAll: () => [{ contentWindow: outerWindow, contentDocument: outerDocument }] };+ const root = vm.createContext({ document: rootDocument, setTimeout, clearTimeout });+ root.window = root;+ root.__webbrainCaptchaCallbacks = { callbacks() {} };+ const target = { frameId: 0, frameUrl: 'about:srcdoc', documentTimeOrigin: 1000,+ framePath: [{ index: 0, frameUrl: 'about:blank', frameName: 'outer' },+ { index: 0, frameUrl: 'about:srcdoc', frameName: 'inner' }] };+ const api = { runtime: { getURL: file => `moz-extension://fixture/${file}` },+ ...(fallback ? {} : { scripting: { executeScript: async options => [{ result: await vm.runInContext(+ `(${options.func.toString()})(...${JSON.stringify(options.args)})`, root) }] } }),+ tabs: { executeScript: async (_, options) => [await vm.runInContext(options.code, root)] } };+ assert.equal(await ensureCaptchaCallbackBridge(1, target, api), true);+ assert.equal(loads, 1, 'load into the descendant even when the ancestor already has a bridge');+ assert.equal(typeof f.context.__webbrainCaptchaCallbacks.callbacks, 'function');+ for (const stale of [+ { ...target, framePath: [{ ...target.framePath[0], index: 1 }] },+ { ...target, framePath: [{ ...target.framePath[0], frameName: 'changed' }] },+ { ...target, frameUrl: 'about:blank' },+ { ...target, documentTimeOrigin: 2000 },+ ]) assert.equal(await ensureCaptchaCallbackBridge(1, stale, api), false);+ assert.equal(loads, 1, 'stale paths and documents must not install another bridge');+ });+ }- test(`${build}: bridge captures page-load widgets and is ensured in the selected document`, async () => {++ test(`${build}: bridge is scoped to provider settings and ensured in the selected document`, async () => {const manifest = JSON.parse(await readFile(new URL(`../src/${build}/manifest.json`, import.meta.url), 'utf8'));- const entry = manifest.content_scripts.find(entry => entry.js?.includes('src/content/captcha-callback-bridge.js'));- assert.equal(entry, undefined);+ const entries = (manifest.content_scripts || []).filter(entry => entry.js?.includes('src/content/captcha-callback-bridge.js'));- assert.equal(entries.length, 1);- assert.equal(entries[0].world, 'MAIN'); assert.equal(entries[0].run_at, 'document_start');- assert.equal(entries[0].all_frames, true); assert.equal(entries[0].match_about_blank, true);++ assert.equal(entries.length, 0, 'the bridge must be registered dynamically only while a provider is enabled');+ const solver = await readFile(new URL(`../src/${build}/src/agent/captcha-solver.js`, import.meta.url), 'utf8');+ assert.match(solver, /export async function ensureCaptchaCallbackBridge\(tabId/);+ assert.match(solver, /await ensureCaptchaCallbackBridge\(tabId, target\)/);+ assert.match(solver, /captcha-callback-bridge\.js/);+ assert.match(solver, /CAPTCHA_BRIDGE_SETTLE_RETRY_MS/);+ assert.match(solver, /bridgeSettleRetried/);+ const agent = await readFile(new URL(`../src/${build}/src/agent/agent.js`, import.meta.url), 'utf8');+ assert.match(agent, /await ensureCaptchaCallbackBridge\(tabId, detected\)/);});}test('callback bridge is identical in Chrome and Firefox', async () => {