Skip to content

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

fix(captcha): deliver callbacks and recover solve state

Codex release-state testde9ad20d3d36
diff --git a/docs/captcha-provider-coverage.md b/docs/captcha-provider-coverage.md
index 8cd6ac87c..6ff2df2b2 100644
--- a/docs/captcha-provider-coverage.md
+++ b/docs/captcha-provider-coverage.md
@@ -86,10 +86,18 @@ Automatic detection still validates the hCaptcha UUID site key and observed `rqd
Most adapters use a 180-second job deadline and 30-second HTTP requests. The original direct CapSolver route retains its 120-second polling deadline. NopeCHA/NoneCap poll every two seconds; generic JSON providers every five seconds. SolveCaptcha waits 20 seconds initially for reCAPTCHA and five seconds for other tasks. Actual completion time is provider-dependent.
+Pending responses keep polling the existing job. NopeCHA accepts both the [v1 `code: 14`](https://nopecha.com/api-reference/) and [legacy `error: 14`](https://developers.nopecha.com/recognition/hcaptcha/) forms, including numeric strings, on successful HTTP responses or HTTP 409. This applies only to result retrieval; a rejected submission is never recreated. CapSolver's native route accepts its documented [`idle` and `processing`](https://docs.capsolver.com/en/guide/api-gettaskresult/) states. Authentication, balance, rate-limit and server failures remain errors.
+
+After manual completion navigates to another page, the next accessibility read confirms the current URL and checks document identity or completely inspects the old widget and challenge before retiring the previous page's CAPTCHA gate. A confirmed replacement document also retires the gate on a same-URL reload, during a page read or before another solve; unchanged or unreadable document identity keeps the paid lock. This also works with partial or interactive-only reads and with gates restored after a restart. A pathname change within the same document retains the failed-solve lock while the original widget remains. Unverified URLs, incomplete frame inspection, query-only changes, and missing dialog text alone do not clear an unresolved widget.
+
## Automatic widgets and native methods
### Automatic route
+The extension captures callbacks passed to `hcaptcha.render()`, `turnstile.render()`, and `grecaptcha.render()` (including Enterprise) at document start in each matching frame. This supports function closures without a global `data-callback` name. The callback is matched to the selected response field and site key, invoked at most once per widget generation, and invalidated by reset/removal. hCaptcha's [`execute(widgetID, { async: true })`](https://docs.hcaptcha.com/configuration/#asynchronous-mode-get-a-promise) continuation receives the same answer; `getResponse()` and, when supplied by the provider, `getRespKey()` agree with that answer. Page acceptance still requires a fresh inspection: invoking the callback does not clear a visible, rejected challenge.
+
+After updating/reloading the extension, refresh an already-open CAPTCHA page before solving. Existing page closures cannot be recovered retroactively. Named callbacks and the existing reCAPTCHA client discovery remain available for older tabs. The bridge records page registrations only; it does not make provider requests or change the site's submission flow by itself.
+
`solve_captcha` without `providerTasks` retains frame-aware detection for reCAPTCHA, hCaptcha, and standalone Turnstile. Image-to-text takes explicit image bytes. It checks the selected frame, site key, Enterprise flags, action, and available metadata before spending. Ambiguous frames require a discriminator from the returned candidates.
The original five providers have the built-in six-type mappings; NopeCHA and NoneCap have the built-in hCaptcha mapping. Other listed capabilities, including NopeCHA reCAPTCHA/Turnstile/recognition, are callable through the native route. A family appearing in Settings is API coverage, not a promise of automatic DOM detection on every website.
@@ -196,6 +204,10 @@ Solving transmits the supplied challenge information to each attempted provider:
A local preflight failure reports `dispatched: false`. Once a create request may have been sent, a failure reports dispatch rather than implying that nothing happened. Applying a solution has its own page-change boundary. Page rejection never triggers a second fallback cycle.
+Automatic widget solves save the selected widget and a paid-attempt gate before contacting a provider, including when the model calls `solve_captcha` directly from a screenshot before any accessibility read. The saved gate prevents another paid attempt after a provider failure, failed application, or worker restart. With `inject: false`, the provider answer is saved against the observed page/frame document identities and returned with `applicationRequired: true`. Use `apply_captcha_solution` with observed field/callback bindings and `path: "token"`; `get_captcha_capabilities` retrieves the pending answer after restart. The same answer is applied at most once, and expiry or document replacement makes it unusable without authorizing another solve for the old document. If the gate cannot be saved, no request is sent. Injection and callback diagnostics precede the full token in tool results so long tokens do not hide them in shortened trace exports.
+
+The CAPTCHA gate permits `done` with `outcome: "failed"` or `"partial"` in every gate state. Cancelling or reporting blocked work must not require a solve. This exception does not authorize page mutations or bypass verification for successful completion.
+
**Managed Cloud is separate.** Managed browsers continue using the server-side CapSolver broker and ignore personal keys and weights. Native catalog discovery/submission is excluded for that route. This change does not expand or deploy the server-side broker's allowlist, quotas, or billing.
## Troubleshooting
@@ -206,6 +218,7 @@ A local preflight failure reports `dispatched: false`. Once a create request may
| hCaptcha says no provider | Enable NopeCHA or NoneCap. A CapSolver/2Captcha/CapMonster/SolveCaptcha/Anti-Captcha key does not enable hCaptcha in this catalog. |
| Required-field error | Read that exact method's schema; obtain fresh page values. It has not spent a solve. |
| Token returned but page stays blocked | Correct target frame/callback, freshness, Enterprise metadata, IP/User-Agent requirements, and site acceptance. Do not buy another solve automatically. |
+| NopeCHA reports “Incomplete job” as an error | Check the request stage, HTTP status and numeric code now included in the error. Known pending responses are polled; submission errors and terminal HTTP failures are not retried. |
| Native result has coordinates/cookies/object fields | Use suitable answer bindings or a site-specific handler, not a token textarea by assumption. |
| Balance is credits instead of currency | Expected for NopeCHA and NoneCap; their pricing units differ from dollar-balance providers. |
| More than one provider charged | Expected when earlier jobs failed/timed out and fallback ran. A timeout does not cancel an accepted upstream job. |
diff --git a/package.json b/package.json
index dd7bafe10..81c65e94d 100644
--- a/package.json
+++ b/package.json
@@ -5,8 +5,9 @@
"private": true,
"type": "module",
"scripts": {
- "test": "npm run test:cms && npm run test:markdown && 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 && npm run test:firefox-bidi && npm run test:runtime-lifecycle && npm run test:provider-limits && npm run test:accessibility-tree-benchmark && npm run test:toolbar-guard && 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/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: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 && npm run test:firefox-bidi && npm run test:runtime-lifecycle && npm run test:provider-limits && npm run test:accessibility-tree-benchmark && npm run test:toolbar-guard && 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/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:provider-limits": "node test/provider-model-limits.mjs",
"test:markdown": "node --test test/markdown-render.mjs",
"test:accessibility-tree-benchmark": "node --test test/llm/lib/accessibility-tree-formats.test.mjs && node test/llm/accessibility-tree-benchmark.mjs --no-exact-tokenizer --check",
diff --git a/src/chrome/manifest.json b/src/chrome/manifest.json
index edd5a8970..e843f3865 100644
--- a/src/chrome/manifest.json
+++ b/src/chrome/manifest.json
@@ -45,6 +45,14 @@
"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/agent.js b/src/chrome/src/agent/agent.js
index 9feb48deb..fd89efadd 100644
--- a/src/chrome/src/agent/agent.js
+++ b/src/chrome/src/agent/agent.js
@@ -10851,11 +10851,12 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
let status;
try { status = await captchaAnswerDocumentStatus(tabId, record, {}, api); } catch { /* Expiry is still conclusive when inspection fails. */ }
if (status === 'root_changed') {
+ if (record.automatic) await this._refreshCaptchaGateDocument(tabId);
delete record.solution;
// Keep the paid history, but retire this document only once so later
// discovery cannot clear a gate belonging to the replacement document.
record.documentRetired = true;
- this._captchaGateStates.delete(tabId);
+ if (!record.automatic) this._captchaGateStates.delete(tabId);
return null;
}
const expired = record.solution !== undefined && Date.now() - record.createdAt > 180_000;
@@ -10885,7 +10886,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
delete record.solution;
const newlyRetired = record.documentRetired !== true;
record.documentRetired = true;
- return newlyRetired;
+ return newlyRetired && record.automatic !== true;
}
return false;
}
@@ -10910,7 +10911,9 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
: '\n[TRUSTED CAPTCHA GATE: A verification challenge is active, but no safely selectable automatic widget was detected. Inspect get_captcha_capabilities and use one native providerTasks solve only if its required parameters can be observed. Otherwise ask for manual completion. Do not dismiss, close, or resubmit the challenge.]';
onUpdate('warning', { message: 'Verification challenge requires manual completion.' });
} else if (captchaGateDecision?.status === 'cleared') {
- if (captchaGateDecision.clearedByNativeApplication === true) {
+ if (captchaGateDecision.clearedByNavigation === true) {
+ resultContent += '\n[TRUSTED CAPTCHA GATE: Browser navigation confirms the previous challenged page has been left. Read the current page and continue the task on a fresh model turn.]';
+ } else if (captchaGateDecision.clearedByNativeApplication === true) {
resultContent += '\n[TRUSTED CAPTCHA GATE: A fresh complete inspection confirms the applied native challenge is gone. Continue only on a fresh model turn.]';
} else if (captchaGateDecision.clearedByResponseToken === true) {
resultContent += '\n[TRUSTED CAPTCHA GATE: The gated widget now exposes a response token and no active challenge frame remains. The CAPTCHA gate is cleared. Choose any continuation or submit action only on a fresh model turn; the mutation preflight will re-arm the gate if the site rejects the token and shows the challenge again.]';
@@ -10963,6 +10966,9 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
}
_captchaGateBlockResult(tabId, toolName, toolArgs = {}) {
+ // Ending blocked/cancelled work is not a page mutation or a success claim.
+ // done_json is always a success claim, even if its payload says otherwise.
+ if (toolName === 'done' && ['failed', 'partial'].includes(normalizeDoneOutcome(toolArgs?.outcome))) return null;
const gate = this._captchaGateForTools(tabId, this._captchaGateStates.get(tabId));
const gatedCompletion = toolName === 'done' || toolName === 'done_json';
const abandonmentNavigation = Agent.NAV_TOOLS.has(toolName);
@@ -11036,11 +11042,15 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
_clearCaptchaGateAfterNavigation(tabId, toolName, beforeUrl, afterUrl, toolResult) {
if (!Agent.NAV_TOOLS.has(toolName)) return null;
+ return this._clearCaptchaGateAfterPageChange(tabId, beforeUrl, afterUrl, toolResult);
+ }
+
+ _clearCaptchaGateAfterPageChange(tabId, beforeUrl, afterUrl, toolResult, { documentReplaced = false } = {}) {
const beforeDocument = this._normalizeUrlPath(beforeUrl);
const afterDocument = this._normalizeUrlPath(afterUrl);
if (!beforeDocument || !afterDocument) return null;
const nativeAnswerRetired = this._retireNativeCaptchaAnswerIfPageChanged(tabId, afterUrl);
- if (beforeDocument === afterDocument && !nativeAnswerRetired) return null;
+ if (beforeDocument === afterDocument && !nativeAnswerRetired && !documentReplaced) return null;
const gate = this._captchaGateStates.get(tabId);
if (!gate) return null;
const clearedGate = {
@@ -11055,6 +11065,31 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
return clearedGate;
}
+ async _refreshCaptchaGateDocument(tabId, rootDocument = null) {
+ const gate = this._captchaGateStates.get(tabId);
+ const previousRoot = gate?.rootDocument;
+ if (!(previousRoot?.timeOrigin > 0)) return null;
+ try {
+ if (!rootDocument) {
+ const documents = await captureCaptchaDocuments(tabId, [{ frameId: 0 }], chrome);
+ const root = documents.find(document => document.frameId === 0);
+ if (root) rootDocument = { url: root.url, timeOrigin: root.timeOrigin };
+ }
+ const currentUrl = await this._currentUrl(tabId);
+ if (!(rootDocument?.timeOrigin > 0) || rootDocument.timeOrigin === previousRoot.timeOrigin
+ || this._normalizeUrl(rootDocument.url) !== this._normalizeUrl(currentUrl)
+ || this._captchaGateStates.get(tabId) !== gate) return null;
+ const record = this._nativeCaptchaSolutions?.get(tabId);
+ if (record?.documents?.some(document => document.frameId === 0
+ && document.timeOrigin === previousRoot.timeOrigin)) {
+ delete record.solution;
+ record.documentRetired = true;
+ }
+ return this._clearCaptchaGateAfterPageChange(tabId, gate.pageUrl || previousRoot.url,
+ currentUrl, null, { documentReplaced: true });
+ } catch { return null; } // An unreadable document must retain the paid lock.
+ }
+
_visibleChallengeDialogFromFrames(frameEntries, navigationFrames) {
const candidates = [];
const frameContexts = [];
@@ -11176,11 +11211,17 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
async _captchaMutationPreflight(tabId, toolName, toolArgs = {}, abortSignal = null) {
this._throwIfAborted(abortSignal);
+ if (toolName === 'done' && ['failed', 'partial'].includes(normalizeDoneOutcome(toolArgs?.outcome))) return null;
const gatedCompletion = toolName === 'done' || toolName === 'done_json';
const gatedAction = this._isBrowserMutationTool(toolName)
|| gatedCompletion
|| isNetworkMutation(toolName, toolArgs);
- if (!gatedAction || toolName === 'solve_captcha' || Agent.NAV_TOOLS.has(toolName)) return null;
+ if (toolName === 'solve_captcha') {
+ await this._refreshCaptchaGateDocument(tabId);
+ this._throwIfAborted(abortSignal);
+ return null;
+ }
+ if (!gatedAction || Agent.NAV_TOOLS.has(toolName)) return null;
const activeGate = this._captchaGateForTools(tabId, this._captchaGateStates.get(tabId));
if (
activeGate
@@ -11236,6 +11277,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
}
let activeGate = this._captchaGateForTools(tabId, this._captchaGateStates.get(tabId));
+ let navigationClearance = null;
const treeFilter = String(toolArgs?.filter || 'all').toLowerCase();
let observedChallengeFrameId = Number.isInteger(toolResult.captchaChallengeFrameId)
? toolResult.captchaChallengeFrameId
@@ -11297,6 +11339,45 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
failedDiagnostics = error?.captchaDiagnostics || null;
}
};
+ // A route change may be pushState/replaceState in the same document.
+ // Keep the failed solve until the root document is replaced or a complete
+ // inspection proves the original widget and challenge have disappeared.
+ const gatedPageUrl = activeGate?.pageUrl || String(activeGate?.key || '').split('\n')[0];
+ const pathChanged = this._normalizeUrlPath(pageUrl) !== this._normalizeUrlPath(gatedPageUrl);
+ if (activeGate && /^https?:\/\//i.test(gatedPageUrl)
+ && (pathChanged || activeGate.rootDocument?.timeOrigin > 0)) {
+ try {
+ const currentUrl = await this._currentUrl(tabId);
+ if (this._normalizeUrlPath(currentUrl) === this._normalizeUrlPath(pageUrl)) {
+ await inspectCaptchaFrames();
+ const previousRoot = activeGate.rootDocument;
+ const currentRoot = detection?.rootDocument;
+ const rootReplaced = previousRoot?.timeOrigin > 0 && currentRoot?.timeOrigin > 0
+ && previousRoot.timeOrigin !== currentRoot.timeOrigin
+ && this._normalizeUrl(currentRoot.url) === this._normalizeUrl(currentUrl);
+ const identity = activeGate.captchaCandidateIdentity;
+ // A sibling/relocated copy of the same widget is deliberately
+ // conservative here; only a new document can reset that solve lock.
+ const originalWidgetPresent = identity && (detection?.candidates || []).some(candidate =>
+ captchaTypesMatch(identity.type, candidate.type, identity.isEnterprise, candidate.isEnterprise)
+ && (!identity.websiteKey || candidate.websiteKey === identity.websiteKey));
+ let widgetGone = false;
+ if (pathChanged && !rootReplaced && !challenge && !detectionFailed && detection?.inspectionComplete
+ && !originalWidgetPresent) {
+ const inspection = await this._detectChallengeDialogBeforeMutation(tabId, { includeStatus: true });
+ widgetGone = inspection.inspectionComplete && !inspection.challenge;
+ }
+ if ((rootReplaced || widgetGone)
+ && this._normalizeUrl(await this._currentUrl(tabId)) === this._normalizeUrl(currentUrl)) {
+ navigationClearance = rootReplaced
+ ? await this._refreshCaptchaGateDocument(tabId, currentRoot)
+ : this._clearCaptchaGateAfterPageChange(tabId, gatedPageUrl, currentUrl, toolResult);
+ if (navigationClearance) toolResult.captchaGate = navigationClearance;
+ if (navigationClearance) activeGate = null;
+ }
+ }
+ } catch { /* Inconclusive document/widget inspection retains the solve lock. */ }
+ }
let languageNeutralFrameTrigger = false;
const hasDialogSurface = toolResult.pageGate?.surface === 'dialog'
|| /^\s*(?:dialog|alertdialog)(?=\s|$)/im.test(toolResult.pageContent);
@@ -11513,7 +11594,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
toolResult.captchaGate = guardedState.publicGate;
return { gate: guardedState.publicGate, loopCheck };
}
- return { gate: null, loopCheck };
+ return { gate: navigationClearance, loopCheck };
}
const key = captchaChallengeKey(pageUrl, challenge.normalizedLabel);
@@ -11607,6 +11688,8 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
: null;
this._captchaGateStates.set(tabId, {
key,
+ pageUrl,
+ ...(detection?.rootDocument ? { rootDocument: detection.rootDocument } : {}),
status: publicGate.status,
publicGate,
...(captchaCandidateIdentity ? { captchaCandidateIdentity } : {}),
@@ -16641,13 +16724,13 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
&& nativeAnswer.dispatchedTimeOrigins instanceof Set
? { pageUrl: nativeAnswer.pageUrl, createdAt: nativeAnswer.createdAt,
applied: nativeAnswer.applied === true, applicationSucceeded: nativeAnswer.applicationSucceeded === true,
- documentRetired: nativeAnswer.documentRetired === true,
+ documentRetired: nativeAnswer.documentRetired === true, automatic: nativeAnswer.automatic === true,
documents: nativeAnswer.documents,
dispatchedTimeOrigins: [...nativeAnswer.dispatchedTimeOrigins] }
: null;
const savedNativeAnswer = nativeAnswer?.solution !== undefined && nativeAnswer.applied === false
&& Date.now() - nativeAnswer.createdAt <= 180_000
- ? { pageUrl: nativeAnswer.pageUrl, createdAt: nativeAnswer.createdAt, applied: false,
+ ? { pageUrl: nativeAnswer.pageUrl, createdAt: nativeAnswer.createdAt, applied: false, automatic: nativeAnswer.automatic === true,
documents: nativeAnswer.documents, solution: nativeAnswer.solution,
provider: nativeAnswer.provider, method: nativeAnswer.method,
family: nativeAnswer.family, taskId: nativeAnswer.taskId,
@@ -35907,8 +35990,9 @@ If the user has already named or confirmed this exact recipient, do NOT ask agai
// A new root may expose a new CAPTCHA. A reloaded child frame in
// the same root has already used this document's paid dispatch.
if (documentStatus === 'root_changed') {
+ if (record.automatic) await this._refreshCaptchaGateDocument(tabId);
record.documentRetired = true;
- this._captchaGateStates.delete(tabId);
+ if (!record.automatic) this._captchaGateStates.delete(tabId);
}
return false;
}
@@ -35959,6 +36043,8 @@ If the user has already named or confirmed this exact recipient, do NOT ask agai
websiteURL = tab?.url || '';
} catch {}
+ const pageUrl = websiteURL;
+
if (args?.providerTasks) {
if (args.inject !== false) return noDispatchFailure('Native CAPTCHA methods require inject: false. Apply the returned structured answer with apply_captcha_solution after inspecting the page.');
const prepared = prepareNativeCaptchaTasks(providers, args.providerTasks);
@@ -36030,8 +36116,8 @@ If the user has already named or confirmed this exact recipient, do NOT ask agai
// the model gets the remedy, not just the rejection.
let detectionNote = null;
let detected = null;
+ let detection = null;
if (type !== 'image_to_text') {
- let detection = null;
try {
detection = await detectCaptcha(tabId, {
type,
@@ -36188,8 +36274,75 @@ If the user has already named or confirmed this exact recipient, do NOT ask agai
);
}
+ let automaticAnswer = null;
+ if (type !== 'image_to_text') {
+ await this._refreshCaptchaGateDocument(tabId, detection?.rootDocument);
+ // The model can solve directly from a screenshot before any tree
+ // read arms a gate. Reserve and persist that paid attempt here,
+ // after argument validation but before contacting any provider.
+ const previousGate = this._captchaGateStates.get(tabId);
+ if (previousGate?.publicGate?.solveAttempted || previousGate?.publicGate?.solveFailed) {
+ return noDispatchFailure('An automatic CAPTCHA solve was already dispatched for this challenge. Verify the page or ask for manual completion; do not spend again.');
+ }
+ const previousAnswer = this._nativeCaptchaSolutions?.get(tabId);
+ const currentRoot = detection?.rootDocument;
+ if (currentRoot && previousAnswer?.dispatchedTimeOrigins?.has(currentRoot.timeOrigin)) {
+ return noDispatchFailure('A CAPTCHA solve was already dispatched for this page document. Use its result or ask for manual completion; do not spend again.');
+ }
+ if (!wantInject) {
+ const frames = await chrome.webNavigation.getAllFrames({ tabId });
+ const documents = await captureCaptchaDocuments(tabId, frames, chrome);
+ const root = documents.find(document => document.frameId === 0 && document.url === pageUrl);
+ if (!root) return noDispatchFailure('Could not bind this page document before the token-only CAPTCHA request.');
+ const dispatchedTimeOrigins = new Set(previousAnswer?.dispatchedTimeOrigins || []);
+ if (dispatchedTimeOrigins.has(root.timeOrigin)) return noDispatchFailure('A CAPTCHA solve was already dispatched for this page document. Do not spend again.');
+ dispatchedTimeOrigins.add(root.timeOrigin);
+ automaticAnswer = { pageUrl, createdAt: Date.now(), applied: false, automatic: true,
+ documents, dispatchedTimeOrigins };
+ this._nativeCaptchaSolutions ||= new Map();
+ this._nativeCaptchaSolutions.set(tabId, automaticAnswer);
+ }
+ const identity = captchaGateCandidateIdentity(detected);
+ const answerRoot = automaticAnswer?.documents.find(document => document.frameId === 0);
+ const rootDocument = answerRoot ? { url: answerRoot.url, timeOrigin: answerRoot.timeOrigin } : currentRoot;
+ const publicGate = { ...previousGate?.publicGate, status: 'manual_required',
+ solveAttempted: true, selectedType: type,
+ ...(identity ? { candidateNotCorrelated: false } : {}) };
+ this._captchaGateStates.set(tabId, {
+ ...previousGate,
+ key: previousGate?.key || captchaChallengeKey(pageUrl, 'automatic captcha solve'),
+ pageUrl,
+ ...(rootDocument ? { rootDocument } : {}),
+ ...(identity ? { captchaCandidateIdentity: identity } : {}),
+ status: publicGate.status,
+ publicGate,
+ });
+ // A worker interruption must retain a manual gate, even if the
+ // provider accepted the request before its result was recorded.
+ const saved = await this._persistNow(tabId);
+ if (!saved?.ok) {
+ if (previousGate) this._captchaGateStates.set(tabId, previousGate);
+ else this._captchaGateStates.delete(tabId);
+ if (automaticAnswer) {
+ if (previousAnswer) this._nativeCaptchaSolutions.set(tabId, previousAnswer);
+ else this._nativeCaptchaSolutions.delete(tabId);
+ }
+ return noDispatchFailure('Could not save the CAPTCHA dispatch lock. No provider was contacted; retry after session storage is available.');
+ }
+ }
+
dispatched = true;
const result = await solveCaptchaWithProviders(providers, params);
+ if (automaticAnswer) {
+ automaticAnswer.solution = { ...result.solution, token: result.token };
+ automaticAnswer.provider = result.provider;
+ automaticAnswer.method = 'automatic';
+ automaticAnswer.family = type;
+ automaticAnswer.taskId = result.taskId;
+ automaticAnswer.createdAt = Date.now();
+ this._captchaSolveGateAfterTool(tabId, 'solve_captcha', { success: true, applicationRequired: true });
+ await this._persistNow(tabId);
+ }
if (wantInject && result.provider === 'nonecap' && result.solution?.userAgent
&& result.solution.userAgent !== params.userAgent) {
return { success: false, dispatched: true, manualCompletionRequired: true,
@@ -36207,6 +36360,7 @@ If the user has already named or confirmed this exact recipient, do NOT ask agai
fieldName: result.fieldName,
alsoSet: result.alsoSet,
token: result.token,
+ respKey: result.solution?.respKey,
callbackHint: detected.callbackName || null,
target: detected ? {
frameId: detected.frameId,
@@ -36233,7 +36387,6 @@ If the user has already named or confirmed this exact recipient, do NOT ask agai
type,
taskId: result.taskId,
provider: result.provider,
- token: result.token,
...(result.solution?.respKey ? { respKey: result.solution.respKey } : {}),
...(result.solution?.userAgent ? { solverUserAgent: result.solution.userAgent } : {}),
tokenPreview: result.token ? `${String(result.token).slice(0, 24)}…(${String(result.token).length} chars)` : null,
@@ -36243,14 +36396,19 @@ If the user has already named or confirmed this exact recipient, do NOT ask agai
selectionReason: detected?.selectionReason || null,
detectedType: detected?.type || null,
injected: injection?.success === true,
+ ...(automaticAnswer ? { applicationRequired: true } : {}),
injection,
- note: !wantInject
- ? 'Token returned without injection. Apply this token to the intended response field; do not request another paid solve for the same challenge.'
+ note: automaticAnswer
+ ? 'Token returned without injection. Inspect the page and call apply_captcha_solution with observed frame/field or callback bindings and path: token. The paid answer is saved; do not request another solve.'
+ : !wantInject ? 'Recognition answer returned without page injection.'
: injection?.success
? (injection.calledCallback
? 'Token was inserted into the selected frame and its callback was invoked. Wait for the page to react, then verify whether the challenge cleared.'
: 'Token was inserted into the selected frame, but no unique callback was invoked. Verify page progress before submitting or taking another action; do not request another paid solve.')
: 'The CAPTCHA solver returned a token, but targeted injection failed. The challenge is not confirmed cleared; do not request another paid solve for the same token.',
+ // Keep injection diagnostics ahead of long tokens in trace exports.
+ token: result.token,
+ ...(automaticAnswer ? { solution: automaticAnswer.solution } : {}),
};
} catch (e) {
const error = `solve_captcha failed: ${e.message}`;
diff --git a/src/chrome/src/agent/captcha-frame-runtime.js b/src/chrome/src/agent/captcha-frame-runtime.js
index 22389a3e5..a92f7d8ed 100644
--- a/src/chrome/src/agent/captcha-frame-runtime.js
+++ b/src/chrome/src/agent/captcha-frame-runtime.js
@@ -1090,6 +1090,7 @@ export function detectCaptchaCandidatesInPage(scope = null, matcherOptions = nul
frameContext: {
frameUrl,
frameName,
+ documentTimeOrigin,
childFrames,
},
};
@@ -1309,11 +1310,6 @@ export function injectCaptchaTokenInPage(payload, scope = null) {
}
return element;
};
- for (const field of injectableFields) {
- setOn(field.name, field.element);
- }
- const fieldsTouched = injectableFields.length;
-
const pageWindow = frameWindow.wrappedJSObject || frameWindow;
const callbacks = [];
const addCallback = (fn, source) => {
@@ -1329,8 +1325,20 @@ export function injectCaptchaTokenInPage(payload, scope = null) {
return null;
}
};
+ // The bridge remembers closure callbacks supplied to render(), including
+ // widget-bound execute({async:true}) continuations. Query before dispatching
+ // field events, which may remove or replace the selected widget.
+ let callbackBridgeAvailable = false;
+ try {
+ const bridge = pageWindow.__webbrainCaptchaCallbacks;
+ callbackBridgeAvailable = typeof bridge?.callbacks === 'function';
+ const registered = bridge?.callbacks(
+ target.type, target.websiteKey, fieldName, target.responseFieldId, target.responseFieldIndex,
+ );
+ for (const entry of registered || []) addCallback(entry.fn, entry.source);
+ } catch (_) { /* Older tabs still use observed names and vendor discovery. */ }
const callbackHint = payload?.callbackHint || null;
- if (callbackHint) {
+ if (!callbacks.length && callbackHint) {
addCallback(resolveNamedCallback(callbackHint), `data-callback:${callbackHint}`);
}
if (!callbacks.length) {
@@ -1381,12 +1389,17 @@ export function injectCaptchaTokenInPage(payload, scope = null) {
};
if (!callbacks.length) collectGoogleCallbacks();
+ for (const field of injectableFields) {
+ setOn(field.name, field.element);
+ }
+ const fieldsTouched = injectableFields.length;
+
let calledCallback = false;
let callbackSource = null;
let callbackError = null;
if (callbacks.length === 1) {
try {
- callbacks[0].fn.call(pageWindow, token);
+ callbacks[0].fn.call(pageWindow, token, payload?.respKey);
calledCallback = true;
callbackSource = callbacks[0].source;
} catch (error) {
@@ -1413,6 +1426,7 @@ export function injectCaptchaTokenInPage(payload, scope = null) {
callbackSource,
callbackAmbiguous: callbacks.length > 1,
callbackCandidates: callbacks.length,
+ callbackBridgeAvailable,
callbackError,
siteKeyMatched,
challengeMarkerMatched,
diff --git a/src/chrome/src/agent/captcha-hcaptcha-providers.js b/src/chrome/src/agent/captcha-hcaptcha-providers.js
index 9fed02aee..a8cc479c9 100644
--- a/src/chrome/src/agent/captcha-hcaptcha-providers.js
+++ b/src/chrome/src/agent/captcha-hcaptcha-providers.js
@@ -15,11 +15,21 @@ async function request(id, apiKey, path, { body, timeoutMs = 30_000, allowPendin
});
const result = await response.json().catch(() => null);
if (!result || typeof result !== 'object' || Array.isArray(result)) throw new Error(`${NAMES[id]}: invalid response.`);
- // NopeCHA v1 reports an unfinished job as HTTP 409 / code 14. Only polls
- // may treat this as pending; a rejected creation must never be re-submitted.
- if (allowPending && id === 'nopecha' && response.status === 409 && result.code === 14) return null;
+ // v1 uses code:14 / HTTP 409; older responses use error:14 with HTTP 200.
+ // Accept numeric strings and nested error codes as well, but only while
+ // polling an existing job. Auth, quota, rate-limit and server errors are
+ // terminal even if their body happens to contain a pending code.
+ const code = result.code ?? result.error?.code ?? result.error;
+ const incomplete = code === 14 || code === '14';
+ if (allowPending && !body && id === 'nopecha' && incomplete
+ && (response.ok || response.status === 409)) return null;
if (!response.ok || result.error || result.code) {
- throw new Error(`${NAMES[id]}: ${result.error?.message || result.message || result.error?.code || `HTTP ${response.status}`}`);
+ const message = String(result.error?.message || result.message || result.error?.code || 'Request failed')
+ .split(apiKey).join('[redacted]');
+ const numericCode = typeof code === 'number' || (typeof code === 'string' && /^\d+$/.test(code))
+ ? `; code ${code}` : '';
+ // Keep phase/status in traces without including keys, task IDs or payloads.
+ throw new Error(`${NAMES[id]}: ${message} (${body ? 'POST' : 'GET'} ${path.split('?')[0]}; HTTP ${response.status}${numericCode})`);
}
return result;
}
diff --git a/src/chrome/src/agent/captcha-json-api.js b/src/chrome/src/agent/captcha-json-api.js
index abb7a8b5e..d5dca35ca 100644
--- a/src/chrome/src/agent/captcha-json-api.js
+++ b/src/chrome/src/agent/captcha-json-api.js
@@ -19,7 +19,7 @@ export async function getJsonCaptchaBalance(apiBase, name, apiKey) {
return { balance: Number(result.balance) };
}
-export async function solveJsonCaptcha(apiBase, name, apiKey, task) {
+export async function solveJsonCaptcha(apiBase, name, apiKey, task, { pendingStatuses = ['processing'] } = {}) {
if (!apiKey) throw new Error(`No ${name} API key configured.`);
const created = await postJson(apiBase, name, 'createTask', { clientKey: apiKey, task });
if (created.status === 'ready') return { taskId: created.taskId, solution: created.solution ?? {} };
@@ -31,7 +31,7 @@ export async function solveJsonCaptcha(apiBase, name, apiKey, task) {
if (remaining <= 0) break;
const result = await postJson(apiBase, name, 'getTaskResult', { clientKey: apiKey, taskId: created.taskId }, Math.min(30_000, remaining));
if (result.status === 'ready') return { taskId: created.taskId, solution: result.solution ?? {} };
- if (result.status !== 'processing') throw new Error(`${name} getTaskResult: unexpected status`);
+ if (!pendingStatuses.includes(result.status)) throw new Error(`${name} getTaskResult: unexpected status`);
}
throw new Error(`${name}: timed out waiting for solution.`);
}
diff --git a/src/chrome/src/agent/captcha-native-providers.js b/src/chrome/src/agent/captcha-native-providers.js
index 027238db4..fa62645b4 100644
--- a/src/chrome/src/agent/captcha-native-providers.js
+++ b/src/chrome/src/agent/captcha-native-providers.js
@@ -517,7 +517,8 @@ export async function solveNativeCaptchaTasks(prepared) {
for (const { provider, contract, task, family } of prepared) {
try {
const result = JSON_BASES[provider.id]
- ? await solveJsonCaptcha(JSON_BASES[provider.id], provider.id, provider.apiKey, task)
+ ? await solveJsonCaptcha(JSON_BASES[provider.id], provider.id, provider.apiKey, task,
+ provider.id === 'capsolver' ? { pendingStatuses: ['idle', 'processing'] } : {})
: provider.id === 'nopecha' ? await solveNopechaTask(provider.apiKey, contract.path, task)
: provider.id === 'nonecap' ? await solveNonecapTask(provider.apiKey, task)
: await solveForm(provider.apiKey, contract, task);
diff --git a/src/chrome/src/agent/captcha-solver.js b/src/chrome/src/agent/captcha-solver.js
index cdd6f2293..0cf33a1c1 100644
--- a/src/chrome/src/agent/captcha-solver.js
+++ b/src/chrome/src/agent/captcha-solver.js
@@ -285,7 +285,7 @@ export async function detectCaptcha(tabId, constraints = {}) {
}),
frameTreePromise,
]);
- const navigationFrames = frameTreeAttempt.status === 'fulfilled'
+ const navigationFrames = frameTreeAttempt.status === 'fulfilled' && Array.isArray(frameTreeAttempt.value)
? frameTreeAttempt.value
: [];
if (scriptAttempt.status === 'rejected') {
@@ -321,8 +321,14 @@ export async function detectCaptcha(tabId, constraints = {}) {
}
}
const visibleCandidates = applyCaptchaFrameVisibility(candidates, frameContexts, navigationFrames);
+ const root = frameContexts.find(frame => frame.frameId === 0);
return {
...selectCaptchaCandidate(visibleCandidates, constraints),
+ rootDocument: root && Number.isFinite(root.documentTimeOrigin) && root.documentTimeOrigin > 0
+ ? { url: root.frameUrl, timeOrigin: root.documentTimeOrigin } : null,
+ inspectionComplete: frameTreeAttempt.status === 'fulfilled' && !!root
+ && navigationFrames.some(frame => frame.frameId === 0)
+ && navigationFrames.every(frame => frameContexts.some(context => context.frameId === frame.frameId)),
diagnostics: buildCaptchaDiagnostics({
candidates: visibleCandidates,
frameContexts,
@@ -348,6 +354,7 @@ export async function injectToken(tabId, {
fieldName,
alsoSet,
token,
+ respKey,
callbackHint,
target = null,
}) {
@@ -364,6 +371,7 @@ export async function injectToken(tabId, {
fieldName,
alsoSet,
token,
+ respKey,
callbackHint,
target: target || {},
};
diff --git a/src/chrome/src/agent/tools.js b/src/chrome/src/agent/tools.js
index ce4e38913..38963ce28 100644
--- a/src/chrome/src/agent/tools.js
+++ b/src/chrome/src/agent/tools.js
@@ -1243,7 +1243,7 @@ export const AGENT_TOOLS = [
"type": "function",
"function": {
"name": "apply_captcha_solution",
- "description": "Apply the stored answer from the one native CAPTCHA solve to its original page. Bind solution paths to observed response fields, host-only cookies, image/grid clicks, or an observed named CAPTCHA callback. The frame host's Type, Click, or JavaScript permission is required for the corresponding binding. Never invent selectors/callbacks or execute returned scripts. Requires exact observed frameId and frameUrl; cookie bindings require frame 0. Match any required proxy/User-Agent first. Then verify fresh page state. This never requests a paid solve.",
+ "description": "Apply the stored answer from a native or token-only CAPTCHA solve to its original page. Bind solution paths to observed response fields, host-only cookies, image/grid clicks, or an observed named CAPTCHA callback. The frame host's Type, Click, or JavaScript permission is required for the corresponding binding. Never invent selectors/callbacks or execute returned scripts. Requires exact observed frameId and frameUrl; cookie bindings require frame 0. Match any required proxy/User-Agent first. Then verify fresh page state. This never requests a paid solve.",
"parameters": {
"type": "object",
"properties": {
@@ -1374,7 +1374,7 @@ export const AGENT_TOOLS = [
},
rqdata: { type: 'string', description: 'hCaptcha only — optional; preserve the exact rqdata when the widget exposes it. Never invent it.' },
imageBase64: { type: 'string', description: 'image_to_text only — base64-encoded image bytes (no data: prefix).' },
- inject: { type: 'boolean', description: 'After solving, inject the token into the detected frame\'s response field (textarea[name=g-recaptcha-response] etc.) and fire the widget\'s callback. Default true and requires a detected frame target. If the widget cannot be detected but type/websiteKey are known, set false to get only the token without page injection.' },
+ inject: { type: 'boolean', description: 'After solving, inject the token into the detected frame\'s response field (textarea[name=g-recaptcha-response] etc.) and fire the widget\'s callback. Default true and requires a detected frame target. If the widget cannot be detected but type/websiteKey are known, set false to save a token-only answer. Apply it using apply_captcha_solution with observed frame and field/callback bindings and path: token; get_captcha_capabilities can retrieve the saved answer without another solve.' },
},
required: [],
},
diff --git a/src/chrome/src/content/captcha-callback-bridge.js b/src/chrome/src/content/captcha-callback-bridge.js
new file mode 100644
index 000000000..60ae3088d
--- /dev/null
+++ b/src/chrome/src/content/captcha-callback-bridge.js
@@ -0,0 +1,179 @@
+// Runs in MAIN at document_start: render callbacks are often closures, with
+// no data-callback attribute or global name to discover after a paid solve.
+// This bridge only remembers page registrations. It never buys a solve or
+// treats a callback invocation as proof that the site accepted an answer.
+(() => {
+ const bridgeName = '__webbrainCaptchaCallbacks';
+ if (window[bridgeName]) return;
+ const registrations = new Set();
+ const watched = new WeakMap();
+ const apis = new WeakMap();
+ const resolveCallback = value => typeof value === 'function' ? value
+ : typeof value === 'string' ? value.split('.').reduce((object, key) => object?.[key], window) : null;
+ const containerElement = value => typeof value === 'string'
+ ? document.getElementById(value) || (() => { try { return document.querySelector(value); } catch { return null; } })()
+ : value;
+ const live = record => record.container?.isConnected === true
+ && record.records.get(record.id) === record;
+
+ // Preserve native calls, receivers and return values. Setters also catch SDKs
+ // which first publish a ready() stub and install render() later in the load.
+ function watch(object, key, transform) {
+ if (!object || !['object', 'function'].includes(typeof object)) return;
+ let keys = watched.get(object);
+ if (!keys) watched.set(object, keys = new Set());
+ if (keys.has(key)) return;
+ const descriptor = Object.getOwnPropertyDescriptor(object, key);
+ if (descriptor && (!descriptor.configurable || descriptor.get || descriptor.set || descriptor.writable === false)) return;
+ keys.add(key);
+ const prepare = next => { try { return transform(next); } catch { return next; } };
+ let value = prepare(descriptor?.value);
+ Object.defineProperty(object, key, {
+ configurable: true, enumerable: descriptor?.enumerable ?? true,
+ get: () => value,
+ set: next => { value = prepare(next); },
+ });
+ }
+
+ function instrument(api, family) {
+ if (!api || !['object', 'function'].includes(typeof api)) return api;
+ if (apis.has(api)) {
+ // hCaptcha can publish the same API as grecaptcha for compatibility.
+ if (family === 'hcaptcha') apis.get(api).family = family;
+ return api;
+ }
+ const records = new Map();
+ const state = { records, family };
+ apis.set(api, state);
+ const find = id => id == null ? records.values().next().value
+ : records.get(String(id)) || [...records.values()].find(record => record.container === containerElement(id));
+ const clear = record => {
+ if (!record) return;
+ record.token = null;
+ record.tokenAt = 0;
+ record.respKey = null;
+ record.delivered = false;
+ record.generation += 1;
+ record.pending.clear();
+ };
+ const wrap = (key, factory) => watch(api, key, original =>
+ typeof original === 'function' ? factory(original) : original);
+
+ wrap('render', original => function (container, params, ...rest) {
+ const element = containerElement(container);
+ // Capture before render: SDKs are allowed to mutate the options object.
+ const callback = params?.callback ?? element?.getAttribute?.('data-callback');
+ const sitekey = String(params?.sitekey || element?.getAttribute?.('data-sitekey') || '');
+ let record;
+ const options = params && typeof params === 'object' ? { ...params } : params;
+ for (const event of ['expired-callback', 'chalexpired-callback', 'error-callback']) {
+ if (!options || !options[event]) continue;
+ const handler = options[event];
+ options[event] = function (...args) {
+ clear(record);
+ const fn = resolveCallback(handler);
+ if (typeof fn === 'function') return Reflect.apply(fn, this, args);
+ };
+ }
+ const args = [...arguments];
+ if (args.length > 1) args[1] = options;
+ const id = Reflect.apply(original, this, args);
+ if (id == null || !element || !sitekey) return id;
+ for (const previous of registrations) if (previous.container === element || (previous.records === records && previous.id === String(id))) {
+ registrations.delete(previous);
+ previous.records.delete(previous.id);
+ }
+ record = { family: state.family, records, id: String(id), container: element, sitekey, callback,
+ generation: 0, delivered: false, token: null, respKey: null, pending: new Set() };
+ records.set(record.id, record);
+ registrations.add(record);
+ // Bound memory to widgets still owned by the document.
+ for (const old of registrations) if (!live(old)) {
+ registrations.delete(old);
+ old.records.delete(old.id);
+ }
+ return id;
+ });
+ for (const method of ['reset', 'remove']) wrap(method, original => function (id, ...rest) {
+ const record = find(id);
+ const result = Reflect.apply(original, this, arguments);
+ clear(record);
+ if (method === 'remove' && record) {
+ registrations.delete(record);
+ records.delete(record.id);
+ }
+ return result;
+ });
+ wrap('getResponse', original => function (id, ...rest) {
+ const record = find(id);
+ if (record && live(record) && record.token && Date.now() - record.tokenAt <= 180_000) return record.token;
+ return Reflect.apply(original, this, arguments);
+ });
+ {
+ wrap('getRespKey', original => function (id, ...rest) {
+ const record = find(id);
+ if (record && live(record) && record.token && record.respKey && Date.now() - record.tokenAt <= 180_000) return record.respKey;
+ return Reflect.apply(original, this, arguments);
+ });
+ wrap('execute', original => function (id, options, ...rest) {
+ const record = find(id);
+ const result = Reflect.apply(original, this, arguments);
+ if (state.family !== 'hcaptcha' || !record || options?.async !== true || typeof result?.then !== 'function') return result;
+ // Invisible integrations may await execute() instead of registering a
+ // callback. Resolve that original page continuation with the same answer.
+ return new Promise((resolve, reject) => {
+ const pending = { resolve, generation: record.generation };
+ record.pending.add(pending);
+ Promise.resolve(result).then(resolve, reject).finally(() => record.pending.delete(pending));
+ });
+ });
+ }
+ return api;
+ }
+
+ Object.defineProperty(window, bridgeName, { configurable: true, value: {
+ callbacks(type, sitekey, fieldName, fieldId, fieldIndex) {
+ const family = String(type).startsWith('recaptcha') ? 'recaptcha' : type;
+ const fields = [...document.querySelectorAll(`textarea[name="${fieldName}"], input[name="${fieldName}"]`)];
+ const field = fieldId ? fields.find(element => element.id === fieldId)
+ : Number.isInteger(fieldIndex) ? fields[fieldIndex] : fields.length === 1 ? fields[0] : null;
+ return [...registrations].filter(record => {
+ if (!live(record) || record.family !== family || record.sitekey !== sitekey) return false;
+ if (typeof resolveCallback(record.callback) !== 'function' && !record.pending.size) return false;
+ // Site keys are shared across widgets. Never use one alone when the
+ // solver selected a particular response field.
+ if (field && !record.container.contains(field)) return false;
+ if ((fieldId || Number.isInteger(fieldIndex)) && !field) return false;
+ return true;
+ }).map(record => {
+ const generation = record.generation;
+ return {
+ source: `${record.family}.render`,
+ fn: (token, respKey) => {
+ if (!live(record) || record.generation !== generation || record.delivered) {
+ throw new Error('The registered CAPTCHA widget changed or its callback was already delivered.');
+ }
+ const callback = resolveCallback(record.callback);
+ const pending = [...record.pending].filter(item => item.generation === generation);
+ if (typeof callback !== 'function' && !pending.length) {
+ throw new Error('The registered CAPTCHA widget has no completion callback or pending execute promise.');
+ }
+ record.delivered = true;
+ record.token = token;
+ record.tokenAt = Date.now();
+ record.respKey = respKey || null;
+ for (const item of pending) { item.resolve({ response: token, key: respKey || '' }); record.pending.delete(item); }
+ if (typeof callback === 'function') Reflect.apply(callback, window, [token]);
+ },
+ };
+ });
+ },
+ } });
+ try { watch(window, 'hcaptcha', api => instrument(api, 'hcaptcha')); } catch {}
+ try { watch(window, 'turnstile', api => instrument(api, 'turnstile')); } catch {}
+ try { watch(window, 'grecaptcha', api => {
+ instrument(api, 'recaptcha');
+ watch(api, 'enterprise', enterprise => instrument(enterprise, 'recaptcha'));
+ return api;
+ }); } catch {}
+})();
diff --git a/src/firefox/manifest.json b/src/firefox/manifest.json
index 2b43546d3..6607c9b94 100644
--- a/src/firefox/manifest.json
+++ b/src/firefox/manifest.json
@@ -35,6 +35,14 @@
}
},
"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/agent.js b/src/firefox/src/agent/agent.js
index 53223990f..1abb2ac97 100644
--- a/src/firefox/src/agent/agent.js
+++ b/src/firefox/src/agent/agent.js
@@ -6052,13 +6052,13 @@ export class Agent extends LoopDetector {
&& nativeAnswer.dispatchedTimeOrigins instanceof Set
? { pageUrl: nativeAnswer.pageUrl, createdAt: nativeAnswer.createdAt,
applied: nativeAnswer.applied === true, applicationSucceeded: nativeAnswer.applicationSucceeded === true,
- documentRetired: nativeAnswer.documentRetired === true,
+ documentRetired: nativeAnswer.documentRetired === true, automatic: nativeAnswer.automatic === true,
documents: nativeAnswer.documents,
dispatchedTimeOrigins: [...nativeAnswer.dispatchedTimeOrigins] }
: null;
const savedNativeAnswer = nativeAnswer?.solution !== undefined && nativeAnswer.applied === false
&& Date.now() - nativeAnswer.createdAt <= 180_000
- ? { pageUrl: nativeAnswer.pageUrl, createdAt: nativeAnswer.createdAt, applied: false,
+ ? { pageUrl: nativeAnswer.pageUrl, createdAt: nativeAnswer.createdAt, applied: false, automatic: nativeAnswer.automatic === true,
documents: nativeAnswer.documents, solution: nativeAnswer.solution,
provider: nativeAnswer.provider, method: nativeAnswer.method,
family: nativeAnswer.family, taskId: nativeAnswer.taskId,
@@ -9525,11 +9525,12 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
let status;
try { status = await captchaAnswerDocumentStatus(tabId, record, {}, api); } catch { /* Expiry is still conclusive when inspection fails. */ }
if (status === 'root_changed') {
+ if (record.automatic) await this._refreshCaptchaGateDocument(tabId);
delete record.solution;
// Keep the paid history, but retire this document only once so later
// discovery cannot clear a gate belonging to the replacement document.
record.documentRetired = true;
- this._captchaGateStates.delete(tabId);
+ if (!record.automatic) this._captchaGateStates.delete(tabId);
return null;
}
const expired = record.solution !== undefined && Date.now() - record.createdAt > 180_000;
@@ -9559,7 +9560,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
delete record.solution;
const newlyRetired = record.documentRetired !== true;
record.documentRetired = true;
- return newlyRetired;
+ return newlyRetired && record.automatic !== true;
}
return false;
}
@@ -9584,7 +9585,9 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
: '\n[TRUSTED CAPTCHA GATE: A verification challenge is active, but no safely selectable automatic widget was detected. Inspect get_captcha_capabilities and use one native providerTasks solve only if its required parameters can be observed. Otherwise ask for manual completion. Do not dismiss, close, or resubmit the challenge.]';
onUpdate('warning', { message: 'Verification challenge requires manual completion.' });
} else if (captchaGateDecision?.status === 'cleared') {
- if (captchaGateDecision.clearedByNativeApplication === true) {
+ if (captchaGateDecision.clearedByNavigation === true) {
+ resultContent += '\n[TRUSTED CAPTCHA GATE: Browser navigation confirms the previous challenged page has been left. Read the current page and continue the task on a fresh model turn.]';
+ } else if (captchaGateDecision.clearedByNativeApplication === true) {
resultContent += '\n[TRUSTED CAPTCHA GATE: A fresh complete inspection confirms the applied native challenge is gone. Continue only on a fresh model turn.]';
} else if (captchaGateDecision.clearedByResponseToken === true) {
resultContent += '\n[TRUSTED CAPTCHA GATE: The gated widget now exposes a response token and no active challenge frame remains. The CAPTCHA gate is cleared. Choose any continuation or submit action only on a fresh model turn; the mutation preflight will re-arm the gate if the site rejects the token and shows the challenge again.]';
@@ -9637,6 +9640,9 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
}
_captchaGateBlockResult(tabId, toolName, toolArgs = {}) {
+ // Ending blocked/cancelled work is not a page mutation or a success claim.
+ // done_json is always a success claim, even if its payload says otherwise.
+ if (toolName === 'done' && ['failed', 'partial'].includes(normalizeDoneOutcome(toolArgs?.outcome))) return null;
const gate = this._captchaGateForTools(tabId, this._captchaGateStates.get(tabId));
const gatedCompletion = toolName === 'done' || toolName === 'done_json';
const abandonmentNavigation = Agent.NAV_TOOLS.has(toolName);
@@ -9710,11 +9716,15 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
_clearCaptchaGateAfterNavigation(tabId, toolName, beforeUrl, afterUrl, toolResult) {
if (!Agent.NAV_TOOLS.has(toolName)) return null;
+ return this._clearCaptchaGateAfterPageChange(tabId, beforeUrl, afterUrl, toolResult);
+ }
+
+ _clearCaptchaGateAfterPageChange(tabId, beforeUrl, afterUrl, toolResult, { documentReplaced = false } = {}) {
const beforeDocument = this._normalizeUrlPath(beforeUrl);
const afterDocument = this._normalizeUrlPath(afterUrl);
if (!beforeDocument || !afterDocument) return null;
const nativeAnswerRetired = this._retireNativeCaptchaAnswerIfPageChanged(tabId, afterUrl);
- if (beforeDocument === afterDocument && !nativeAnswerRetired) return null;
+ if (beforeDocument === afterDocument && !nativeAnswerRetired && !documentReplaced) return null;
const gate = this._captchaGateStates.get(tabId);
if (!gate) return null;
const clearedGate = {
@@ -9729,6 +9739,31 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
return clearedGate;
}
+ async _refreshCaptchaGateDocument(tabId, rootDocument = null) {
+ const gate = this._captchaGateStates.get(tabId);
+ const previousRoot = gate?.rootDocument;
+ if (!(previousRoot?.timeOrigin > 0)) return null;
+ try {
+ if (!rootDocument) {
+ const documents = await captureCaptchaDocuments(tabId, [{ frameId: 0 }], browser);
+ const root = documents.find(document => document.frameId === 0);
+ if (root) rootDocument = { url: root.url, timeOrigin: root.timeOrigin };
+ }
+ const currentUrl = await this._currentUrl(tabId);
+ if (!(rootDocument?.timeOrigin > 0) || rootDocument.timeOrigin === previousRoot.timeOrigin
+ || this._normalizeUrl(rootDocument.url) !== this._normalizeUrl(currentUrl)
+ || this._captchaGateStates.get(tabId) !== gate) return null;
+ const record = this._nativeCaptchaSolutions?.get(tabId);
+ if (record?.documents?.some(document => document.frameId === 0
+ && document.timeOrigin === previousRoot.timeOrigin)) {
+ delete record.solution;
+ record.documentRetired = true;
+ }
+ return this._clearCaptchaGateAfterPageChange(tabId, gate.pageUrl || previousRoot.url,
+ currentUrl, null, { documentReplaced: true });
+ } catch { return null; } // An unreadable document must retain the paid lock.
+ }
+
_visibleChallengeDialogFromFrames(frameEntries, navigationFrames) {
const candidates = [];
const frameContexts = [];
@@ -9841,11 +9876,17 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
async _captchaMutationPreflight(tabId, toolName, toolArgs = {}, abortSignal = null) {
this._throwIfAborted(abortSignal);
+ if (toolName === 'done' && ['failed', 'partial'].includes(normalizeDoneOutcome(toolArgs?.outcome))) return null;
const gatedCompletion = toolName === 'done' || toolName === 'done_json';
const gatedAction = this._isBrowserMutationTool(toolName)
|| gatedCompletion
|| isNetworkMutation(toolName, toolArgs);
- if (!gatedAction || toolName === 'solve_captcha' || Agent.NAV_TOOLS.has(toolName)) return null;
+ if (toolName === 'solve_captcha') {
+ await this._refreshCaptchaGateDocument(tabId);
+ this._throwIfAborted(abortSignal);
+ return null;
+ }
+ if (!gatedAction || Agent.NAV_TOOLS.has(toolName)) return null;
const activeGate = this._captchaGateForTools(tabId, this._captchaGateStates.get(tabId));
if (
activeGate
@@ -9901,6 +9942,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
}
let activeGate = this._captchaGateForTools(tabId, this._captchaGateStates.get(tabId));
+ let navigationClearance = null;
const treeFilter = String(toolArgs?.filter || 'all').toLowerCase();
let observedChallengeFrameId = Number.isInteger(toolResult.captchaChallengeFrameId)
? toolResult.captchaChallengeFrameId
@@ -9962,6 +10004,45 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
failedDiagnostics = error?.captchaDiagnostics || null;
}
};
+ // A route change may be pushState/replaceState in the same document.
+ // Keep the failed solve until the root document is replaced or a complete
+ // inspection proves the original widget and challenge have disappeared.
+ const gatedPageUrl = activeGate?.pageUrl || String(activeGate?.key || '').split('\n')[0];
+ const pathChanged = this._normalizeUrlPath(pageUrl) !== this._normalizeUrlPath(gatedPageUrl);
+ if (activeGate && /^https?:\/\//i.test(gatedPageUrl)
+ && (pathChanged || activeGate.rootDocument?.timeOrigin > 0)) {
+ try {
+ const currentUrl = await this._currentUrl(tabId);
+ if (this._normalizeUrlPath(currentUrl) === this._normalizeUrlPath(pageUrl)) {
+ await inspectCaptchaFrames();
+ const previousRoot = activeGate.rootDocument;
+ const currentRoot = detection?.rootDocument;
+ const rootReplaced = previousRoot?.timeOrigin > 0 && currentRoot?.timeOrigin > 0
+ && previousRoot.timeOrigin !== currentRoot.timeOrigin
+ && this._normalizeUrl(currentRoot.url) === this._normalizeUrl(currentUrl);
+ const identity = activeGate.captchaCandidateIdentity;
+ // A sibling/relocated copy of the same widget is deliberately
+ // conservative here; only a new document can reset that solve lock.
+ const originalWidgetPresent = identity && (detection?.candidates || []).some(candidate =>
+ captchaTypesMatch(identity.type, candidate.type, identity.isEnterprise, candidate.isEnterprise)
+ && (!identity.websiteKey || candidate.websiteKey === identity.websiteKey));
+ let widgetGone = false;
+ if (pathChanged && !rootReplaced && !challenge && !detectionFailed && detection?.inspectionComplete
+ && !originalWidgetPresent) {
+ const inspection = await this._detectChallengeDialogBeforeMutation(tabId, { includeStatus: true });
+ widgetGone = inspection.inspectionComplete && !inspection.challenge;
+ }
+ if ((rootReplaced || widgetGone)
+ && this._normalizeUrl(await this._currentUrl(tabId)) === this._normalizeUrl(currentUrl)) {
+ navigationClearance = rootReplaced
+ ? await this._refreshCaptchaGateDocument(tabId, currentRoot)
+ : this._clearCaptchaGateAfterPageChange(tabId, gatedPageUrl, currentUrl, toolResult);
+ if (navigationClearance) toolResult.captchaGate = navigationClearance;
+ if (navigationClearance) activeGate = null;
+ }
+ }
+ } catch { /* Inconclusive document/widget inspection retains the solve lock. */ }
+ }
let languageNeutralFrameTrigger = false;
const hasDialogSurface = toolResult.pageGate?.surface === 'dialog'
|| /^\s*(?:dialog|alertdialog)(?=\s|$)/im.test(toolResult.pageContent);
@@ -10178,7 +10259,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
toolResult.captchaGate = guardedState.publicGate;
return { gate: guardedState.publicGate, loopCheck };
}
- return { gate: null, loopCheck };
+ return { gate: navigationClearance, loopCheck };
}
const key = captchaChallengeKey(pageUrl, challenge.normalizedLabel);
@@ -10272,6 +10353,8 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
: null;
this._captchaGateStates.set(tabId, {
key,
+ pageUrl,
+ ...(detection?.rootDocument ? { rootDocument: detection.rootDocument } : {}),
status: publicGate.status,
publicGate,
...(captchaCandidateIdentity ? { captchaCandidateIdentity } : {}),
@@ -32893,8 +32976,9 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
// A new root may expose a new CAPTCHA. A reloaded child frame in
// the same root has already used this document's paid dispatch.
if (documentStatus === 'root_changed') {
+ if (record.automatic) await this._refreshCaptchaGateDocument(tabId);
record.documentRetired = true;
- this._captchaGateStates.delete(tabId);
+ if (!record.automatic) this._captchaGateStates.delete(tabId);
}
return false;
}
@@ -32942,6 +33026,8 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
websiteURL = tab?.url || '';
} catch {}
+ const pageUrl = websiteURL;
+
if (args?.providerTasks) {
if (args.inject !== false) return noDispatchFailure('Native CAPTCHA methods require inject: false. Apply the returned structured answer with apply_captcha_solution after inspecting the page.');
const prepared = prepareNativeCaptchaTasks(providers, args.providerTasks);
@@ -33013,8 +33099,8 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
// the model gets the remedy, not just the rejection.
let detectionNote = null;
let detected = null;
+ let detection = null;
if (type !== 'image_to_text') {
- let detection = null;
try {
detection = await detectCaptcha(tabId, {
type,
@@ -33171,8 +33257,75 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
);
}
+ let automaticAnswer = null;
+ if (type !== 'image_to_text') {
+ await this._refreshCaptchaGateDocument(tabId, detection?.rootDocument);
+ // The model can solve directly from a screenshot before any tree
+ // read arms a gate. Reserve and persist that paid attempt here,
+ // after argument validation but before contacting any provider.
+ const previousGate = this._captchaGateStates.get(tabId);
+ if (previousGate?.publicGate?.solveAttempted || previousGate?.publicGate?.solveFailed) {
+ return noDispatchFailure('An automatic CAPTCHA solve was already dispatched for this challenge. Verify the page or ask for manual completion; do not spend again.');
+ }
+ const previousAnswer = this._nativeCaptchaSolutions?.get(tabId);
+ const currentRoot = detection?.rootDocument;
+ if (currentRoot && previousAnswer?.dispatchedTimeOrigins?.has(currentRoot.timeOrigin)) {
+ return noDispatchFailure('A CAPTCHA solve was already dispatched for this page document. Use its result or ask for manual completion; do not spend again.');
+ }
+ if (!wantInject) {
+ const frames = await browser.webNavigation.getAllFrames({ tabId });
+ const documents = await captureCaptchaDocuments(tabId, frames, browser);
+ const root = documents.find(document => document.frameId === 0 && document.url === pageUrl);
+ if (!root) return noDispatchFailure('Could not bind this page document before the token-only CAPTCHA request.');
+ const dispatchedTimeOrigins = new Set(previousAnswer?.dispatchedTimeOrigins || []);
+ if (dispatchedTimeOrigins.has(root.timeOrigin)) return noDispatchFailure('A CAPTCHA solve was already dispatched for this page document. Do not spend again.');
+ dispatchedTimeOrigins.add(root.timeOrigin);
+ automaticAnswer = { pageUrl, createdAt: Date.now(), applied: false, automatic: true,
+ documents, dispatchedTimeOrigins };
+ this._nativeCaptchaSolutions ||= new Map();
+ this._nativeCaptchaSolutions.set(tabId, automaticAnswer);
+ }
+ const identity = captchaGateCandidateIdentity(detected);
+ const answerRoot = automaticAnswer?.documents.find(document => document.frameId === 0);
+ const rootDocument = answerRoot ? { url: answerRoot.url, timeOrigin: answerRoot.timeOrigin } : currentRoot;
+ const publicGate = { ...previousGate?.publicGate, status: 'manual_required',
+ solveAttempted: true, selectedType: type,
+ ...(identity ? { candidateNotCorrelated: false } : {}) };
+ this._captchaGateStates.set(tabId, {
+ ...previousGate,
+ key: previousGate?.key || captchaChallengeKey(pageUrl, 'automatic captcha solve'),
+ pageUrl,
+ ...(rootDocument ? { rootDocument } : {}),
+ ...(identity ? { captchaCandidateIdentity: identity } : {}),
+ status: publicGate.status,
+ publicGate,
+ });
+ // A worker interruption must retain a manual gate, even if the
+ // provider accepted the request before its result was recorded.
+ const saved = await this._persistNow(tabId);
+ if (!saved?.ok) {
+ if (previousGate) this._captchaGateStates.set(tabId, previousGate);
+ else this._captchaGateStates.delete(tabId);
+ if (automaticAnswer) {
+ if (previousAnswer) this._nativeCaptchaSolutions.set(tabId, previousAnswer);
+ else this._nativeCaptchaSolutions.delete(tabId);
+ }
+ return noDispatchFailure('Could not save the CAPTCHA dispatch lock. No provider was contacted; retry after session storage is available.');
+ }
+ }
+
dispatched = true;
const result = await solveCaptchaWithProviders(providers, params);
+ if (automaticAnswer) {
+ automaticAnswer.solution = { ...result.solution, token: result.token };
+ automaticAnswer.provider = result.provider;
+ automaticAnswer.method = 'automatic';
+ automaticAnswer.family = type;
+ automaticAnswer.taskId = result.taskId;
+ automaticAnswer.createdAt = Date.now();
+ this._captchaSolveGateAfterTool(tabId, 'solve_captcha', { success: true, applicationRequired: true });
+ await this._persistNow(tabId);
+ }
if (wantInject && result.provider === 'nonecap' && result.solution?.userAgent
&& result.solution.userAgent !== params.userAgent) {
return { success: false, dispatched: true, manualCompletionRequired: true,
@@ -33188,6 +33341,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
fieldName: result.fieldName,
alsoSet: result.alsoSet,
token: result.token,
+ respKey: result.solution?.respKey,
callbackHint: detected.callbackName || null,
target: detected ? {
frameId: detected.frameId,
@@ -33214,7 +33368,6 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
type,
taskId: result.taskId,
provider: result.provider,
- token: result.token,
...(result.solution?.respKey ? { respKey: result.solution.respKey } : {}),
...(result.solution?.userAgent ? { solverUserAgent: result.solution.userAgent } : {}),
tokenPreview: result.token ? `${String(result.token).slice(0, 24)}…(${String(result.token).length} chars)` : null,
@@ -33224,14 +33377,19 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
selectionReason: detected?.selectionReason || null,
detectedType: detected?.type || null,
injected: injection?.success === true,
+ ...(automaticAnswer ? { applicationRequired: true } : {}),
injection,
- note: !wantInject
- ? 'Token returned without injection. Apply this token to the intended response field; do not request another paid solve for the same challenge.'
+ note: automaticAnswer
+ ? 'Token returned without injection. Inspect the page and call apply_captcha_solution with observed frame/field or callback bindings and path: token. The paid answer is saved; do not request another solve.'
+ : !wantInject ? 'Recognition answer returned without page injection.'
: injection?.success
? (injection.calledCallback
? 'Token was inserted into the selected frame and its callback was invoked. Wait for the page to react, then verify whether the challenge cleared.'
: 'Token was inserted into the selected frame, but no unique callback was invoked. Verify page progress before submitting or taking another action; do not request another paid solve.')
: 'The CAPTCHA solver returned a token, but targeted injection failed. The challenge is not confirmed cleared; do not request another paid solve for the same token.',
+ // Keep injection diagnostics ahead of long tokens in trace exports.
+ token: result.token,
+ ...(automaticAnswer ? { solution: automaticAnswer.solution } : {}),
};
} catch (e) {
const error = `solve_captcha failed: ${e.message}`;
diff --git a/src/firefox/src/agent/captcha-frame-runtime.js b/src/firefox/src/agent/captcha-frame-runtime.js
index 22389a3e5..a92f7d8ed 100644
--- a/src/firefox/src/agent/captcha-frame-runtime.js
+++ b/src/firefox/src/agent/captcha-frame-runtime.js
@@ -1090,6 +1090,7 @@ export function detectCaptchaCandidatesInPage(scope = null, matcherOptions = nul
frameContext: {
frameUrl,
frameName,
+ documentTimeOrigin,
childFrames,
},
};
@@ -1309,11 +1310,6 @@ export function injectCaptchaTokenInPage(payload, scope = null) {
}
return element;
};
- for (const field of injectableFields) {
- setOn(field.name, field.element);
- }
- const fieldsTouched = injectableFields.length;
-
const pageWindow = frameWindow.wrappedJSObject || frameWindow;
const callbacks = [];
const addCallback = (fn, source) => {
@@ -1329,8 +1325,20 @@ export function injectCaptchaTokenInPage(payload, scope = null) {
return null;
}
};
+ // The bridge remembers closure callbacks supplied to render(), including
+ // widget-bound execute({async:true}) continuations. Query before dispatching
+ // field events, which may remove or replace the selected widget.
+ let callbackBridgeAvailable = false;
+ try {
+ const bridge = pageWindow.__webbrainCaptchaCallbacks;
+ callbackBridgeAvailable = typeof bridge?.callbacks === 'function';
+ const registered = bridge?.callbacks(
+ target.type, target.websiteKey, fieldName, target.responseFieldId, target.responseFieldIndex,
+ );
+ for (const entry of registered || []) addCallback(entry.fn, entry.source);
+ } catch (_) { /* Older tabs still use observed names and vendor discovery. */ }
const callbackHint = payload?.callbackHint || null;
- if (callbackHint) {
+ if (!callbacks.length && callbackHint) {
addCallback(resolveNamedCallback(callbackHint), `data-callback:${callbackHint}`);
}
if (!callbacks.length) {
@@ -1381,12 +1389,17 @@ export function injectCaptchaTokenInPage(payload, scope = null) {
};
if (!callbacks.length) collectGoogleCallbacks();
+ for (const field of injectableFields) {
+ setOn(field.name, field.element);
+ }
+ const fieldsTouched = injectableFields.length;
+
let calledCallback = false;
let callbackSource = null;
let callbackError = null;
if (callbacks.length === 1) {
try {
- callbacks[0].fn.call(pageWindow, token);
+ callbacks[0].fn.call(pageWindow, token, payload?.respKey);
calledCallback = true;
callbackSource = callbacks[0].source;
} catch (error) {
@@ -1413,6 +1426,7 @@ export function injectCaptchaTokenInPage(payload, scope = null) {
callbackSource,
callbackAmbiguous: callbacks.length > 1,
callbackCandidates: callbacks.length,
+ callbackBridgeAvailable,
callbackError,
siteKeyMatched,
challengeMarkerMatched,
diff --git a/src/firefox/src/agent/captcha-hcaptcha-providers.js b/src/firefox/src/agent/captcha-hcaptcha-providers.js
index 9fed02aee..a8cc479c9 100644
--- a/src/firefox/src/agent/captcha-hcaptcha-providers.js
+++ b/src/firefox/src/agent/captcha-hcaptcha-providers.js
@@ -15,11 +15,21 @@ async function request(id, apiKey, path, { body, timeoutMs = 30_000, allowPendin
});
const result = await response.json().catch(() => null);
if (!result || typeof result !== 'object' || Array.isArray(result)) throw new Error(`${NAMES[id]}: invalid response.`);
- // NopeCHA v1 reports an unfinished job as HTTP 409 / code 14. Only polls
- // may treat this as pending; a rejected creation must never be re-submitted.
- if (allowPending && id === 'nopecha' && response.status === 409 && result.code === 14) return null;
+ // v1 uses code:14 / HTTP 409; older responses use error:14 with HTTP 200.
+ // Accept numeric strings and nested error codes as well, but only while
+ // polling an existing job. Auth, quota, rate-limit and server errors are
+ // terminal even if their body happens to contain a pending code.
+ const code = result.code ?? result.error?.code ?? result.error;
+ const incomplete = code === 14 || code === '14';
+ if (allowPending && !body && id === 'nopecha' && incomplete
+ && (response.ok || response.status === 409)) return null;
if (!response.ok || result.error || result.code) {
- throw new Error(`${NAMES[id]}: ${result.error?.message || result.message || result.error?.code || `HTTP ${response.status}`}`);
+ const message = String(result.error?.message || result.message || result.error?.code || 'Request failed')
+ .split(apiKey).join('[redacted]');
+ const numericCode = typeof code === 'number' || (typeof code === 'string' && /^\d+$/.test(code))
+ ? `; code ${code}` : '';
+ // Keep phase/status in traces without including keys, task IDs or payloads.
+ throw new Error(`${NAMES[id]}: ${message} (${body ? 'POST' : 'GET'} ${path.split('?')[0]}; HTTP ${response.status}${numericCode})`);
}
return result;
}
diff --git a/src/firefox/src/agent/captcha-json-api.js b/src/firefox/src/agent/captcha-json-api.js
index abb7a8b5e..d5dca35ca 100644
--- a/src/firefox/src/agent/captcha-json-api.js
+++ b/src/firefox/src/agent/captcha-json-api.js
@@ -19,7 +19,7 @@ export async function getJsonCaptchaBalance(apiBase, name, apiKey) {
return { balance: Number(result.balance) };
}
-export async function solveJsonCaptcha(apiBase, name, apiKey, task) {
+export async function solveJsonCaptcha(apiBase, name, apiKey, task, { pendingStatuses = ['processing'] } = {}) {
if (!apiKey) throw new Error(`No ${name} API key configured.`);
const created = await postJson(apiBase, name, 'createTask', { clientKey: apiKey, task });
if (created.status === 'ready') return { taskId: created.taskId, solution: created.solution ?? {} };
@@ -31,7 +31,7 @@ export async function solveJsonCaptcha(apiBase, name, apiKey, task) {
if (remaining <= 0) break;
const result = await postJson(apiBase, name, 'getTaskResult', { clientKey: apiKey, taskId: created.taskId }, Math.min(30_000, remaining));
if (result.status === 'ready') return { taskId: created.taskId, solution: result.solution ?? {} };
- if (result.status !== 'processing') throw new Error(`${name} getTaskResult: unexpected status`);
+ if (!pendingStatuses.includes(result.status)) throw new Error(`${name} getTaskResult: unexpected status`);
}
throw new Error(`${name}: timed out waiting for solution.`);
}
diff --git a/src/firefox/src/agent/captcha-native-providers.js b/src/firefox/src/agent/captcha-native-providers.js
index 027238db4..fa62645b4 100644
--- a/src/firefox/src/agent/captcha-native-providers.js
+++ b/src/firefox/src/agent/captcha-native-providers.js
@@ -517,7 +517,8 @@ export async function solveNativeCaptchaTasks(prepared) {
for (const { provider, contract, task, family } of prepared) {
try {
const result = JSON_BASES[provider.id]
- ? await solveJsonCaptcha(JSON_BASES[provider.id], provider.id, provider.apiKey, task)
+ ? await solveJsonCaptcha(JSON_BASES[provider.id], provider.id, provider.apiKey, task,
+ provider.id === 'capsolver' ? { pendingStatuses: ['idle', 'processing'] } : {})
: provider.id === 'nopecha' ? await solveNopechaTask(provider.apiKey, contract.path, task)
: provider.id === 'nonecap' ? await solveNonecapTask(provider.apiKey, task)
: await solveForm(provider.apiKey, contract, task);
diff --git a/src/firefox/src/agent/captcha-solver.js b/src/firefox/src/agent/captcha-solver.js
index ce4d8aae5..93167971c 100644
--- a/src/firefox/src/agent/captcha-solver.js
+++ b/src/firefox/src/agent/captcha-solver.js
@@ -253,8 +253,10 @@ export async function solveCaptchaWithProviders(providers, params) {
export async function detectCaptcha(tabId, constraints = {}) {
let frames;
+ let navigationInspectionComplete = false;
try {
frames = await browser.webNavigation.getAllFrames({ tabId });
+ navigationInspectionComplete = Array.isArray(frames) && frames.some(frame => frame.frameId === 0);
} catch (_) {
frames = [{ frameId: 0, url: '' }];
}
@@ -386,8 +388,13 @@ export async function detectCaptcha(tabId, constraints = {}) {
const candidates = [...directCandidates, ...inheritedCandidates];
const frameContexts = batches.map(batch => batch.frameContext).filter(Boolean);
const visibleCandidates = applyCaptchaFrameVisibility(candidates, frameContexts, frames);
+ const root = frameContexts.find(frame => frame.frameId === 0);
return {
...selectCaptchaCandidate(visibleCandidates, constraints),
+ rootDocument: root && Number.isFinite(root.documentTimeOrigin) && root.documentTimeOrigin > 0
+ ? { url: root.frameUrl, timeOrigin: root.documentTimeOrigin } : null,
+ inspectionComplete: navigationInspectionComplete && !!root
+ && frames.every(frame => frameContexts.some(context => context.frameId === frame.frameId)),
diagnostics: buildCaptchaDiagnostics({
candidates: visibleCandidates,
frameContexts,
@@ -409,6 +416,7 @@ export async function injectToken(tabId, {
fieldName,
alsoSet,
token,
+ respKey,
callbackHint,
target = null,
}) {
@@ -425,6 +433,7 @@ export async function injectToken(tabId, {
fieldName,
alsoSet,
token,
+ respKey,
callbackHint,
target: target || {},
};
diff --git a/src/firefox/src/agent/tools.js b/src/firefox/src/agent/tools.js
index 1c09d5739..f11cb6b9a 100644
--- a/src/firefox/src/agent/tools.js
+++ b/src/firefox/src/agent/tools.js
@@ -1097,7 +1097,7 @@ export const AGENT_TOOLS = [
"type": "function",
"function": {
"name": "apply_captcha_solution",
- "description": "Apply the stored answer from the one native CAPTCHA solve to its original page. Bind solution paths to observed response fields, host-only cookies, image/grid clicks, or an observed named CAPTCHA callback. The frame host's Type, Click, or JavaScript permission is required for the corresponding binding. Never invent selectors/callbacks or execute returned scripts. Requires exact observed frameId and frameUrl; cookie bindings require frame 0. Match any required proxy/User-Agent first. Then verify fresh page state. This never requests a paid solve.",
+ "description": "Apply the stored answer from a native or token-only CAPTCHA solve to its original page. Bind solution paths to observed response fields, host-only cookies, image/grid clicks, or an observed named CAPTCHA callback. The frame host's Type, Click, or JavaScript permission is required for the corresponding binding. Never invent selectors/callbacks or execute returned scripts. Requires exact observed frameId and frameUrl; cookie bindings require frame 0. Match any required proxy/User-Agent first. Then verify fresh page state. This never requests a paid solve.",
"parameters": {
"type": "object",
"properties": {
@@ -1228,7 +1228,7 @@ export const AGENT_TOOLS = [
},
rqdata: { type: 'string', description: 'hCaptcha only — optional; preserve the exact rqdata when the widget exposes it. Never invent it.' },
imageBase64: { type: 'string', description: 'image_to_text only — base64-encoded image bytes (no data: prefix).' },
- inject: { type: 'boolean', description: 'After solving, inject the token into the detected frame\'s response field (textarea[name=g-recaptcha-response] etc.) and fire the widget\'s callback. Default true and requires a detected frame target. If the widget cannot be detected but type/websiteKey are known, set false to get only the token without page injection.' },
+ inject: { type: 'boolean', description: 'After solving, inject the token into the detected frame\'s response field (textarea[name=g-recaptcha-response] etc.) and fire the widget\'s callback. Default true and requires a detected frame target. If the widget cannot be detected but type/websiteKey are known, set false to save a token-only answer. Apply it using apply_captcha_solution with observed frame and field/callback bindings and path: token; get_captcha_capabilities can retrieve the saved answer without another solve.' },
},
required: [],
},
diff --git a/src/firefox/src/content/captcha-callback-bridge.js b/src/firefox/src/content/captcha-callback-bridge.js
new file mode 100644
index 000000000..60ae3088d
--- /dev/null
+++ b/src/firefox/src/content/captcha-callback-bridge.js
@@ -0,0 +1,179 @@
+// Runs in MAIN at document_start: render callbacks are often closures, with
+// no data-callback attribute or global name to discover after a paid solve.
+// This bridge only remembers page registrations. It never buys a solve or
+// treats a callback invocation as proof that the site accepted an answer.
+(() => {
+ const bridgeName = '__webbrainCaptchaCallbacks';
+ if (window[bridgeName]) return;
+ const registrations = new Set();
+ const watched = new WeakMap();
+ const apis = new WeakMap();
+ const resolveCallback = value => typeof value === 'function' ? value
+ : typeof value === 'string' ? value.split('.').reduce((object, key) => object?.[key], window) : null;
+ const containerElement = value => typeof value === 'string'
+ ? document.getElementById(value) || (() => { try { return document.querySelector(value); } catch { return null; } })()
+ : value;
+ const live = record => record.container?.isConnected === true
+ && record.records.get(record.id) === record;
+
+ // Preserve native calls, receivers and return values. Setters also catch SDKs
+ // which first publish a ready() stub and install render() later in the load.
+ function watch(object, key, transform) {
+ if (!object || !['object', 'function'].includes(typeof object)) return;
+ let keys = watched.get(object);
+ if (!keys) watched.set(object, keys = new Set());
+ if (keys.has(key)) return;
+ const descriptor = Object.getOwnPropertyDescriptor(object, key);
+ if (descriptor && (!descriptor.configurable || descriptor.get || descriptor.set || descriptor.writable === false)) return;
+ keys.add(key);
+ const prepare = next => { try { return transform(next); } catch { return next; } };
+ let value = prepare(descriptor?.value);
+ Object.defineProperty(object, key, {
+ configurable: true, enumerable: descriptor?.enumerable ?? true,
+ get: () => value,
+ set: next => { value = prepare(next); },
+ });
+ }
+
+ function instrument(api, family) {
+ if (!api || !['object', 'function'].includes(typeof api)) return api;
+ if (apis.has(api)) {
+ // hCaptcha can publish the same API as grecaptcha for compatibility.
+ if (family === 'hcaptcha') apis.get(api).family = family;
+ return api;
+ }
+ const records = new Map();
+ const state = { records, family };
+ apis.set(api, state);
+ const find = id => id == null ? records.values().next().value
+ : records.get(String(id)) || [...records.values()].find(record => record.container === containerElement(id));
+ const clear = record => {
+ if (!record) return;
+ record.token = null;
+ record.tokenAt = 0;
+ record.respKey = null;
+ record.delivered = false;
+ record.generation += 1;
+ record.pending.clear();
+ };
+ const wrap = (key, factory) => watch(api, key, original =>
+ typeof original === 'function' ? factory(original) : original);
+
+ wrap('render', original => function (container, params, ...rest) {
+ const element = containerElement(container);
+ // Capture before render: SDKs are allowed to mutate the options object.
+ const callback = params?.callback ?? element?.getAttribute?.('data-callback');
+ const sitekey = String(params?.sitekey || element?.getAttribute?.('data-sitekey') || '');
+ let record;
+ const options = params && typeof params === 'object' ? { ...params } : params;
+ for (const event of ['expired-callback', 'chalexpired-callback', 'error-callback']) {
+ if (!options || !options[event]) continue;
+ const handler = options[event];
+ options[event] = function (...args) {
+ clear(record);
+ const fn = resolveCallback(handler);
+ if (typeof fn === 'function') return Reflect.apply(fn, this, args);
+ };
+ }
+ const args = [...arguments];
+ if (args.length > 1) args[1] = options;
+ const id = Reflect.apply(original, this, args);
+ if (id == null || !element || !sitekey) return id;
+ for (const previous of registrations) if (previous.container === element || (previous.records === records && previous.id === String(id))) {
+ registrations.delete(previous);
+ previous.records.delete(previous.id);
+ }
+ record = { family: state.family, records, id: String(id), container: element, sitekey, callback,
+ generation: 0, delivered: false, token: null, respKey: null, pending: new Set() };
+ records.set(record.id, record);
+ registrations.add(record);
+ // Bound memory to widgets still owned by the document.
+ for (const old of registrations) if (!live(old)) {
+ registrations.delete(old);
+ old.records.delete(old.id);
+ }
+ return id;
+ });
+ for (const method of ['reset', 'remove']) wrap(method, original => function (id, ...rest) {
+ const record = find(id);
+ const result = Reflect.apply(original, this, arguments);
+ clear(record);
+ if (method === 'remove' && record) {
+ registrations.delete(record);
+ records.delete(record.id);
+ }
+ return result;
+ });
+ wrap('getResponse', original => function (id, ...rest) {
+ const record = find(id);
+ if (record && live(record) && record.token && Date.now() - record.tokenAt <= 180_000) return record.token;
+ return Reflect.apply(original, this, arguments);
+ });
+ {
+ wrap('getRespKey', original => function (id, ...rest) {
+ const record = find(id);
+ if (record && live(record) && record.token && record.respKey && Date.now() - record.tokenAt <= 180_000) return record.respKey;
+ return Reflect.apply(original, this, arguments);
+ });
+ wrap('execute', original => function (id, options, ...rest) {
+ const record = find(id);
+ const result = Reflect.apply(original, this, arguments);
+ if (state.family !== 'hcaptcha' || !record || options?.async !== true || typeof result?.then !== 'function') return result;
+ // Invisible integrations may await execute() instead of registering a
+ // callback. Resolve that original page continuation with the same answer.
+ return new Promise((resolve, reject) => {
+ const pending = { resolve, generation: record.generation };
+ record.pending.add(pending);
+ Promise.resolve(result).then(resolve, reject).finally(() => record.pending.delete(pending));
+ });
+ });
+ }
+ return api;
+ }
+
+ Object.defineProperty(window, bridgeName, { configurable: true, value: {
+ callbacks(type, sitekey, fieldName, fieldId, fieldIndex) {
+ const family = String(type).startsWith('recaptcha') ? 'recaptcha' : type;
+ const fields = [...document.querySelectorAll(`textarea[name="${fieldName}"], input[name="${fieldName}"]`)];
+ const field = fieldId ? fields.find(element => element.id === fieldId)
+ : Number.isInteger(fieldIndex) ? fields[fieldIndex] : fields.length === 1 ? fields[0] : null;
+ return [...registrations].filter(record => {
+ if (!live(record) || record.family !== family || record.sitekey !== sitekey) return false;
+ if (typeof resolveCallback(record.callback) !== 'function' && !record.pending.size) return false;
+ // Site keys are shared across widgets. Never use one alone when the
+ // solver selected a particular response field.
+ if (field && !record.container.contains(field)) return false;
+ if ((fieldId || Number.isInteger(fieldIndex)) && !field) return false;
+ return true;
+ }).map(record => {
+ const generation = record.generation;
+ return {
+ source: `${record.family}.render`,
+ fn: (token, respKey) => {
+ if (!live(record) || record.generation !== generation || record.delivered) {
+ throw new Error('The registered CAPTCHA widget changed or its callback was already delivered.');
+ }
+ const callback = resolveCallback(record.callback);
+ const pending = [...record.pending].filter(item => item.generation === generation);
+ if (typeof callback !== 'function' && !pending.length) {
+ throw new Error('The registered CAPTCHA widget has no completion callback or pending execute promise.');
+ }
+ record.delivered = true;
+ record.token = token;
+ record.tokenAt = Date.now();
+ record.respKey = respKey || null;
+ for (const item of pending) { item.resolve({ response: token, key: respKey || '' }); record.pending.delete(item); }
+ if (typeof callback === 'function') Reflect.apply(callback, window, [token]);
+ },
+ };
+ });
+ },
+ } });
+ try { watch(window, 'hcaptcha', api => instrument(api, 'hcaptcha')); } catch {}
+ try { watch(window, 'turnstile', api => instrument(api, 'turnstile')); } catch {}
+ try { watch(window, 'grecaptcha', api => {
+ instrument(api, 'recaptcha');
+ watch(api, 'enterprise', enterprise => instrument(enterprise, 'recaptcha'));
+ return api;
+ }); } catch {}
+})();
diff --git a/test/captcha-callback-bridge-ui.mjs b/test/captcha-callback-bridge-ui.mjs
new file mode 100644
index 000000000..e7700c42a
--- /dev/null
+++ b/test/captcha-callback-bridge-ui.mjs
@@ -0,0 +1,151 @@
+// Real extension worlds, local pages only; no solver keys or paid requests.
+// Requires installed Firefox with BiDi (or FIREFOX_BINARY); Playwright's
+// patched Firefox does not reliably support native extension BiDi sessions.
+import { chromium } from 'playwright';
+import assert from 'node:assert/strict';
+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 { BidiSession } from '../firefox-companion/session.mjs';
+
+const sitekey = '10000000-ffff-ffff-ffff-000000000001';
+const server = createServer((req, res) => {
+ const url = new URL(req.url, 'http://localhost');
+ res.setHeader('Content-Security-Policy', "default-src 'self'; script-src 'self'; style-src 'unsafe-inline'");
+ if (url.pathname === '/sdk.js') {
+ res.setHeader('Content-Type', 'application/javascript');
+ res.end(`window.bridgeAtFirstScript = !!window.__webbrainCaptchaCallbacks;
+ (() => {
+ const widgets = new Map(); let counter = 0;
+ const api = { render(container, params) {
+ const element = document.getElementById(container);
+ const id = 'widget-' + (++counter);
+ const field = document.createElement('textarea');field.name = window.fieldName;field.id = 'answer-' + id;
+ element.append(field);widgets.set(id, { params });return id;
+ }, getResponse:()=>'', getRespKey:()=>'', reset:()=>{}, remove:()=>{},
+ execute(id) { return new Promise((resolve, reject) => Object.assign(widgets.get(id), { resolve, reject })); } };
+ const type = new URL(location.href).searchParams.get('type');
+ window.fieldName = type==='hcaptcha'?'h-captcha-response':type==='turnstile'?'cf-turnstile-response':'g-recaptcha-response';
+ window.api = type==='hcaptcha'?(window.hcaptcha=api):type==='turnstile'?(window.turnstile=api):(window.grecaptcha=api);
+ })();`);
+ return;
+ }
+ if (url.pathname === '/page.js') {
+ res.setHeader('Content-Type', 'application/javascript');
+ res.end(`(() => {
+ let accepted = 0;
+ const complete = token => {
+ if (token !== 'fixture-token' || api.getResponse(widget) !== token) throw new Error('app state was not updated');
+ document.querySelector('#next').disabled=false;
+ document.querySelector('#challenge').hidden=true;
+ document.querySelector('#result').textContent='accepted:'+ (++accepted);
+ };
+ const asyncMode = new URL(location.href).searchParams.get('mode')==='async';
+ const widget=api.render('widget', {sitekey:${JSON.stringify(sitekey)}, ...(asyncMode?{}:{callback:complete})});
+ api.render('other', {sitekey:${JSON.stringify(sitekey)},callback:()=>{throw new Error('wrong widget');}});
+ if(asyncMode)api.execute(widget,{async:true}).then(({response})=>complete(response));
+ })();`);
+ return;
+ }
+ res.setHeader('Content-Type', 'text/html');
+ const widgetClass = url.searchParams.get('type')==='hcaptcha'?'h-captcha':url.searchParams.get('type')==='turnstile'?'cf-turnstile':'g-recaptcha';
+ res.end(`<!doctype html><script src="/sdk.js"></script><div id="challenge" role="dialog" aria-label="Security verification"><div id="widget" class="${widgetClass}" data-sitekey="${sitekey}"></div></div><div id="other" class="${widgetClass}" data-sitekey="${sitekey}"></div><button id="next" disabled>Continue</button><output id="result"></output><script src="/page.js"></script>`);
+});
+await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
+const origin = `http://127.0.0.1:${server.address().port}`;
+const scenarios = [['hcaptcha','callback'],['hcaptcha','async'],['turnstile','callback'],['recaptcha_v2','callback']];
+const payload = type => ({fieldName:type==='hcaptcha'?'h-captcha-response':type==='turnstile'?'cf-turnstile-response':'g-recaptcha-response',token:'fixture-token',
+ target:{frameId:0,websiteKey:sitekey,type,responseFieldId:'answer-widget-1'}});
+const probe = `JSON.stringify({early:bridgeAtFirstScript,enabled:!document.querySelector('#next').disabled,result:document.querySelector('#result').textContent,hidden:document.querySelector('#challenge').hidden})`;
+async function verifyGate(tabId, input, api) {
+ const { Agent } = await import(api.runtime.getURL('src/agent/agent.js'));
+ const agent = new Agent({ getActive: () => ({ promptTier: 'full' }) });
+ agent._captchaGateStates.set(tabId, {
+ pageUrl: input.target.frameUrl, status: 'verification_pending',
+ publicGate: { status: 'verification_pending', solveAttempted: true },
+ captchaCandidateIdentity: { ...input.target },
+ });
+ const observation = await agent._observeCaptchaChallenge(tabId, 'get_accessibility_tree',
+ { pageUrl: input.target.frameUrl, pageContent: 'button Continue' }, {});
+ return observation.gate;
+}
+const assertProgress = (build, type, mode, result, state) => {
+ assert.equal(result.calledCallback, true, `${build} ${type} ${mode}: ${JSON.stringify(result)}`);
+ assert.equal(result.callbackCandidates, 1);
+ assert.equal(result.callbackBridgeAvailable, true);
+ assert.deepEqual(state, {early:true,enabled:true,result:'accepted:1',hidden:true});
+ console.log(`PASS ${build}: ${type} ${mode}, document-start capture, exact widget callback, page continuation and gate clearance`);
+};
+try {
+ const profile = await mkdtemp(join(tmpdir(),'webbrain-captcha-chrome-'));
+ let context;
+ try {
+ const extension = resolve('src/chrome');
+ context = await chromium.launchPersistentContext(profile, {headless:true,channel:'chromium',args:[`--disable-extensions-except=${extension}`,`--load-extension=${extension}`]});
+ await context.route('http**://**/*', route => new URL(route.request().url()).origin === origin ? route.continue() : route.abort());
+ const worker = context.serviceWorkers()[0] || await context.waitForEvent('serviceworker');
+ const control = await context.newPage();
+ await control.goto(new URL('/src/ui/settings.html', worker.url()).href);
+ const page = await context.newPage();
+ for (const [type, mode] of scenarios) {
+ await page.goto(`${origin}/fixture?type=${type}&mode=${mode}`);
+ const input = payload(type);input.target.frameUrl=page.url();
+ 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});
+ assert.equal(outcome.gate?.status, 'cleared', JSON.stringify(outcome));
+ assertProgress('chrome',type,mode,outcome.injection,JSON.parse(await page.evaluate(probe)));
+ }
+ } 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)));
+ }
+ } 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
new file mode 100644
index 000000000..bb6d92aa1
--- /dev/null
+++ b/test/captcha-callback-bridge.mjs
@@ -0,0 +1,131 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import vm from 'node:vm';
+import { readFile } from 'node:fs/promises';
+
+for (const build of ['chrome', 'firefox']) {
+ const source = await readFile(new URL(`../src/${build}/src/content/captcha-callback-bridge.js`, import.meta.url), 'utf8');
+ const { injectCaptchaTokenInPage } = await import(`../src/${build}/src/agent/captcha-frame-runtime.js`);
+ function fixture(family = 'hcaptcha') {
+ const name = family === 'hcaptcha' ? 'h-captcha-response' : family === 'turnstile' ? 'cf-turnstile-response' : 'g-recaptcha-response';
+ const hosts = [], fields = [];
+ const document = {
+ getElementById: id => [...hosts, ...fields].find(element => element.id === id),
+ querySelector: () => null,
+ querySelectorAll: selector => selector.includes('[data-callback]') ? []
+ : selector.includes('[data-sitekey]') ? hosts
+ : selector.includes('textarea[name=') ? fields.filter(field => selector.includes(`name="${field.name}"`)) : [],
+ };
+ const context = vm.createContext({ document, URL, URLSearchParams, performance: { timeOrigin: 1000 }, location: { href: 'https://fixture.test/join' }, Event: class {}, answers: [] });
+ context.window = context;
+ const evaluate = code => vm.runInContext(code, context);
+ evaluate(source);
+ const add = id => {
+ const field = { id: `answer-${id}`, name, value: '', tagName: 'TEXTAREA', dispatchEvent() {}, getAttribute: key => key === 'id' ? `answer-${id}` : null };
+ const host = { id, isConnected: true, contains: value => value === field, getAttribute: key => key === 'data-sitekey' ? 'site-key' : null };
+ hosts.push(host); fields.push(field);
+ return { host, field };
+ };
+ add('one'); add('two');
+ evaluate(`window.${family === 'recaptcha' ? 'grecaptcha' : family} = {
+ render(container, params) { window.lastOptions = params; return typeof container === 'string' ? container : container.id; },
+ getResponse() { return 'native'; }, getRespKey() { return 'native-key'; },
+ reset() { return 'reset-result'; }, remove() { return 'remove-result'; },
+ execute() { return new Promise((resolve, reject) => { window.nativeResolve = resolve; window.nativeReject = reject; }); }
+ }; window.api = ${family === 'recaptcha' ? 'grecaptcha' : family};`);
+ const render = (id = 'one', callback = 'token => answers.push([token, api.getResponse("one"), api.getRespKey("one")])') => evaluate(`api.render('${id}', { sitekey: 'site-key', callback: ${callback} })`);
+ const inject = (id = 'one') => injectCaptchaTokenInPage({ fieldName: name, token: 'paid-token', respKey: 'paid-key',
+ target: { frameId: 0, frameUrl: context.location.href, websiteKey: 'site-key', type: family === 'recaptcha' ? 'recaptcha_v2' : family, responseFieldId: `answer-${id}`, documentTimeOrigin: 1000 } }, { document, window: context });
+ return { context, evaluate, render, inject, hosts, fields, name };
+ }
+ for (const family of ['hcaptcha', 'turnstile', 'recaptcha']) test(`${build}: ${family} closure receives the selected token once and getResponse agrees`, () => {
+ const f = fixture(family);
+ assert.equal(f.render(), 'one');
+ f.render('two', 'token => answers.push(["wrong", token])');
+ const result = f.inject();
+ assert.equal(result.calledCallback, true, result.callbackError);
+ assert.equal(result.callbackSource, `${family}.render`);
+ assert.equal(result.callbackCandidates, 1);
+ assert.equal(f.fields[0].value, 'paid-token');
+ assert.equal(f.fields[1].value, '');
+ assert.deepEqual(JSON.parse(JSON.stringify(f.context.answers)), [['paid-token', 'paid-token', 'paid-key']]);
+ assert.equal(f.inject().calledCallback, false);
+ assert.equal(f.context.answers.length, 1);
+ });
+ test(`${build}: hCaptcha async execute resumes without a globally named callback`, async () => {
+ const f = fixture(); f.render('one', 'undefined');
+ const continuation = f.evaluate('api.execute("one", {async:true})');
+ assert.equal(f.inject().calledCallback, true);
+ assert.deepEqual(JSON.parse(JSON.stringify(await continuation)), { response: 'paid-token', key: 'paid-key' });
+ f.context.nativeReject(new Error('late native rejection'));
+ await new Promise(resolve => setImmediate(resolve));
+ });
+ test(`${build}: native execute resolution and rejection are preserved`, async () => {
+ const f = fixture(); f.render('one', 'undefined');
+ const first = f.evaluate('api.execute("one", {async:true})');
+ f.context.nativeResolve({ response: 'human-token', key: 'human-key' });
+ assert.equal((await first).response, 'human-token');
+ await new Promise(resolve => setImmediate(resolve));
+ const second = f.evaluate('api.execute("one", {async:true})');
+ f.context.nativeReject(new Error('challenge-closed'));
+ await assert.rejects(second, /challenge-closed/);
+ await new Promise(resolve => setImmediate(resolve));
+ assert.equal(f.inject().callbackCandidates, 0);
+ });
+ test(`${build}: a reset during field events invalidates the captured callback`, () => {
+ const f = fixture(); f.render();
+ f.fields[0].dispatchEvent = () => f.evaluate('api.reset("one")');
+ const result = f.inject();
+ assert.equal(result.calledCallback, false);
+ assert.match(result.callbackError, /changed/);
+ assert.equal(f.context.answers.length, 0);
+ assert.equal(f.evaluate('api.getResponse("one")'), 'native');
+ });
+ test(`${build}: removal and expiry discard captured responses`, () => {
+ const f = fixture();
+ f.evaluate('api.render("one", {sitekey:"site-key", callback:token=>answers.push(token), "expired-callback":()=>answers.push("expired")})');
+ assert.equal(f.inject().calledCallback, true);
+ f.evaluate('lastOptions["expired-callback"]()');
+ assert.equal(f.evaluate('api.getResponse("one")'), 'native');
+ assert.equal(f.evaluate('api.remove("one")'), 'remove-result');
+ assert.equal(f.inject().callbackCandidates, 0);
+ assert.deepEqual(JSON.parse(JSON.stringify(f.context.answers)), ['paid-token', 'expired']);
+ });
+ test(`${build}: detached and ambiguous widgets never invoke a closure`, () => {
+ const f = fixture(); f.render(); f.render('two');
+ f.hosts[0].isConnected = false;
+ assert.equal(f.inject().calledCallback, false);
+ f.hosts[0].isConnected = true;
+ f.fields.length = 0;
+ const callbacks = f.context.__webbrainCaptchaCallbacks.callbacks('hcaptcha', 'site-key', f.name, null, null);
+ assert.equal(callbacks.length, 2, 'shared site keys must not be collapsed into one widget');
+ });
+ test(`${build}: late SDK methods and enterprise render registrations are captured`, () => {
+ const f = fixture('recaptcha');
+ f.evaluate('grecaptcha = {ready: fn => fn()}; grecaptcha.enterprise = {}; grecaptcha.enterprise.render = (id, options) => id; grecaptcha.enterprise.render("one",{sitekey:"site-key",callback:token=>answers.push(token)})');
+ assert.equal(f.inject().calledCallback, true);
+ assert.deepEqual(JSON.parse(JSON.stringify(f.context.answers)), ['paid-token']);
+ });
+ test(`${build}: hCaptcha compatibility alias retains the hCaptcha family`, () => {
+ const f = fixture();
+ f.evaluate('grecaptcha = {render: id=>id}; hcaptcha = grecaptcha; hcaptcha.render("one",{sitekey:"site-key",callback:token=>answers.push(token)})');
+ assert.equal(f.inject().calledCallback, true);
+ });
+ test(`${build}: callback exceptions remain diagnostic and cannot be replayed`, () => {
+ const f = fixture(); f.render('one', 'token => { answers.push(token); throw new Error("site-handler-failed"); }');
+ const result = f.inject();
+ assert.equal(result.calledCallback, false);
+ assert.equal(result.callbackError, 'site-handler-failed');
+ 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 () => {
+ 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);
+ });
+}
+test('callback bridge is identical in Chrome and Firefox', async () => {
+ assert.equal(await readFile('src/chrome/src/content/captcha-callback-bridge.js', 'utf8'), await readFile('src/firefox/src/content/captcha-callback-bridge.js', 'utf8'));
+});
diff --git a/test/captcha-hcaptcha-providers.mjs b/test/captcha-hcaptcha-providers.mjs
index 24ee10e53..cf2c8f34a 100644
--- a/test/captcha-hcaptcha-providers.mjs
+++ b/test/captcha-hcaptcha-providers.mjs
@@ -61,6 +61,49 @@ for (const build of ['chrome', 'firefox']) {
assert.equal(calls[1].query.get('id'),'job/id'); assert.equal(calls[1].options.method,'GET');
for (const c of calls) { assert.equal(c.host,'api.nopecha.com'); assert.equal(c.path,'/v1/token/hcaptcha'); assert.equal(c.options.headers.Authorization,`Basic ${keys.nopecha}`); assert.equal(c.url.includes(keys.nopecha),false); }
});
+ for (const [label, status, pending] of [
+ ['legacy error', 200, { error: 14, message: 'Incomplete job' }],
+ ['string code', 409, { code: '14', message: 'Incomplete job' }],
+ ['nested code', 200, { error: { code: 14, message: 'Incomplete job' } }],
+ ]) for (const route of ['token/hcaptcha', 'recognition/hcaptcha']) {
+ test(`${build}: NopeCHA ${route} keeps polling ${label} on the same job`, async t => {
+ const solution = route.startsWith('token/') ? 'token' : [true, false];
+ const calls = api(t, (call, n) => n === 1 ? { data: 'one-job' }
+ : n < 4 ? Response.json(pending, { status }) : { data: solution });
+ const result = await h.solveNopechaTask(keys.nopecha, `/v1/${route}`, { sitekey: params.websiteKey });
+ assert.deepEqual(result, { taskId: 'one-job', solution });
+ assert.equal(calls.filter(c => c.options.method === 'POST').length, 1);
+ assert.deepEqual(calls.slice(1).map(c => c.query.get('id')), ['one-job', 'one-job', 'one-job']);
+ });
+ }
+ test(`${build}: NopeCHA pending compatibility retains the deadline without resubmitting`, async t => {
+ const calls = api(t, call => call.options.method === 'POST' ? { data: 'one-job' }
+ : { error: '14', message: 'Incomplete job' });
+ await assert.rejects(h.solveWithHcaptchaProvider('nopecha', keys.nopecha, params), /timed out/);
+ assert.equal(calls.filter(c => c.options.method === 'POST').length, 1);
+ assert.ok(calls.length > 2 && calls.length < 100);
+ });
+ for (const [status, body] of [
+ [403, { code: 16, message: 'Out of credit' }],
+ [401, { code: 14, message: 'Incomplete job' }],
+ [429, { code: 14, message: 'Incomplete job' }],
+ [500, { code: 14, message: 'Incomplete job' }],
+ [409, { message: 'Incomplete job' }],
+ [200, { error: 15, message: 'Incomplete job' }],
+ ]) test(`${build}: NopeCHA does not mistake HTTP ${status} ${JSON.stringify(body)} for pending`, async t => {
+ const calls = api(t, (call, n) => n === 1 ? { data: 'one-job' } : Response.json(body, { status }));
+ await assert.rejects(h.solveWithHcaptchaProvider('nopecha', keys.nopecha, params), /GET.*HTTP/);
+ assert.equal(calls.length, 2);
+ });
+ test(`${build}: NopeCHA creation errors include safe phase diagnostics and never retry`, async t => {
+ const calls = api(t, () => Response.json({ error: 14, message: `Incomplete job ${keys.nopecha}` }, { status: 409 }));
+ await assert.rejects(h.solveWithHcaptchaProvider('nopecha', keys.nopecha, params), error => {
+ assert.match(error.message, /POST \/v1\/token\/hcaptcha.*HTTP 409.*code 14/);
+ assert.equal(error.message.includes(keys.nopecha), false);
+ return true;
+ });
+ assert.equal(calls.length, 1);
+ });
test(`${build}: hCaptcha fallback skips the original five services and accepts NoneCap metadata`, async t => {
const calls=api(t,call=>call.host==='api.nopecha.com' ? Response.json({code:16,message:'Out of credit'},{status:403}) : call.options.method==='POST' ? {id:'solve_1',status:'pending'} : {id:'solve_1',status:'solved',token:'P1_token',resp_key:'E0_key',user_agent:'solver-agent'});
const result=await solver.solveCaptchaWithProviders(config.getCaptchaProviders(stored),params);
@@ -68,6 +111,14 @@ for (const build of ['chrome', 'firefox']) {
assert.deepEqual(calls.map(c=>c.host),['api.nopecha.com','api.nonecap.com','api.nonecap.com']);
assert.equal(calls[1].options.headers.Authorization,`Bearer ${keys.nonecap}`); assert.equal(calls[1].path,'/v1/solves'); assert.equal(calls[2].path,'/v1/solves/solve_1');
});
+ test(`${build}: NoneCap pending and solving states poll the original job until solved`, async t => {
+ const calls = api(t, (call, n) => ({ id: 'one-job', status: n === 1 ? 'pending' : n === 2 ? 'solving' : 'solved',
+ ...(n === 3 ? { token: 'answer' } : {}) }));
+ const result = await h.solveWithHcaptchaProvider('nonecap', keys.nonecap, params);
+ assert.equal(result.solution.gRecaptchaResponse, 'answer');
+ assert.equal(calls.filter(c => c.options.method === 'POST').length, 1);
+ assert.deepEqual(calls.slice(1).map(c => c.path), ['/v1/solves/one-job', '/v1/solves/one-job']);
+ });
for (const id of ['nopecha','nonecap']) {
test(`${build}: ${id} reports credits and validates balance responses`,async t=>{
const calls=api(t,()=>id==='nopecha'?{credit:250}:{credits_balance:250});
diff --git a/test/captcha-native-providers.mjs b/test/captcha-native-providers.mjs
index ae77ec77d..359e62ae7 100644
--- a/test/captcha-native-providers.mjs
+++ b/test/captcha-native-providers.mjs
@@ -237,6 +237,27 @@ for (const browser of ['chrome','firefox']) {
assert.deepEqual(calls.map(c=>c.url.hostname),['api.capsolver.com','api.2captcha.com']);
assert.equal(calls[0].body.task.captchaId,'id');assert.equal(calls[1].body.task.initParameters.captcha_id,'id');
});
+ for (const id of ['capsolver', '2captcha', 'capmonster', 'anti-captcha']) {
+ test(`${browser}: native ${id} waits for its pending job before considering fallback`, async t => {
+ const [, method, parameters] = fixtures.find(([provider]) => provider === id);
+ const calls = mockApi(t, (call, n) => n === 1 ? { errorId: 0, taskId: 'one-job' }
+ : n < 4 ? { errorId: 0, status: id === 'capsolver' && n === 2 ? 'idle' : 'processing' }
+ : { errorId: 0, status: 'ready', solution: { token: 'answer' } });
+ const result = await native.solveNativeCaptchaTasks(native.prepareNativeCaptchaTasks(providers,
+ [{ provider: id, method, parameters }]));
+ assert.equal(result.provider, id);
+ assert.equal(result.solution.token, 'answer');
+ assert.equal(calls.filter(c => c.url.pathname === '/createTask').length, 1);
+ assert.deepEqual(calls.slice(1).map(c => c.body.taskId), ['one-job', 'one-job', 'one-job']);
+ });
+ }
+ test(`${browser}: native JSON pending compatibility does not swallow terminal errors`, async t => {
+ const calls = mockApi(t, (call, n) => n === 1 ? { taskId: 'one-job' }
+ : { errorId: 1, errorCode: 'ERROR_ZERO_BALANCE', status: 'idle' });
+ await assert.rejects(native.solveNativeCaptchaTasks(native.prepareNativeCaptchaTasks(providers,
+ [{ provider: 'capsolver', method: 'GeeTestTaskProxyLess', parameters: { websiteURL: url, captchaId: 'id' } }])), /ERROR_ZERO_BALANCE/);
+ assert.equal(calls.length, 2);
+ });
test(`${browser}: recognition keeps false selections and zero coordinates`,async t=>{
const calls=mockApi(t,c=>c.options.method==='POST'?{data:'job'}:{data:[false,false,false]});
const result=await native.solveNativeCaptchaTasks(native.prepareNativeCaptchaTasks(providers,[{provider:'nopecha',method:'recognition/recaptcha',parameters:{task:'cars',grid:'3x3',image_data:['base64']}}]));
diff --git a/test/captcha-runtime-policy.mjs b/test/captcha-runtime-policy.mjs
index af87991ba..3d757ebc3 100644
--- a/test/captcha-runtime-policy.mjs
+++ b/test/captcha-runtime-policy.mjs
@@ -1,6 +1,7 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
+import vm from 'node:vm';
const captchaNames = ['get_captcha_capabilities', 'solve_captcha', 'apply_captcha_solution'];
const solverInstructions = /get_captcha_capabilities|solve_captcha|apply_captcha_solution|\[CAPTCHA SOLVER/;
test('CAPTCHA tool matrix matches Ask, Compact, Mid, Full and Dev availability', async () => {
@@ -39,6 +40,472 @@ for (const build of ['chrome', 'firefox']) {
agent.captchaProviderIds = enabled ? ['nonecap'] : [];
return agent;
}
+ function mockCaptchaPage(t, { url, timeOrigin = 2000, candidates = [], missingChild = false, navigationFails = false }) {
+ const apiName = build === 'chrome' ? 'chrome' : 'browser';
+ const previous = globalThis[apiName];
+ const payload = { candidates, frameContext: { frameUrl: url, documentTimeOrigin: timeOrigin, childFrames: [] },
+ challenge: candidates.some(candidate => candidate.activeChallengeFrameVisible)
+ ? { label: 'Security verification', normalizedLabel: 'security verification' } : null };
+ globalThis[apiName] = {
+ tabs: { get: async () => ({ url }), executeScript: async (tabId, options) => {
+ if (options.frameId === 5) throw new Error('Frame inspection failed');
+ return [payload];
+ } },
+ scripting: { executeScript: async () => [{ frameId: 0, result: payload }] },
+ webNavigation: { getAllFrames: async () => {
+ if (navigationFails) throw new Error('Navigation inspection failed');
+ return [{ frameId: 0, parentFrameId: -1, url }, ...(missingChild ? [{ frameId: 5, parentFrameId: 0, url: 'https://captcha.test/frame' }] : [])];
+ } },
+ };
+ t.after(() => { if (previous === undefined) delete globalThis[apiName]; else globalThis[apiName] = previous; });
+ return payload;
+ }
+ function automaticSolveFixture(t, { type = 'hcaptcha', injectionSucceeds = true, providerFails = false } = {}) {
+ const pageUrl = 'https://example.test/join';
+ const widget = { type, frameUrl: pageUrl, websiteKey: '5bd005a4-6ac8-4a86-8e60-53083832ed22',
+ visible: true, activeChallengeFrame: true, activeChallengeFrameVisible: true,
+ responseFieldId: 'captcha-response', responseFieldIndex: 0, documentTimeOrigin: 2000 };
+ const page = mockCaptchaPage(t, { url: pageUrl, candidates: [widget] });
+ const api = globalThis[build === 'chrome' ? 'chrome' : 'browser'];
+ api.tabs.get = async () => ({ url: page.frameContext.frameUrl });
+ api.webNavigation.getAllFrames = async () => [{ frameId: 0, parentFrameId: -1, url: page.frameContext.frameUrl }];
+ const agent = agentFor('act', 'full');
+ agent.captchaProviderIds = type === 'hcaptcha' ? ['nonecap'] : ['2captcha'];
+ agent.conversations.set(1, [{ role: 'system', content: 'test' }]);
+ const stored = {};
+ api.storage = {
+ local: { get: async () => type === 'hcaptcha'
+ ? { nonecapEnabled: true, nonecapApiKey: 'nc_live_' + 'a'.repeat(32) }
+ : { twoCaptchaEnabled: true, twoCaptchaApiKey: 'a'.repeat(32) } },
+ session: { get: async key => ({ [key]: stored[key] }), set: async value => Object.assign(stored, structuredClone(value)) },
+ };
+ const injection = { success: injectionSucceeds, fieldUpdated: injectionSucceeds, calledCallback: false };
+ if (build === 'chrome') {
+ const execute = api.scripting.executeScript;
+ api.scripting.executeScript = async options => options.func.name === 'read'
+ ? [{ frameId: 0, result: { url: page.frameContext.frameUrl, timeOrigin: page.frameContext.documentTimeOrigin } }]
+ : options.world === 'MAIN'
+ ? [{ frameId: 0, result: options.args?.[0]?.token ? injection : 'test-browser' }]
+ : execute(options);
+ } else {
+ delete api.scripting;
+ const execute = api.tabs.executeScript;
+ api.tabs.executeScript = async (tabId, options) => options.code === 'navigator.userAgent' ? ['test-browser']
+ : options.code.includes('injectCaptchaTokenInPage') ? [injection]
+ : options.code.includes('const read') || options.code.startsWith('(() => ({ url: location.href')
+ ? [{ url: page.frameContext.frameUrl, timeOrigin: page.frameContext.documentTimeOrigin }] : execute(tabId, options);
+ }
+ const requests = [];
+ const savedAtDispatch = [];
+ t.mock.method(globalThis, 'fetch', async (url, options) => {
+ requests.push({ url, options });
+ savedAtDispatch.push(structuredClone(stored[agent._convKey(1)]?.captchaGateState));
+ if (providerFails) throw new Error('Provider connection lost after dispatch');
+ return Response.json(type === 'hcaptcha' ? { id: 'paid-task', status: 'solved', token: 'paid-token' }
+ : url.endsWith('/createTask') ? { taskId: 123 }
+ : { status: 'ready', solution: { gRecaptchaResponse: 'paid-token', token: 'paid-token' } });
+ });
+ const timeout = globalThis.setTimeout;
+ t.mock.method(globalThis, 'setTimeout', (fn, delay, ...args) => timeout(fn, delay === 5000 ? 0 : delay, ...args));
+ return { agent, api, widget, page, pageUrl, stored, requests, savedAtDispatch };
+ }
+ for (const type of ['hcaptcha', 'recaptcha_v2', 'turnstile']) {
+ test(`${build}: ${type} solve before any tree gate is saved before dispatch and cannot be bought twice`, async t => {
+ const f = automaticSolveFixture(t, { type });
+ const result = await f.agent._executeToolImpl(1, 'solve_captcha', { type });
+ assert.equal(result.success, true, result.error);
+ assert.equal(result.injected, true);
+ assert.ok(JSON.stringify(result).indexOf('"injection":') < JSON.stringify(result).indexOf('"token":'),
+ 'long tokens must not hide application diagnostics in exported traces');
+ assert.equal(f.savedAtDispatch[0]?.publicGate.solveAttempted, true);
+ assert.equal(f.savedAtDispatch[0]?.pageUrl, f.pageUrl);
+ assert.equal(f.savedAtDispatch[0]?.captchaCandidateIdentity.websiteKey, f.widget.websiteKey);
+ assert.deepEqual(f.savedAtDispatch[0]?.rootDocument, { url: f.pageUrl, timeOrigin: 2000 });
+ const beforeRetry = f.requests.length;
+ const repeated = await f.agent._executeToolImpl(1, 'solve_captcha', { type });
+ assert.equal(repeated.noDispatch, true);
+ assert.equal(f.requests.length, beforeRetry);
+ const observed = await f.agent._observeCaptchaChallenge(1, 'get_accessibility_tree',
+ { pageUrl: f.pageUrl, pageContent: 'dialog "Security verification"' }, { filter: 'visible' });
+ assert.equal(observed.gate.status, 'manual_required');
+ assert.equal(observed.gate.solveAttempted, true);
+ assert.equal(f.agent._captchaGateBlockResult(1, 'solve_captcha', {}).denied, true);
+ const restored = agentFor('act', 'full');
+ await restored._hydrate(1);
+ assert.equal(restored._captchaGateBlockResult(1, 'solve_captcha', {}).denied, true);
+ });
+ }
+ for (const scenario of ['provider fails', 'injection fails', 'token only']) {
+ test(`${build}: ungated ${scenario} retains the paid solve lock`, async t => {
+ const f = automaticSolveFixture(t, { injectionSucceeds: scenario !== 'injection fails', providerFails: scenario === 'provider fails' });
+ const args = { type: 'hcaptcha', ...(scenario === 'token only' ? { inject: false } : {}) };
+ const result = await f.agent._executeToolImpl(1, 'solve_captcha', args);
+ assert.equal(result.dispatched, true);
+ assert.equal(f.agent._captchaGateStates.get(1)?.publicGate.solveAttempted, true);
+ const repeated = await f.agent._executeToolImpl(1, 'solve_captcha', args);
+ assert.equal(repeated.noDispatch, true);
+ assert.equal(f.requests.length, 1);
+ assert.equal(f.agent._captchaGateBlockResult(1, 'solve_captcha', { providerTasks: [{}] }).denied, true);
+ });
+ }
+ test(`${build}: an unpersisted automatic solve never reaches a provider and can be retried`, async t => {
+ const f = automaticSolveFixture(t);
+ const save = f.api.storage.session.set;
+ f.api.storage.session.set = async () => { throw new Error('Storage unavailable'); };
+ const result = await f.agent._executeToolImpl(1, 'solve_captcha', { type: 'hcaptcha' });
+ assert.equal(result.noDispatch, true);
+ assert.equal(f.requests.length, 0);
+ assert.equal(f.agent._captchaGateStates.has(1), false);
+ f.api.storage.session.set = save;
+ assert.equal((await f.agent._executeToolImpl(1, 'solve_captcha', { type: 'hcaptcha' })).success, true);
+ });
+ test(`${build}: invalid automatic solve arguments do not consume the solve`, async t => {
+ const f = automaticSolveFixture(t);
+ const result = await f.agent._executeToolImpl(1, 'solve_captcha', { type: 'hcaptcha', frameId: 999 });
+ assert.equal(result.noDispatch, true);
+ assert.equal(f.requests.length, 0);
+ assert.equal(f.agent._captchaGateStates.has(1), false);
+ });
+ for (const type of ['hcaptcha', 'recaptcha_v2', 'turnstile']) {
+ test(`${build}: ${type} token-only answers can be applied once after restoration without another solve`, async t => {
+ const f = automaticSolveFixture(t, { type });
+ f.page.candidates.length = 0; // The advertised fallback for undetectable widgets.
+ const result = await f.agent._executeToolImpl(1, 'solve_captcha', { type,
+ websiteKey: f.widget.websiteKey, inject: false });
+ assert.equal(result.success, true, result.error);
+ assert.equal(result.applicationRequired, true);
+ assert.equal(result.injected, false);
+ assert.equal(f.agent._captchaGateStates.get(1).status, 'verification_pending');
+ assert.equal(f.agent._captchaGateBlockResult(1, 'apply_captcha_solution', {}), null);
+ assert.equal(f.agent._captchaGateBlockResult(1, 'click', {}).denied, true);
+ const paidRequests = f.requests.length;
+ const restored = agentFor('act', 'full');
+ await restored._hydrate(1);
+ const discovery = await restored._executeToolImpl(1, 'get_captcha_capabilities', {});
+ assert.equal(discovery.pendingNativeAnswer.solution.token, 'paid-token');
+ assert.equal(discovery.pendingNativeAnswer.method, 'automatic');
+ const bad = await restored._executeToolImpl(1, 'apply_captcha_solution', {
+ frameId: 0, frameUrl: f.pageUrl, fields: [{ selector: '#response', path: 'missing' }] });
+ assert.equal(bad.success, false);
+ assert.equal(bad.applicationRetryable, true);
+ const values = [], callbacks = [];
+ class TextArea { set value(value) { values.push(value); } }
+ const field = new TextArea();
+ field.tagName = 'TEXTAREA';
+ field.dispatchEvent = () => {};
+ const sandbox = { location: { href: f.pageUrl }, performance: { timeOrigin: 2000 },
+ document: { querySelectorAll: selector => selector === '#response' ? [field] : [] },
+ window: { onCaptchaComplete: value => callbacks.push(value) },
+ HTMLTextAreaElement: TextArea, Event: class {} };
+ if (build === 'chrome') {
+ const execute = f.api.scripting.executeScript;
+ f.api.scripting.executeScript = async options => options.func.name === 'applyCaptchaValuesInPage'
+ ? [{ frameId: 0, result: vm.runInNewContext(`(${options.func.toString()})(...args)`, { ...sandbox, args: options.args }) }]
+ : execute(options);
+ } else {
+ const execute = f.api.tabs.executeScript;
+ f.api.tabs.executeScript = async (tabId, options) => options.code.includes('applyCaptchaValuesInPage')
+ ? [vm.runInNewContext(options.code, sandbox)] : execute(tabId, options);
+ }
+ const application = { frameId: 0, frameUrl: f.pageUrl,
+ fields: [{ selector: '#response', path: 'token' }], callback: { name: 'onCaptchaComplete', path: 'token' } };
+ const applied = await restored._executeToolImpl(1, 'apply_captcha_solution', application);
+ assert.equal(applied.success, true, applied.error);
+ assert.deepEqual(values, ['paid-token']);
+ assert.deepEqual(callbacks, ['paid-token']);
+ assert.equal((await restored._executeToolImpl(1, 'apply_captcha_solution', application)).success, false);
+ assert.equal(f.requests.length, paidRequests);
+ assert.deepEqual(values, ['paid-token']);
+ f.page.challenge = null;
+ const verified = await restored._observeCaptchaChallenge(1, 'get_accessibility_tree',
+ { pageUrl: f.pageUrl, pageContent: 'heading "Verified"' });
+ assert.equal(verified.gate.status, 'cleared');
+ assert.equal(restored._captchaGateBlockResult(1, 'click', {}), null);
+ });
+ }
+ for (const via of ['tree read', 'solve preflight', 'direct solve']) {
+ test(`${build}: a same-URL replacement document releases the paid lock through ${via}`, async t => {
+ const f = automaticSolveFixture(t);
+ await f.agent._executeToolImpl(1, 'solve_captcha', { type: 'hcaptcha' });
+ f.page.frameContext.documentTimeOrigin = 3000;
+ f.widget.documentTimeOrigin = 3000;
+ if (via === 'tree read') {
+ const observed = await f.agent._observeCaptchaChallenge(1, 'get_accessibility_tree',
+ { pageUrl: f.pageUrl, pageContent: 'dialog "Security verification"' }, { filter: 'visible' });
+ assert.equal(observed.gate.status, 'solve_required');
+ } else if (via === 'solve preflight') {
+ await f.agent._captchaMutationPreflight(1, 'solve_captcha', { type: 'hcaptcha' });
+ assert.equal(f.agent._captchaGateBlockResult(1, 'solve_captcha', {}), null);
+ }
+ const result = await f.agent._executeToolImpl(1, 'solve_captcha', { type: 'hcaptcha' });
+ assert.equal(result.success, true, result.error);
+ assert.equal(f.requests.length, 2);
+ assert.equal(f.agent._captchaGateStates.get(1).rootDocument.timeOrigin, 3000);
+ assert.equal((await f.agent._executeToolImpl(1, 'solve_captcha', { type: 'hcaptcha' })).noDispatch, true);
+ assert.equal(f.requests.length, 2);
+ });
+ }
+ for (const scenario of ['same document', 'unknown document']) {
+ test(`${build}: ${scenario} retains the paid lock during same-URL recovery`, async t => {
+ const f = automaticSolveFixture(t);
+ await f.agent._executeToolImpl(1, 'solve_captcha', { type: 'hcaptcha' });
+ if (scenario === 'unknown document') f.page.frameContext.documentTimeOrigin = 0;
+ await f.agent._captchaMutationPreflight(1, 'solve_captcha', {});
+ assert.equal(f.agent._captchaGateBlockResult(1, 'solve_captcha', {}).denied, true);
+ assert.equal((await f.agent._executeToolImpl(1, 'solve_captcha', { type: 'hcaptcha' })).noDispatch, true);
+ assert.equal(f.requests.length, 1);
+ });
+ }
+ test(`${build}: a token-only answer cannot cross a reload but the new document can solve once`, async t => {
+ const f = automaticSolveFixture(t);
+ await f.agent._executeToolImpl(1, 'solve_captcha', { type: 'hcaptcha', inject: false });
+ f.page.frameContext.documentTimeOrigin = 3000;
+ const discovery = await f.agent._executeToolImpl(1, 'get_captcha_capabilities', {});
+ assert.equal(discovery.pendingNativeAnswer, undefined);
+ assert.equal(f.agent._hasUnappliedNativeCaptchaSolution(1), false);
+ assert.equal(f.agent._captchaGateStates.has(1), false);
+ const fresh = await f.agent._executeToolImpl(1, 'solve_captcha', { type: 'hcaptcha', inject: false });
+ assert.equal(fresh.success, true, fresh.error);
+ assert.equal(fresh.applicationRequired, true);
+ assert.equal(f.requests.length, 2);
+ assert.equal((await f.agent._executeToolImpl(1, 'solve_captcha', { type: 'hcaptcha', inject: false })).noDispatch, true);
+ });
+ test(`${build}: routing a token-only page within the same document cannot retire its paid lock`, async t => {
+ const f = automaticSolveFixture(t);
+ await f.agent._executeToolImpl(1, 'solve_captcha', { type: 'hcaptcha', inject: false });
+ const to = `${f.pageUrl}/verification`;
+ f.page.frameContext.frameUrl = to;
+ f.widget.frameUrl = to;
+ const discovery = await f.agent._executeToolImpl(1, 'get_captcha_capabilities', {});
+ assert.equal(discovery.pendingNativeAnswer, undefined);
+ assert.equal(f.agent._captchaGateStates.get(1).publicGate.solveAttempted, true);
+ const observation = await f.agent._observeCaptchaChallenge(1, 'get_accessibility_tree',
+ { pageUrl: to, pageContent: 'dialog "Security verification"' }, { filter: 'visible' });
+ assert.equal(observation.gate.status, 'manual_required');
+ assert.equal((await f.agent._executeToolImpl(1, 'solve_captcha', { type: 'hcaptcha' })).noDispatch, true);
+ assert.equal(f.requests.length, 1);
+ });
+ test(`${build}: the first automatic solve is remembered through the real tool batch`, async t => {
+ const f = automaticSolveFixture(t);
+ f.agent._persist = () => {};
+ f.agent._ensureGateSetting = async () => {};
+ f.agent._skipPermissionGate = true;
+ f.agent.executeTool = f.agent._executeToolImpl.bind(f.agent);
+ const messages = [];
+ await f.agent._executeToolBatch(1, [
+ { id: 'first-solve', function: { name: 'solve_captcha', arguments: '{"type":"hcaptcha"}' } },
+ ], messages, () => {}, { supportsVision: false }, '', new Set(['solve_captcha']), 1);
+ assert.equal(f.requests.length, 1);
+ assert.equal(f.agent._captchaGateStates.get(1).status, 'verification_pending');
+ assert.match(messages[0].content, /do not.*solve_captcha again/i);
+ const observed = await f.agent._observeCaptchaChallenge(1, 'get_accessibility_tree',
+ { pageUrl: f.pageUrl, pageContent: 'link "Home"', truncated: true }, { filter: 'interactive' });
+ assert.equal(observed.gate.status, 'manual_required');
+ assert.equal(observed.gate.activeChallengeAfterSolve, true);
+ assert.equal(f.agent._captchaGateBlockResult(1, 'solve_captcha', {}).denied, true);
+ // Once the user completes this exact widget, continuation is still allowed.
+ f.widget.activeChallengeFrame = false;
+ f.widget.activeChallengeFrameVisible = false;
+ f.widget.responseTokenPresent = true;
+ const completed = await f.agent._observeCaptchaChallenge(1, 'get_accessibility_tree',
+ { pageUrl: f.pageUrl, pageContent: 'link "Home"' }, { filter: 'visible' });
+ assert.equal(completed.gate.status, 'cleared');
+ assert.equal(f.agent._captchaGateBlockResult(1, 'click', {}), null);
+ });
+ for (const status of ['solve_required', 'verification_pending', 'manual_required']) {
+ test(`${build}: ${status} allows cancellation and partial reports without a solve`, async () => {
+ const agent = agentFor('act', 'full');
+ agent._captchaGateStates.set(1, { key: 'challenge', status, publicGate: { status } });
+ agent._detectChallengeDialogBeforeMutation = async () => { throw new Error('Non-success completion must not inspect CAPTCHA'); };
+ for (const outcome of ['failed', 'partial']) {
+ assert.equal(await agent._captchaMutationPreflight(1, 'done', { outcome }), null);
+ assert.equal(agent._captchaGateBlockResult(1, 'done', { outcome }), null);
+ }
+ if (status !== 'manual_required') {
+ assert.equal(agent._captchaGateBlockResult(1, 'done', { outcome: 'success' }).denied, true);
+ assert.equal(agent._captchaGateBlockResult(1, 'done_json', { outcome: 'failed' }).denied, true);
+ }
+ assert.equal(agent._captchaGateBlockResult(1, 'click', {}).denied, true);
+ });
+ }
+ test(`${build}: cancelling with an unsolved CAPTCHA ends the batch before another solve`, async () => {
+ const agent = agentFor('act', 'full');
+ agent._persist = () => {};
+ agent._ensureGateSetting = async () => {};
+ agent._skipPermissionGate = true;
+ agent._captchaGateStates.set(1, { key: 'challenge', status: 'solve_required', publicGate: { status: 'solve_required' } });
+ const executed = [];
+ agent.executeTool = async (tabId, name, args) => {
+ executed.push(name);
+ return { success: false, done: true, outcome: args.outcome, summary: args.summary };
+ };
+ const summary = 'Cancelled at your request.';
+ const result = await agent._executeToolBatch(1, [
+ { id: 'cancel', function: { name: 'done', arguments: JSON.stringify({ outcome: 'failed', summary }) } },
+ { id: 'never-solve', function: { name: 'solve_captcha', arguments: '{}' } },
+ ], [], () => {}, { supportsVision: false }, '', new Set(['done', 'solve_captcha']), 1);
+ assert.equal(result.action, 'return');
+ assert.equal(result.value, summary);
+ assert.deepEqual(executed, ['done']);
+ });
+ for (const type of ['hcaptcha', 'recaptcha_v2', 'turnstile']) {
+ test(`${build}: manual ${type} completion can advance to a new page before a partial continuation read`, async t => {
+ const agent = agentFor('act', 'full');
+ agent.conversations.set(1, [{ role: 'system', content: 'test' }]);
+ const from = 'https://example.test/join';
+ const to = 'https://example.test/email-confirmation';
+ mockCaptchaPage(t, { url: to });
+ agent._activeCloudflareManagedChallengeGate = () => null;
+ agent._checkVerificationChallengeLoop = () => ({ kind: 'none' });
+ agent._currentUrl = async () => to;
+ // This is also the legacy persisted shape, before gates stored pageUrl.
+ agent._captchaGateStates.set(1, { key: `${from}\nsecurity verification`, status: 'manual_required',
+ captchaCandidateIdentity: { frameId: 0, framePathIndexes: [], type, websiteKey: 'site', responseFieldIndex: 0 },
+ publicGate: { status: 'manual_required', solveFailed: true } });
+ const result = { pageUrl: to, pageContent: 'link "Home"', truncated: true, hasMore: true };
+ const observed = await agent._observeCaptchaChallenge(1, 'get_accessibility_tree', result,
+ { filter: 'interactive', maxDepth: 10, maxChars: 3500 });
+ assert.equal(observed.gate?.status, 'cleared');
+ assert.equal(observed.gate?.clearedByNavigation, true);
+ assert.equal(agent._captchaGateStates.has(1), false);
+ assert.equal(agent._captchaGateBlockResult(1, 'click_ax', {}), null);
+ assert.equal(agent._conversationStorageEntry(1).captchaGateState, null);
+ assert.match(agent._captchaRoutingMessage(1, observed.gate), /navigat/i);
+ assert.doesNotMatch(agent._captchaRoutingMessage(1, observed.gate), /unrecognized challenge/);
+ });
+ }
+ for (const scenario of ['same page', 'query only', 'unverified URL', 'URL read failed']) {
+ test(`${build}: manual CAPTCHA gate survives ${scenario} without token evidence`, async () => {
+ const agent = agentFor('act', 'full');
+ const from = 'https://example.test/join';
+ const to = scenario === 'same page' ? from : scenario === 'query only' ? `${from}?step=2` : 'https://example.test/next';
+ agent._activeCloudflareManagedChallengeGate = () => null;
+ agent._checkVerificationChallengeLoop = () => ({ kind: 'none' });
+ agent._currentUrl = async () => {
+ if (scenario === 'URL read failed') throw new Error('Tab unavailable');
+ return scenario === 'unverified URL' ? from : to;
+ };
+ agent._captchaGateStates.set(1, { key: `${from}\nchallenge`, status: 'manual_required',
+ captchaCandidateIdentity: { frameId: 0, framePathIndexes: [], type: 'hcaptcha', websiteKey: 'site', responseFieldIndex: 0 },
+ publicGate: { status: 'manual_required', solveFailed: true } });
+ const observed = await agent._observeCaptchaChallenge(1, 'get_accessibility_tree',
+ { pageUrl: to, pageContent: 'heading "Verify Your Email"' }, { filter: 'interactive', maxDepth: 10 });
+ assert.equal(observed.gate?.status, 'manual_required');
+ assert.equal(agent._captchaGateBlockResult(1, 'click', {}).denied, true);
+ });
+ }
+ test(`${build}: a replaced document with a new challenge gets a fresh CAPTCHA gate`, async t => {
+ const agent = agentFor('act', 'full');
+ const to = 'https://example.test/new-challenge';
+ mockCaptchaPage(t, { url: to });
+ agent._activeCloudflareManagedChallengeGate = () => null;
+ agent._checkVerificationChallengeLoop = () => ({ kind: 'none' });
+ agent._currentUrl = async () => to;
+ agent._captchaGateStates.set(1, { key: 'https://example.test/old\nchallenge', status: 'manual_required',
+ rootDocument: { url: 'https://example.test/old', timeOrigin: 1000 },
+ publicGate: { status: 'manual_required', solveFailed: true } });
+ const observed = await agent._observeCaptchaChallenge(1, 'get_accessibility_tree',
+ { pageUrl: to, pageContent: 'dialog "Security verification"' }, { filter: 'visible' });
+ assert.equal(observed.gate?.status, 'manual_required');
+ assert.equal(observed.gate?.solveFailed, undefined, 'the old failed solve must not be attributed to the new page');
+ assert.equal(agent._captchaGateStates.get(1).pageUrl, to);
+ assert.equal(agent._captchaGateBlockResult(1, 'click', {}).denied, true);
+ });
+ test(`${build}: continuation batch leaves a stale manual gate and gives the model a fresh turn`, async t => {
+ const agent = agentFor('act', 'full');
+ const to = 'https://example.test/email-confirmation';
+ mockCaptchaPage(t, { url: to });
+ agent._persist = () => {};
+ agent._ensureGateSetting = async () => {};
+ agent._skipPermissionGate = true;
+ agent._currentUrl = async () => to;
+ agent._captchaGateStates.set(1, { key: 'https://example.test/join\nsecurity verification', status: 'manual_required',
+ captchaCandidateIdentity: { frameId: 0, type: 'hcaptcha', websiteKey: 'site', responseFieldIndex: 0 },
+ publicGate: { status: 'manual_required', solveFailed: true } });
+ const executed = [];
+ agent.executeTool = async (tabId, name) => {
+ executed.push(name);
+ return { pageUrl: to, pageContent: 'link "Home"', truncated: true, hasMore: true };
+ };
+ const messages = [];
+ const result = await agent._executeToolBatch(1, [
+ { id: 'read-current', function: { name: 'get_accessibility_tree', arguments: JSON.stringify({ filter: 'interactive', maxDepth: 10, maxChars: 3500 }) } },
+ { id: 'stale-click', function: { name: 'click', arguments: '{}' } },
+ ], messages, () => {}, { supportsVision: false }, '', new Set(['get_accessibility_tree', 'click']), 1);
+ assert.deepEqual(result, { action: 'continue' });
+ assert.deepEqual(executed, ['get_accessibility_tree']);
+ assert.equal(agent._captchaGateStates.has(1), false);
+ assert.match(messages.find(m => m.tool_call_id === 'stale-click')?.content || '', /fresh verification turn/);
+ });
+ test(`${build}: a confirmed replacement document may solve a new instance of the same widget`, async t => {
+ const agent = agentFor('act', 'full');
+ const from = 'https://example.test/join';
+ const to = 'https://example.test/new-challenge';
+ const widget = { type: 'hcaptcha', websiteKey: '5bd005a4-6ac8-4a86-8e60-53083832ed22',
+ visible: true, dialogAssociated: true, activeChallengeFrame: true, activeChallengeFrameVisible: true,
+ framePathIndexes: [], responseFieldId: 'h-captcha-response', responseFieldIndex: 0 };
+ mockCaptchaPage(t, { url: to, timeOrigin: 2000, candidates: [widget] });
+ agent._captchaGateStates.set(1, { key: `${from}\nchallenge`, pageUrl: from, status: 'manual_required',
+ rootDocument: { url: from, timeOrigin: 1000 }, captchaCandidateIdentity: { ...widget, frameId: 0 },
+ publicGate: { status: 'manual_required', solveFailed: true } });
+ const observed = await agent._observeCaptchaChallenge(1, 'get_accessibility_tree',
+ { pageUrl: to, pageContent: 'dialog "Security verification"' }, { filter: 'visible' });
+ assert.equal(observed.gate.status, 'solve_required');
+ assert.equal(observed.gate.solveFailed, undefined);
+ assert.deepEqual(agent._captchaGateStates.get(1).rootDocument, { url: to, timeOrigin: 2000 });
+ assert.equal(agent._captchaGateBlockResult(1, 'solve_captcha', {}), null);
+ });
+ for (const legacy of [false, true]) for (const partial of [false, true]) {
+ test(`${build}: same-document route changes preserve ${legacy ? 'legacy' : 'current'} failed solves on ${partial ? 'partial' : 'dialog'} reads`, async t => {
+ const agent = agentFor('act', 'full');
+ const from = 'https://example.test/join';
+ const to = 'https://example.test/join/verification';
+ const widget = { type: 'hcaptcha', websiteKey: '5bd005a4-6ac8-4a86-8e60-53083832ed22',
+ visible: true, dialogAssociated: true, activeChallengeFrame: true, activeChallengeFrameVisible: true,
+ framePathIndexes: [], responseFieldId: 'h-captcha-response', responseFieldIndex: 0 };
+ mockCaptchaPage(t, { url: to, timeOrigin: 1000, candidates: [widget] });
+ agent._captchaGateStates.set(1, { key: `${from}\nsecurity verification`, pageUrl: from, status: 'manual_required',
+ ...(!legacy ? { rootDocument: { url: from, timeOrigin: 1000 } } : {}),
+ captchaCandidateIdentity: { ...widget, frameId: 0 },
+ publicGate: { status: 'manual_required', solveFailed: true } });
+ const observed = await agent._observeCaptchaChallenge(1, 'get_accessibility_tree',
+ { pageUrl: to, pageContent: partial ? 'link "Home"' : 'dialog "Security verification"', truncated: partial },
+ { filter: partial ? 'interactive' : 'visible', maxDepth: 10 });
+ assert.equal(observed.gate.status, 'manual_required');
+ assert.equal(observed.gate.solveFailed, true);
+ assert.equal(agent._captchaGateStates.get(1).pageUrl, from);
+ assert.equal(agent._captchaGateBlockResult(1, 'solve_captcha', {}).denied, true);
+ });
+ }
+ for (const scenario of ['missing child', 'navigation failed']) {
+ test(`${build}: ${scenario} cannot prove a legacy widget disappeared after a route change`, async t => {
+ const agent = agentFor('act', 'full');
+ const to = 'https://example.test/next';
+ mockCaptchaPage(t, { url: to, missingChild: scenario === 'missing child', navigationFails: scenario === 'navigation failed' });
+ agent._captchaGateStates.set(1, { key: 'https://example.test/join\nchallenge', status: 'manual_required',
+ captchaCandidateIdentity: { frameId: 0, type: 'hcaptcha', websiteKey: 'site', responseFieldIndex: 0 },
+ publicGate: { status: 'manual_required', solveFailed: true } });
+ const observed = await agent._observeCaptchaChallenge(1, 'get_accessibility_tree',
+ { pageUrl: to, pageContent: 'link "Home"', truncated: true }, { filter: 'interactive' });
+ assert.equal(observed.gate.status, 'manual_required');
+ assert.equal(agent._captchaGateBlockResult(1, 'solve_captcha', {}).denied, true);
+ });
+ }
+ test(`${build}: a native gate key is not mistaken for a departed page URL`, async () => {
+ const agent = agentFor('act', 'full');
+ const pageUrl = 'https://example.test/challenge';
+ agent._activeCloudflareManagedChallengeGate = () => null;
+ agent._checkVerificationChallengeLoop = () => ({ kind: 'none' });
+ agent._currentUrl = async () => pageUrl;
+ agent._captchaGateStates.set(1, { key: `native:${pageUrl}`, status: 'verification_pending',
+ publicGate: { status: 'verification_pending', solveAttempted: true, nativeAnswerPending: true } });
+ agent._nativeCaptchaSolutions = new Map([[1, { pageUrl, solution: { token: 'paid-answer' }, applied: false }]]);
+ const observed = await agent._observeCaptchaChallenge(1, 'get_accessibility_tree',
+ { pageUrl, pageContent: 'heading "Challenge"', truncated: true }, { filter: 'interactive' });
+ assert.equal(observed.gate?.status, 'verification_pending');
+ assert.equal(agent._hasUnappliedNativeCaptchaSolution(1), true);
+ assert.equal(agent._captchaGateBlockResult(1, 'click', {}).denied, true);
+ });
for (const mode of ['ask', 'act', 'dev']) for (const tier of ['compact', 'mid', 'full']) {
test(`${build}: CAPTCHA tools, prompts and runtime gates agree in ${mode}/${tier}`, () => {
const available = mode !== 'ask' && tier !== 'compact';
diff --git a/test/run.js b/test/run.js
index 8b518d1fe..e1a77c726 100644
--- a/test/run.js
+++ b/test/run.js
@@ -122285,6 +122285,7 @@ async function withCaptchaFakePage(build, nodes, callback) {
URL,
URLSearchParams,
navigator: globalThis.navigator,
+ performance: globalThis.performance,
innerWidth: 1280,
innerHeight: 720,
getComputedStyle: globalThis.getComputedStyle,
@@ -122383,6 +122384,8 @@ test('CAPTCHA providers: real Turnstile detection reaches the 2Captcha request w
};
try {
const agent = new AgentClass({});
+ agent.conversations.set(1, [{ role: 'system', content: 'test' }]);
+ api.storage.session = { set: async () => {} };
const result = await agent._executeToolImpl(1, 'solve_captcha', { inject: false, metadata: { chlPageData: 'observed-page-data' } });
assert.equal(result.success, true, `${build}: ${result.error}`);
assert.equal(result.provider, '2captcha', build);
@@ -122425,6 +122428,8 @@ test('CAPTCHA providers: observed hCaptcha rqdata reaches fallback and returns t
};
try {
const agent = new AgentClass({});
+ agent.conversations.set(1, [{ role: 'system', content: 'test' }]);
+ api.storage.session = { set: async () => {} };
const flagConflict = await agent._executeToolImpl(1, 'solve_captcha', { inject: false, isEnterprise: false });
assert.equal(flagConflict.dispatched, false, build);
assert.match(flagConflict.error, /isEnterprise=.*conflicts/, build);
@@ -122469,6 +122474,8 @@ test('NoneCap hCaptcha token is not injected when its User-Agent differs from th
token: 'paid-token', user_agent: `${globalThis.navigator?.userAgent || ''}-mismatch` });
try {
const agent = new AgentClass({});
+ agent.conversations.set(1, [{ role: 'system', content: 'test' }]);
+ api.storage.session = { set: async () => {} };
const result = await agent._executeToolImpl(1, 'solve_captcha', {});
assert.equal(result.success, false, build);
assert.equal(result.dispatched, true, build);
@@ -122518,6 +122525,8 @@ test('hCaptcha dispatch and NoneCap validation use the selected frame User-Agent
};
try {
const agent = new AgentClass({});
+ agent.conversations.set(1, [{ role: 'system', content: 'test' }]);
+ api.storage.session = { set: async () => {} };
const result = await agent._executeToolImpl(1, 'solve_captcha', {});
assert.equal(result.dispatched, true, build);
assert.equal(result.injected, false, build);
@@ -122537,9 +122546,16 @@ test('CAPTCHA providers: explicit rqdata selects NoneCap Enterprise when frame d
api.storage = { local: { get: async () => ({
nonecapEnabled: true, nonecapApiKey: 'nc_live_' + 'a'.repeat(32),
}) } };
- api.tabs = { ...api.tabs, get: async () => ({ url: 'https://example.test/form' }),
- ...(build === 'firefox' ? { executeScript: async () => { throw new Error('frame detection unavailable'); } } : {}) };
- if (build === 'chrome') api.scripting.executeScript = async () => { throw new Error('frame detection unavailable'); };
+ const rootDocument = { url: 'https://example.test/form', timeOrigin: 1000 };
+ api.tabs = { ...api.tabs, get: async () => ({ url: rootDocument.url }),
+ ...(build === 'firefox' ? { executeScript: async (_id, { code }) => {
+ if (code.startsWith('(() => ({ url: location.href')) return [rootDocument];
+ throw new Error('frame detection unavailable');
+ } } : {}) };
+ if (build === 'chrome') api.scripting.executeScript = async ({ func }) => {
+ if (func.name === 'read') return [{ frameId: 0, result: rootDocument }];
+ throw new Error('frame detection unavailable');
+ };
const originalFetch = globalThis.fetch;
const calls = [];
globalThis.fetch = async (_url, options) => {
@@ -122548,6 +122564,8 @@ test('CAPTCHA providers: explicit rqdata selects NoneCap Enterprise when frame d
};
try {
const agent = new AgentClass({});
+ agent.conversations.set(1, [{ role: 'system', content: 'test' }]);
+ api.storage.session = { set: async () => {} };
const args = { type: 'hcaptcha', websiteKey: 'f5ab1c2d-7e8f-4a9b-b1c2-d3e4f5a6b7c8', rqdata: 'observed-rqdata', inject: false };
const conflict = await agent._executeToolImpl(1, 'solve_captcha', { ...args, isEnterprise: false });
assert.equal(conflict.dispatched, false, build);