Skip to content

Open-source AI browser agent for Chrome and Firefox (monorepo) 🧠

fix(captcha): scope callback bridge to enabled providers

16Miku18ee6cc3ef09
diff --git a/package.json b/package.json
index bb5169848..a6c185978 100644
--- a/package.json
+++ b/package.json
@@ -5,7 +5,7 @@
"private": true,
"type": "module",
"scripts": {
- "test": "npm run test:cms && npm run test:markdown && npm run test:generative-media && npm run test:systemone && npm run test:systemone:fast && node --test test/browser-dialogs.mjs test/capsolver-cloud-broker.mjs test/captcha-providers.mjs test/captcha-weighted-fallback.mjs test/captcha-hcaptcha-providers.mjs test/captcha-native-providers.mjs test/captcha-runtime-policy.mjs test/captcha-callback-bridge.mjs test/captcha-aws-recovery.mjs test/captcha-documented-contracts.mjs test/huggingface-signup-recovery.mjs test/trace-full-export.mjs test/feedback-traces.mjs && npm run test:firefox-bidi && npm run test:runtime-lifecycle && npm run test:billing-notice && npm run test:compass-quota && npm run test:provider-limits && npm run test:provider-catalog && npm run test:openrouter-capabilities && npm run test:accessibility-tree-benchmark && npm run test:toolbar-guard && npm run test:cloud-bridge-approval && npm run test:discord && npm run test:pdf-read && npm run test:pdf-selection && npm run test:social-contract && npm run test:safesocial && npm run test:build-unpacked && npm run test:attachment-drop && npm run test:workflow-editor && node --test test/profile-sync-stats.mjs && node --test test/memcode-recall.mjs && node test/run.js && node test/selection-scope-restoration.mjs && node scripts/benchmark-offline-relevance.mjs && npm run test:security",
+ "test": "npm run test:cms && npm run test:markdown && npm run test:generative-media && npm run test:systemone && npm run test:systemone:fast && node --test test/browser-dialogs.mjs test/capsolver-cloud-broker.mjs test/captcha-providers.mjs test/captcha-weighted-fallback.mjs test/captcha-hcaptcha-providers.mjs test/captcha-native-providers.mjs test/captcha-runtime-policy.mjs test/captcha-callback-bridge.mjs test/captcha-bridge-registration.mjs test/captcha-aws-recovery.mjs test/captcha-documented-contracts.mjs test/huggingface-signup-recovery.mjs test/trace-full-export.mjs test/feedback-traces.mjs && npm run test:firefox-bidi && npm run test:runtime-lifecycle && npm run test:billing-notice && npm run test:compass-quota && npm run test:provider-limits && npm run test:provider-catalog && npm run test:openrouter-capabilities && npm run test:accessibility-tree-benchmark && npm run test:toolbar-guard && npm run test:cloud-bridge-approval && npm run test:discord && npm run test:pdf-read && npm run test:pdf-selection && npm run test:social-contract && npm run test:safesocial && npm run test:build-unpacked && npm run test:attachment-drop && npm run test:workflow-editor && node --test test/profile-sync-stats.mjs && node --test test/memcode-recall.mjs && node test/run.js && node test/selection-scope-restoration.mjs && node scripts/benchmark-offline-relevance.mjs && npm run test:security",
"test:captcha:ui": "node test/captcha-settings-ui.mjs && node test/captcha-application-ui.mjs",
"test:captcha:bridge:ui": "node test/captcha-callback-bridge-ui.mjs",
"test:billing-notice": "node test/billing-payment-notice.mjs",
diff --git a/src/chrome/manifest.json b/src/chrome/manifest.json
index 584c5ecfd..9661b18f3 100644
--- a/src/chrome/manifest.json
+++ b/src/chrome/manifest.json
@@ -46,14 +46,6 @@
"type": "module"
},
"content_scripts": [
- {
- "matches": ["<all_urls>"],
- "js": ["src/content/captcha-callback-bridge.js"],
- "run_at": "document_start",
- "world": "MAIN",
- "all_frames": true,
- "match_about_blank": true
- },
{
"matches": ["<all_urls>"],
"js": ["src/content/file-picker-guard-page.js"],
diff --git a/src/chrome/src/agent/captcha-bridge-registration.js b/src/chrome/src/agent/captcha-bridge-registration.js
new file mode 100644
index 000000000..6a9c9456f
--- /dev/null
+++ b/src/chrome/src/agent/captcha-bridge-registration.js
@@ -0,0 +1,62 @@
+const SCRIPT_ID = 'webbrain-captcha-callback-bridge';
+const SCRIPT_FILE = 'src/content/captcha-callback-bridge.js';
+const MATCHES = ['<all_urls>'];
+
+export function createCaptchaBridgeRegistration(api) {
+ let firefoxRegistration = null;
+ let queue = Promise.resolve();
+
+ async function reconcile(enabled) {
+ if (api.contentScripts?.register) {
+ if (enabled && !firefoxRegistration) {
+ firefoxRegistration = await api.contentScripts.register({
+ matches: [...MATCHES],
+ js: [{ file: SCRIPT_FILE }],
+ runAt: 'document_start',
+ world: 'MAIN',
+ allFrames: true,
+ matchAboutBlank: true,
+ });
+ } else if (!enabled && firefoxRegistration) {
+ const registration = firefoxRegistration;
+ await registration.unregister();
+ if (firefoxRegistration === registration) firefoxRegistration = null;
+ }
+ return;
+ }
+
+ const scripting = api.scripting;
+ if (typeof scripting?.getRegisteredContentScripts !== 'function'
+ || typeof scripting.registerContentScripts !== 'function'
+ || typeof scripting.unregisterContentScripts !== 'function') {
+ throw new Error('Dynamic CAPTCHA bridge registration is not supported by this browser.');
+ }
+
+ const [registered] = await scripting.getRegisteredContentScripts({ ids: [SCRIPT_ID] });
+ if (enabled && !registered) {
+ await scripting.registerContentScripts([{
+ id: SCRIPT_ID,
+ matches: [...MATCHES],
+ js: [SCRIPT_FILE],
+ runAt: 'document_start',
+ world: 'MAIN',
+ allFrames: true,
+ matchOriginAsFallback: true,
+ persistAcrossSessions: false,
+ }]);
+ } else if (!enabled && registered) {
+ await scripting.unregisterContentScripts({ ids: [SCRIPT_ID] });
+ }
+ }
+
+ return {
+ sync(enabled) {
+ const operation = queue.then(
+ () => reconcile(enabled === true),
+ () => reconcile(enabled === true),
+ );
+ queue = operation.catch(() => {});
+ return operation;
+ },
+ };
+}
diff --git a/src/chrome/src/background.js b/src/chrome/src/background.js
index cd62044d1..e0e5321e8 100644
--- a/src/chrome/src/background.js
+++ b/src/chrome/src/background.js
@@ -55,6 +55,7 @@ import { isCapsolverEnabled } from './agent/capsolver-config.js';
import { testImageGenProvider } from './agent/fal-media.js';
import { IMAGE_GEN_MODEL_KEY } from './agent/media-config.js';
import { CAPTCHA_SETTINGS_KEYS, getCaptchaProviders } from './agent/captcha-provider-config.js';
+import { createCaptchaBridgeRegistration } from './agent/captcha-bridge-registration.js';
import { getAdditionalCaptchaBalance } from './agent/captcha-additional-providers.js';
import { getTwoCaptchaBalance } from './agent/two-captcha.js';
import { createSystemOneJudge } from './agent/systemone-judge.js';
@@ -1107,13 +1108,15 @@ const customSkillsReady = loadCustomSkills();
// Local browsers require a valid key and explicit consent. Managed Cloud
// browsers use the broker flag and never use a CapSolver key from storage.
+const captchaBridgeRegistration = createCaptchaBridgeRegistration(chrome);
async function loadCaptchaSolver() {
const stored = await chrome.storage.local.get(CAPTCHA_SETTINGS_KEYS);
const providers = getCaptchaProviders(stored);
agent.captchaProviderIds = providers.map(provider => provider.id);
agent.captchaSolverEnabled = providers.length > 0;
+ await captchaBridgeRegistration.sync(agent.captchaSolverEnabled);
}
-loadCaptchaSolver();
+loadCaptchaSolver().catch(error => console.warn('[WebBrain] CAPTCHA settings could not be loaded', error));
function normalizePlanBeforeActMode(stored = {}) {
if (stored.planBeforeActMode === 'try' || stored.planBeforeActMode === 'strict' || stored.planBeforeActMode === 'off') {
diff --git a/src/firefox/manifest.json b/src/firefox/manifest.json
index 83d8267e7..20b9e8b9e 100644
--- a/src/firefox/manifest.json
+++ b/src/firefox/manifest.json
@@ -36,14 +36,6 @@
}
},
"content_scripts": [
- {
- "matches": ["<all_urls>"],
- "js": ["src/content/captcha-callback-bridge.js"],
- "run_at": "document_start",
- "world": "MAIN",
- "all_frames": true,
- "match_about_blank": true
- },
{
"matches": ["<all_urls>"],
"js": ["src/content/file-picker-guard-loader.js"],
diff --git a/src/firefox/src/agent/captcha-bridge-registration.js b/src/firefox/src/agent/captcha-bridge-registration.js
new file mode 100644
index 000000000..6a9c9456f
--- /dev/null
+++ b/src/firefox/src/agent/captcha-bridge-registration.js
@@ -0,0 +1,62 @@
+const SCRIPT_ID = 'webbrain-captcha-callback-bridge';
+const SCRIPT_FILE = 'src/content/captcha-callback-bridge.js';
+const MATCHES = ['<all_urls>'];
+
+export function createCaptchaBridgeRegistration(api) {
+ let firefoxRegistration = null;
+ let queue = Promise.resolve();
+
+ async function reconcile(enabled) {
+ if (api.contentScripts?.register) {
+ if (enabled && !firefoxRegistration) {
+ firefoxRegistration = await api.contentScripts.register({
+ matches: [...MATCHES],
+ js: [{ file: SCRIPT_FILE }],
+ runAt: 'document_start',
+ world: 'MAIN',
+ allFrames: true,
+ matchAboutBlank: true,
+ });
+ } else if (!enabled && firefoxRegistration) {
+ const registration = firefoxRegistration;
+ await registration.unregister();
+ if (firefoxRegistration === registration) firefoxRegistration = null;
+ }
+ return;
+ }
+
+ const scripting = api.scripting;
+ if (typeof scripting?.getRegisteredContentScripts !== 'function'
+ || typeof scripting.registerContentScripts !== 'function'
+ || typeof scripting.unregisterContentScripts !== 'function') {
+ throw new Error('Dynamic CAPTCHA bridge registration is not supported by this browser.');
+ }
+
+ const [registered] = await scripting.getRegisteredContentScripts({ ids: [SCRIPT_ID] });
+ if (enabled && !registered) {
+ await scripting.registerContentScripts([{
+ id: SCRIPT_ID,
+ matches: [...MATCHES],
+ js: [SCRIPT_FILE],
+ runAt: 'document_start',
+ world: 'MAIN',
+ allFrames: true,
+ matchOriginAsFallback: true,
+ persistAcrossSessions: false,
+ }]);
+ } else if (!enabled && registered) {
+ await scripting.unregisterContentScripts({ ids: [SCRIPT_ID] });
+ }
+ }
+
+ return {
+ sync(enabled) {
+ const operation = queue.then(
+ () => reconcile(enabled === true),
+ () => reconcile(enabled === true),
+ );
+ queue = operation.catch(() => {});
+ return operation;
+ },
+ };
+}
diff --git a/src/firefox/src/background.js b/src/firefox/src/background.js
index 3a8d72cca..0ab5ea7e9 100644
--- a/src/firefox/src/background.js
+++ b/src/firefox/src/background.js
@@ -56,6 +56,7 @@ import { isCapsolverEnabled } from './agent/capsolver-config.js';
import { testImageGenProvider } from './agent/fal-media.js';
import { IMAGE_GEN_MODEL_KEY } from './agent/media-config.js';
import { CAPTCHA_SETTINGS_KEYS, getCaptchaProviders } from './agent/captcha-provider-config.js';
+import { createCaptchaBridgeRegistration } from './agent/captcha-bridge-registration.js';
import { getAdditionalCaptchaBalance } from './agent/captcha-additional-providers.js';
import { getTwoCaptchaBalance } from './agent/two-captcha.js';
import { createSystemOneJudge } from './agent/systemone-judge.js';
@@ -1000,13 +1001,15 @@ const customSkillsReady = loadCustomSkills();
// Local browsers require a valid key and explicit consent. Managed Cloud
// browsers use the broker flag and never use a CapSolver key from storage.
+const captchaBridgeRegistration = createCaptchaBridgeRegistration(browser);
async function loadCaptchaSolver() {
const stored = await browser.storage.local.get(CAPTCHA_SETTINGS_KEYS);
const providers = getCaptchaProviders(stored);
agent.captchaProviderIds = providers.map(provider => provider.id);
agent.captchaSolverEnabled = providers.length > 0;
+ await captchaBridgeRegistration.sync(agent.captchaSolverEnabled);
}
-loadCaptchaSolver();
+loadCaptchaSolver().catch(error => console.warn('[WebBrain] CAPTCHA settings could not be loaded', error));
function normalizePlanBeforeActMode(stored = {}) {
if (stored.planBeforeActMode === 'try' || stored.planBeforeActMode === 'strict' || stored.planBeforeActMode === 'off') {
diff --git a/test/captcha-bridge-registration.mjs b/test/captcha-bridge-registration.mjs
new file mode 100644
index 000000000..dfb8d3214
--- /dev/null
+++ b/test/captcha-bridge-registration.mjs
@@ -0,0 +1,103 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { readFile } from 'node:fs/promises';
+
+for (const build of ['chrome', 'firefox']) {
+ const { createCaptchaBridgeRegistration } = await import(`../src/${build}/src/agent/captcha-bridge-registration.js`);
+
+ test(`${build} registers the page bridge only while a CAPTCHA provider is enabled`, async () => {
+ if (build === 'chrome') {
+ let registered = [];
+ const api = { scripting: {
+ getRegisteredContentScripts: async ({ ids }) => registered.filter(script => ids.includes(script.id)),
+ registerContentScripts: async scripts => { registered.push(...scripts); },
+ unregisterContentScripts: async ({ ids }) => { registered = registered.filter(script => !ids.includes(script.id)); },
+ } };
+ const registration = createCaptchaBridgeRegistration(api);
+
+ await registration.sync(false);
+ assert.equal(registered.length, 0);
+ await registration.sync(true);
+ assert.equal(registered.length, 1);
+ assert.deepEqual(registered[0], {
+ id: 'webbrain-captcha-callback-bridge',
+ matches: ['<all_urls>'],
+ js: ['src/content/captcha-callback-bridge.js'],
+ runAt: 'document_start',
+ world: 'MAIN',
+ allFrames: true,
+ matchOriginAsFallback: true,
+ persistAcrossSessions: false,
+ });
+ await registration.sync(true);
+ assert.equal(registered.length, 1);
+ await registration.sync(false);
+ assert.equal(registered.length, 0);
+ return;
+ }
+
+ let script = null;
+ let unregisterCount = 0;
+ const api = { contentScripts: {
+ register: async options => {
+ script = options;
+ return { unregister: async () => { script = null; unregisterCount += 1; } };
+ },
+ } };
+ const registration = createCaptchaBridgeRegistration(api);
+
+ await registration.sync(false);
+ assert.equal(script, null);
+ await registration.sync(true);
+ assert.deepEqual(script, {
+ matches: ['<all_urls>'],
+ js: [{ file: 'src/content/captcha-callback-bridge.js' }],
+ runAt: 'document_start',
+ world: 'MAIN',
+ allFrames: true,
+ matchAboutBlank: true,
+ });
+ await registration.sync(true);
+ assert.equal(unregisterCount, 0);
+ await registration.sync(false);
+ assert.equal(script, null);
+ assert.equal(unregisterCount, 1);
+ });
+
+ test(`${build} reconciles overlapping provider changes in order`, async () => {
+ if (build === 'chrome') {
+ let registered = [];
+ const api = { scripting: {
+ getRegisteredContentScripts: async ({ ids }) => registered.filter(script => ids.includes(script.id)),
+ registerContentScripts: async scripts => {
+ await new Promise(resolve => setImmediate(resolve));
+ registered.push(...scripts);
+ },
+ unregisterContentScripts: async ({ ids }) => { registered = registered.filter(script => !ids.includes(script.id)); },
+ } };
+ const registration = createCaptchaBridgeRegistration(api);
+ await Promise.all([registration.sync(true), registration.sync(false)]);
+ assert.equal(registered.length, 0);
+ return;
+ }
+
+ let script = null;
+ const api = { contentScripts: {
+ register: async () => {
+ await new Promise(resolve => setImmediate(resolve));
+ script = true;
+ return { unregister: async () => { script = null; } };
+ },
+ } };
+ const registration = createCaptchaBridgeRegistration(api);
+ await Promise.all([registration.sync(true), registration.sync(false)]);
+ assert.equal(script, null);
+ });
+}
+
+test('Chrome and Firefox use the same registration state machine', async () => {
+ assert.equal(
+ await readFile(new URL('../src/chrome/src/agent/captcha-bridge-registration.js', import.meta.url), 'utf8'),
+ await readFile(new URL('../src/firefox/src/agent/captcha-bridge-registration.js', import.meta.url), 'utf8'),
+ );
+});
diff --git a/test/captcha-callback-bridge-ui.mjs b/test/captcha-callback-bridge-ui.mjs
index e7700c42a..725966d08 100644
--- a/test/captcha-callback-bridge-ui.mjs
+++ b/test/captcha-callback-bridge-ui.mjs
@@ -7,7 +7,7 @@ import { createServer } from 'node:http';
import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { resolve, join } from 'node:path';
-import { spawn } from 'node:child_process';
+import { spawn, spawnSync } from 'node:child_process';
import { BidiSession } from '../firefox-companion/session.mjs';
const sitekey = '10000000-ffff-ffff-ffff-000000000001';
@@ -89,6 +89,17 @@ try {
const control = await context.newPage();
await control.goto(new URL('/src/ui/settings.html', worker.url()).href);
const page = await context.newPage();
+ await page.goto(`${origin}/fixture?type=turnstile&mode=callback&registration-probe=disabled`);
+ assert.equal(JSON.parse(await page.evaluate(probe)).early, false, 'bridge should stay absent when no provider is enabled');
+ await control.evaluate(async () => {
+ await chrome.storage.local.set({ twoCaptchaApiKey: '00000000000000000000000000000000', twoCaptchaEnabled: true });
+ 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 was not registered after enabling a provider');
+ });
for (const [type, mode] of scenarios) {
await page.goto(`${origin}/fixture?type=${type}&mode=${mode}`);
const input = payload(type);input.target.frameUrl=page.url();
@@ -107,45 +118,93 @@ try {
assert.equal(outcome.gate?.status, 'cleared', JSON.stringify(outcome));
assertProgress('chrome',type,mode,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&registration-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;
- 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));
- assertProgress('firefox',type,mode,outcome.injection,JSON.parse(await evaluate(page,probe)));
+ 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&registration-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;
+ })()`);
+ 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&registration-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;
+ 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));
+ assertProgress('firefox',type,mode,outcome.injection,JSON.parse(await evaluate(page,probe)));
+ }
+ 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&registration-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 --git a/test/captcha-callback-bridge.mjs b/test/captcha-callback-bridge.mjs
index bb6d92aa1..f1ecef60b 100644
--- a/test/captcha-callback-bridge.mjs
+++ b/test/captcha-callback-bridge.mjs
@@ -119,11 +119,10 @@ for (const build of ['chrome', 'firefox']) {
assert.equal(f.inject().calledCallback, false);
assert.equal(f.context.answers.length, 1);
});
- test(`${build}: bridge manifest runs before site scripts in every matching frame`, async () => {
+ test(`${build}: bridge is not injected into every page by default`, 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.world, 'MAIN'); assert.equal(entry.run_at, 'document_start');
- assert.equal(entry.all_frames, true); assert.equal(entry.match_about_blank, true);
+ assert.equal(entry, undefined);
});
}
test('callback bridge is identical in Chrome and Firefox', async () => {