Skip to content

Open-source AI browser agent for Chrome and Firefox (monorepo) đź§ 

fix(captcha): align provider contracts and recover interrupted signup

Codex release-state test9d22f9409755
diff --git a/docs/captcha-method-reference.md b/docs/captcha-method-reference.md
index f8d70447c..60653a628 100644
--- a/docs/captcha-method-reference.md
+++ b/docs/captcha-method-reference.md
@@ -1,6 +1,6 @@
# CAPTCHA native method reference
-Companion to [CAPTCHA provider coverage](captcha-provider-coverage.md). Audited 2026-09-29. Generated from the executable catalog; 197 method variants across seven providers. Method IDs select an adapter contract, not an arbitrary upstream task type. Fixed values are added automatically. Fields use dot paths for nested objects; pass nested JSON, not literal dotted keys.
+Companion to [CAPTCHA provider coverage](captcha-provider-coverage.md). Contracts rechecked 2026-10-01. Generated from the executable catalog; 198 method variants across seven providers. Method IDs select an adapter contract, not an arbitrary upstream task type. Fixed values are added automatically. Fields use dot paths for nested objects; pass nested JSON, not literal dotted keys.
Required fields below are unconditional. GeeTest v3 additionally needs `gt` and a fresh `challenge`; v4 needs its provider-specific CAPTCHA ID. AWS WAF variants, proxy authentication, alternate image inputs, and VisionEngine module-specific fields have conditional requirements described in the guide and official documentation. Every submitted value must come from the selected challenge.
@@ -472,7 +472,7 @@ Family: `funcaptcha_recognition`. [Official contract](https://2captcha.com/api-d
Family: `geetest`. [Official contract](https://2captcha.com/api-docs/geetest).
- Required: `websiteURL` (string).
-- Optional: `gt` (string), `challenge` (string), `geetestApiServerSubdomain` (string), `userAgent` (string), `version` (integer), `initParameters` (object), `risk_type` (string).
+- Optional: `gt` (string), `challenge` (string), `geetestApiServerSubdomain` (string), `userAgent` (string), `version` (integer), `initParameters` (object), `riskType` (string).
- Fixed wire values: `{"type":"GeeTestTaskProxyless"}`.
### GeeTestTask
@@ -480,7 +480,7 @@ Family: `geetest`. [Official contract](https://2captcha.com/api-docs/geetest).
Family: `geetest`. [Official contract](https://2captcha.com/api-docs/geetest).
- Required: `websiteURL` (string), `proxyType` (string), `proxyAddress` (string), `proxyPort` (integer).
-- Optional: `gt` (string), `challenge` (string), `geetestApiServerSubdomain` (string), `userAgent` (string), `version` (integer), `initParameters` (object), `risk_type` (string), `proxyLogin` (string), `proxyPassword` (string).
+- Optional: `gt` (string), `challenge` (string), `geetestApiServerSubdomain` (string), `userAgent` (string), `version` (integer), `initParameters` (object), `riskType` (string), `proxyLogin` (string), `proxyPassword` (string).
- Fixed wire values: `{"type":"GeeTestTask"}`.
### GridTask
@@ -805,6 +805,8 @@ Family: `aws_waf`. [Official contract](https://docs.capmonster.cloud/docs/captch
- Optional: `cookieSolution` (boolean), `proxyType` (string), `proxyAddress` (string), `proxyPort` (integer), `proxyLogin` (string), `proxyPassword` (string).
- Fixed wire values: `{"type":"AmazonTask"}`.
+`context` and `iv` must be supplied as empty strings in this invisible-challenge mode (CapMonster Option 3).
+
### BinanceTask
Family: `binance`. [Official contract](https://docs.capmonster.cloud/docs/captchas/binance/).
@@ -1281,7 +1283,7 @@ Family: `recaptcha_v3_enterprise`. [Official contract](https://solvecaptcha.com/
- Optional: `domain` (string), `action` (string), `min_score` (number), `proxy` (string), `proxytype` (string), `cookies` (string), `userAgent` (string).
- Fixed wire values: `{"method":"userrecaptcha","version":"v3","enterprise":1}`.
-## anti-captcha (23 variants)
+## anti-captcha (24 variants)
### AltchaTask
@@ -1317,6 +1319,14 @@ Family: `aws_waf`. [Official contract](https://anti-captcha.com/apidoc/task-type
- Optional: `captchaScript` (string), `challengeScript` (string).
- Fixed wire values: `{"type":"AmazonTaskProxyless"}`.
+### AmazonTaskProxyless:widget
+
+Family: `aws_waf`. [Official contract — select Widget](https://anti-captcha.com/apidoc/task-types/AmazonTaskProxyless).
+
+- Required: `websiteURL` (string), `websiteKey` (string), `jsapiScript` (string).
+- Fixed wire values: `{"type":"AmazonTaskProxyless","wafType":"widget"}`.
+- `websiteKey` is the observed `AwsWafCaptcha.renderCaptcha` API key; `jsapiScript` is the observed SDK URL. It is not the interstitial `gokuProps.key`.
+
### AntiGateTask
Family: `antigate`. [Official contract](https://anti-captcha.com/apidoc/task-types/AntiGateTask).
diff --git a/docs/captcha-provider-coverage.md b/docs/captcha-provider-coverage.md
index 59339f710..891714707 100644
--- a/docs/captcha-provider-coverage.md
+++ b/docs/captcha-provider-coverage.md
@@ -1,8 +1,8 @@
# CAPTCHA providers: setup, coverage, fallback, and API contracts
-Audited against first-party documentation on **2026-09-29**. Chrome and Firefox share the provider catalog, request validation, transports, and result handling; their browser execution adapters remain platform-specific.
+Initial catalog audit: **2026-09-29**. Integration contracts rechecked against first-party documentation on **2026-10-01**. Chrome and Firefox share the provider catalog, request validation, transports, and result handling; their browser execution adapters remain platform-specific.
-This integration exposes **seven providers and 197 documented method variants**. A method variant can be a proxy/proxyless route, an Enterprise option, a recognition model, or a separate response mode. It is not a claim that there are 197 CAPTCHA products.
+This integration exposes **seven providers and 198 catalog method variants**. A method variant can be a proxy/proxyless route, an Enterprise option, a recognition model, or a separate response mode. It is not a claim that there are 198 CAPTCHA products.
“Integrated” means WebBrain can validate the method's input, submit its documented request, poll when needed, and preserve its answer. It does **not** mean every website exposes the required parameters, that a token is accepted, or that authenticated live success rates have been measured. This implementation was checked with provider-contract fixtures and browser tests; no paid live solves were performed.
@@ -11,6 +11,7 @@ This integration exposes **seven providers and 197 documented method variants**.
- [Setup and consent](#setup-and-consent)
- [Coverage by provider](#coverage-by-provider)
- [hCaptcha](#hcaptcha)
+- [Integration contract audit](#integration-contract-audit--2026-10-01)
- [Fallback and charging](#fallback-and-charging)
- [Automatic widgets and native methods](#automatic-widgets-and-native-methods)
- [Applying answers](#applying-answers)
@@ -58,21 +59,37 @@ All families below have a callable native route. The [complete method reference]
CapMonster's ten ComplexImage models are `bills_audio`, `shein`, `bls`, `baidu`, `betpunch_3x3_rotate`, `oocl_rotate_double_new`, `oocl_rotate_new`, `dli_ensemble`, `mathsum`, and `portugal_text_find_icon`. Their `metadata.Task` values and recognition class are assigned by the adapter. The DLI, MathSum, and BLS methods send `dli`, `MathSum`, and `bls_3x3` respectively; audio sends `PayloadType: "Audio"`. CapSolver VisionEngine accepts the provider's documented module field, including slider, rotation, BotDeflector, Shein, and GIF OCR modes. Modules requiring a second image must receive it.
-Public request examples sometimes disagree with their property tables. The catalog uses documented task names and the working request-example names for 2Captcha's `TemuImageTask` and `VKCaptchaImageTask`; it preserves `BinanceTaskproxyless` casing. CapSolver GeeTest uses the task-table/SDK spelling `GeeTestTaskProxyLess`. These contracts need a real account/site trial before any measured acceptance claim.
+Public request examples sometimes disagree with their property tables. The catalog uses documented task names and the request-example names for 2Captcha's `TemuImageTask` and `VKCaptchaImageTask`; it preserves `BinanceTaskproxyless` casing. CapSolver GeeTest uses the task-table/SDK spelling `GeeTestTaskProxyLess`. These contracts need a real account/site trial before any measured acceptance claim.
## hCaptcha
**NopeCHA and NoneCap provide this integration's hCaptcha routes.** The original five providers are not advertised as hCaptcha solvers and are skipped for automatic hCaptcha fallback.
-This is grounded in their current public catalogs, not a claim that every private or historical endpoint is unavailable. In particular:
+Support is based on the linked catalogs and retained integration evidence; an absent catalog entry alone does not prove a historical endpoint is unavailable. In particular:
- The current [2Captcha API catalog](https://2captcha.com/api-docs) omits hCaptcha. Its [sandbox guide](https://2captcha.com/h/how-to-use-sandbox-mode) mentions hCaptcha for manually solving your own submissions; that does not establish production worker availability.
- CapMonster's source repository contains an hCaptcha document marked `draft: true`; the published catalog does not expose it. Draft/withdrawn methods are not enabled by this integration.
-- NopeCHA's current `/v1/token/hcaptcha` route and its separate `/v1/recognition/hcaptcha` route are different products. Recognition returns puzzle answers, not a completed token.
+- NopeCHA's retained `/v1/token/hcaptcha` and `/v1/recognition/hcaptcha` routes are separate products. Recognition returns puzzle answers, not a completed token. The public reference fetched on 2026-10-01 omits hCaptcha; the token route is retained because the supplied September 30 trace contains a successful provider answer. That trace proves an answer was returned, not current availability or target-site acceptance.
- NoneCap's `hcaptcha_enterprise` type accepts optional `rqdata`; include it whenever the site supplies it. Observed `data-rqdata` marks an automatically detected widget as Enterprise. Caller-supplied User-Agent is not sent because its API documents that input as ignored/deprecated. The returned `resp_key` and `user_agent` are retained.
Automatic detection still validates the hCaptcha UUID site key and observed `rqdata`. An explicit value that conflicts with the selected widget fails before dispatch. Enabling a compatible provider can re-evaluate a previously unsupported gate; a failed paid solve does not authorize another one.
+## Integration contract audit — 2026-10-01
+
+The seven adapters were checked against official request, authentication, polling, and response documentation. Regression fixtures cover dispatch and fallback without contacting paid services; local Chromium and Firefox fixtures cover application. This is not a live acceptance benchmark of every catalog method.
+
+| Provider | Contract checked and resulting correction |
+| --- | --- |
+| [CapSolver](https://docs.capsolver.com/en/guide/captcha/cloudflare_turnstile/) | Standalone Turnstile accepts `action`/`cdata`, not Challenge `chlPageData`. Such requests skip its automatic adapter and retain the complete data for compatible providers. Unknown poll statuses fail promptly; missing balances are errors. The separate native Cloudflare Challenge route remains available. |
+| [2Captcha](https://2captcha.com/api-docs/geetest) | GeeTest uses `riskType`, not `risk_type`. Requests and same-challenge comparisons now use the documented spelling. |
+| [CapMonster](https://docs.capmonster.cloud/docs/captchas/amazon-task/) | Added automatic AWS SDK and invisible-challenge modes. Native voucher answers remain usable; cookie mode rejects missing/empty cookies. Incomplete Cloudflare Challenge metadata is never downgraded to an ordinary Turnstile request. |
+| [SolveCaptcha](https://solvecaptcha.com/captcha-solver-api) | `res.php` accepts the documented Temu/VK `status: ready` / `solution` result as well as legacy numeric `status` / `request`. Structured recognition answers remain intact. The VK request table and example disagree; the adapter continues to follow the established form API/table, without claiming a live VK trial. |
+| [Anti-Captcha](https://anti-captcha.com/apidoc/task-types/AmazonTaskProxyless) | The documentation's **Widget** tab defines `wafType: widget`, `websiteKey` (the SDK API key), and `jsapiScript`. This cookie-returning path now participates in AWS SDK fallback. The gokuProps mode remains separate. |
+| [NopeCHA](https://nopecha.com/api-reference/) | Rechecked Basic-key authorization, v1 job IDs, polling and incomplete-job responses. Existing transport regressions cover them. The hCaptcha documentation discrepancy is recorded above; no new endpoint was guessed. |
+| [NoneCap](https://nonecap.com/api-reference/) | Rechecked Bearer authorization, solve states, token, response key and returned User-Agent. Required identity checks now also apply to stored/native answers, so manual bindings cannot bypass them. |
+
+NoneCap and [CapMonster reCAPTCHA v3](https://docs.capmonster.cloud/docs/captchas/recaptcha-v3-task/) explicitly require the returned User-Agent. Automatic and native application check it before writing fields, cookies or invoking callbacks. A mismatched answer is retained, including after worker restart, and requires manual completion; WebBrain does not silently change the browser identity or purchase another answer. Matching answers proceed normally. Other providers' optional User-Agent metadata remains available in their structured results and AWS diagnostics.
+
## Fallback and charging
1. Re-read enabled settings and validate keys.
@@ -94,7 +111,7 @@ After manual completion navigates to another page, the next accessibility read c
### Automatic route
-AWS WAF is also routed automatically from a visible challenge. The runtime observes initial `gokuProps` inputs or SDK/resource inputs for [CapSolver's secondary-verification contract](https://docs.capsolver.com/en/guide/captcha/awsWaf/), including the observed SDK API key and existing AWS token. Initial cookie tasks can use CapSolver, CapMonster, and Anti-Captcha; secondary SDK tasks currently use CapSolver. Enabling a recognition or voucher-returning service does not make it an applicable cookie fallback. `solve_captcha` applies the returned cookie unless `inject:false` was requested, then requires a reload and fresh inspection. A returned answer or successful cookie write alone is not clearance.
+AWS WAF is also routed automatically from a visible challenge. The runtime observes initial `gokuProps` inputs or SDK/resource inputs for [CapSolver's secondary-verification contract](https://docs.capsolver.com/en/guide/captcha/awsWaf/), including the observed SDK API key and existing AWS token. Initial cookie tasks can use CapSolver, CapMonster, and Anti-Captcha. SDK widget tasks now use CapMonster Option 1 and Anti-Captcha's Widget mode as well as CapSolver secondary verification when an existing token is available (otherwise its documented script-only mode). All use the observed SDK API key and script URL; stale interstitial inputs are excluded. Invisible challenge-only pages also support CapMonster Option 3, with its documented empty `iv` and `context`. Enabling a recognition or voucher-returning service does not make it an applicable cookie fallback. `solve_captcha` applies the returned cookie unless `inject:false` was requested, then requires a reload and fresh inspection. A returned answer or successful cookie write alone is not clearance.
Confirmed clearance permits a later challenge, including another family on the same page. A successful form submission after verified widget clearance can re-arm a newly visible challenge. Mere URL changes, incomplete reads, or an unchanged visible challenge do not unlock another paid attempt. Complete AWS disappearance also permits continuation after manual completion.
@@ -147,7 +164,7 @@ Use observed page parameters to prepare fallback tasks. Method IDs are WebBrain
}
```
-AWS WAF pages keep their inputs out of the page text: `key`, `iv`, and `context` sit in the `window.gokuProps` global, and the challenge script loads from an `awswaf.com` host. When `get_captcha_capabilities` is called without a provider or method on such a page, it reads those values from the top frame and returns `observedChallenge`. That object includes one ready task per enabled CapSolver, CapMonster Cloud, or Anti-Captcha provider, plus the `aws-waf-token` cookie path for each provider's answer (`cookie`, `cookies.aws-waf-token`, and `token`). CapMonster tasks set `cookieSolution: true`. 2Captcha and SolveCaptcha are left out because they return a `captcha_voucher`/`existing_token` pair that WebBrain can't turn into the cookie, so a win by either would be charged and unusable. If an input is missing, the result names it and nothing is guessed. After `apply_captcha_solution` sets the cookie, reload the page and read it again. A site can still reject a proxyless token.
+AWS WAF pages keep their inputs out of the page text: `key`, `iv`, and `context` sit in the `window.gokuProps` global, and the challenge script loads from an `awswaf.com` host. When `get_captcha_capabilities` is called without a provider or method on such a page, it reads those values from the top frame and returns `observedChallenge`. That object includes one ready task per enabled CapSolver, CapMonster Cloud, or Anti-Captcha provider, plus the `aws-waf-token` cookie path for each provider's answer (`cookie`, `cookies.aws-waf-token`, and `token`). Automatic CapMonster tasks set `cookieSolution: true`. Explicit native tasks may instead request the default voucher answer; that valid response is retained without falling through to another paid provider. 2Captcha and SolveCaptcha are left out because they return a `captcha_voucher`/`existing_token` pair that WebBrain can't turn into the cookie, so a win by either would be charged and unusable. If an input is missing, the result names it and nothing is guessed. After `apply_captcha_solution` sets the cookie, reload the page and read it again. A site can still reject a proxyless token.
Saved weights determine execution order, regardless of array order. Supply a task for each enabled provider that can solve that family and for which the required inputs are available. The tool does not invent another provider's parameters. Page URLs must belong to the active tab or an observed frame. Native methods do not automatically scrape every site's internal configuration.
@@ -236,7 +253,7 @@ The CAPTCHA gate permits `done` with `outcome: "failed"` or `"partial"` in every
Both browser trees contain:
- `src/agent/captcha-provider-config.js`: key formats, consent, default weights, automatic and native coverage.
-- `src/agent/captcha-catalog.js`: the 197 method contracts and primary documentation links.
+- `src/agent/captcha-catalog.js`: the 198 method contracts and primary documentation links.
- `src/agent/captcha-native-providers.js`: discovery, preflight, fixed-value mapping, native fallback, and structured results.
- `src/agent/captcha-hcaptcha-providers.js`: NopeCHA/NoneCap v1 transports and automatic hCaptcha mapping.
- `src/agent/captcha-solver.js`, `captcha-additional-providers.js`, `two-captcha.js`, `captcha-json-api.js`: automatic routes and shared request/poll lifecycles.
diff --git a/package.json b/package.json
index 607862e51..a5a07fc3b 100644
--- a/package.json
+++ b/package.json
@@ -5,7 +5,7 @@
"private": true,
"type": "module",
"scripts": {
- "test": "npm run test:cms && npm run test:markdown && npm run test:systemone && npm run test:systemone:fast && node --test test/browser-dialogs.mjs test/capsolver-cloud-broker.mjs test/captcha-providers.mjs test/captcha-weighted-fallback.mjs test/captcha-hcaptcha-providers.mjs test/captcha-native-providers.mjs test/captcha-runtime-policy.mjs test/captcha-callback-bridge.mjs test/captcha-aws-recovery.mjs test/trace-full-export.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 test/captcha-aws-recovery.mjs test/captcha-documented-contracts.mjs test/huggingface-signup-recovery.mjs test/trace-full-export.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",
diff --git a/src/chrome/src/agent/adapters.js b/src/chrome/src/agent/adapters.js
index b04ca685d..8270e6568 100644
--- a/src/chrome/src/agent/adapters.js
+++ b/src/chrome/src/agent/adapters.js
@@ -15904,6 +15904,10 @@ const ADAPTERS = [
category: 'general',
matches: (url) => /^https?:\/\/(?:www\.)?huggingface\.co(?:[/?#]|$)/i.test(url),
notes: `
+- Signup at /join follows the observed credentials, profile, and email-verification stages. CAPTCHA challenges are conditional; never assume one from a person's name, country, IP, or geography, and never trigger solving or reload on a challenge-free path.
+- Only when an actual CAPTCHA interrupts signup, follow the runtime CAPTCHA gate. A solved widget or applied AWS cookie is not account-creation evidence. Reload only when the runtime explicitly requests it, then inspect the current root form before choosing the next action.
+- If the runtime signup checkpoint reports a reset, resume the visible stage with the original user-provided values and fresh refs. Preserve populated fields; restore only missing requested profile details and the original avatar, reusing its saved download/attachment handle when available. If the form survived, continue it without restarting.
+- Before repeating Create Account after an interruption, reconcile signed-in state, verification-pending notices, and already-registered messages. Continue verification or sign-in for the same account when established; stop if creation remains uncertain. Never create another identity or blindly replay a submission. Verify account creation, email verification, profile saving, and any requested access-token creation each from its own observed success evidence.
- Repository upload routes expose two file inputs. Use \`input[type="file"]:not([accept])\` for repository files; \`input[type="file"][accept*="image"]\` belongs to the extended-description editor and does not stage a repository file.
- When the repository input already exists, call \`upload_file\` directly; do not click "Upload file(s)" or the drop zone first.
- A filename chip, generated commit summary, and enabled "Commit changes" button mean the file is staged only. Click "Commit changes", wait, and verify the file under "Files and versions" before reporting upload success.
diff --git a/src/chrome/src/agent/agent.js b/src/chrome/src/agent/agent.js
index 60305e5cb..cc24e5779 100644
--- a/src/chrome/src/agent/agent.js
+++ b/src/chrome/src/agent/agent.js
@@ -83,10 +83,11 @@ import { buildTerminalRuntimeEvent, enqueueCloudRuntimeEvent, flushCloudRuntimeO
import { buildShareGenerationItem, enqueueShareGeneration, flushShareOutbox, purgeShareGenerations } from '../trace/webbrain-share-outbox.js';
import { normalizeRuntimeTraceConfig } from '../trace/runtime-config.js';
import { tracesToMarkdown } from './trace-export.js';
+import { advanceHuggingFaceSignupRecovery, normalizeHuggingFaceSignupRecovery, huggingFaceSignupRecoveryNote } from './huggingface-signup-recovery.js';
import { hcaptchaParamError } from './captcha-hcaptcha-providers.js';
-import { AWS_WAF_COOKIE_PATHS, describeAwsWafObservation, getCaptchaCapabilities, prepareNativeCaptchaTasks, solveNativeCaptchaTasks } from './captcha-native-providers.js';
-import { applyNativeCaptchaSolution, captureCaptchaDocuments, captchaAnswerDocumentStatus } from './captcha-solution-application.js';
-import { solveCaptchaWithProviders, detectCaptcha, injectToken, readCaptchaFrameUserAgent, captchaParamError, captchaTypesMatch, captchaWebsiteUrl } from './captcha-solver.js';
+import { AWS_WAF_COOKIE_PATHS, awsWafTaskRoute, describeAwsWafObservation, getCaptchaCapabilities, prepareNativeCaptchaTasks, solveNativeCaptchaTasks } from './captcha-native-providers.js';
+import { applyNativeCaptchaSolution, captureCaptchaDocuments, captchaAnswerDocumentStatus, requiresCaptchaUserAgent } from './captcha-solution-application.js';
+import { solveCaptchaWithProviders, detectCaptcha, injectToken, readCaptchaFrameUserAgent, captchaParamError, captchaAutomaticDispatchError, captchaTypesMatch, captchaWebsiteUrl } from './captcha-solver.js';
import { CAPTCHA_SETTINGS_KEYS, getCaptchaProviders, captchaProviderSupportsType } from './captcha-provider-config.js';
import { captchaChallengeKey, captchaChallengeMatcherOptions, detectChallengeDialog, detectChallengeDialogInPage } from './captcha-gate.js';
import { applyCaptchaFrameVisibility, observeAwsWafChallengeInPage } from './captcha-frame-runtime.js';
@@ -1087,6 +1088,7 @@ export class Agent extends LoopDetector {
// be consumed by read-only preflight checks.
this.autoScreenshotBursts = new Map();
this.lastSeenAdapter = new Map(); // tabId -> adapter name from last enrichment
+ this._huggingFaceSignupRecoveries = new Map(); // tabId -> task-bound, value-free signup checkpoint
this.pendingAdapterMatchTraces = new Map(); // tabId -> Map(adapter@revision -> content-free match metadata)
this.adapterMatchTraceKeys = new Map(); // runId -> Map(adapter@revision -> OR-merged match metadata)
// Per-tab opt-in: when true, the agent is allowed to use API mutations
@@ -9902,6 +9904,26 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
return metadata;
}
+ async _observeHuggingFaceSignupRecovery(tabId, name, args, result, gate, submitted = false) {
+ if (!this.useSiteAdapters) {
+ this._huggingFaceSignupRecoveries.delete(tabId);
+ return '';
+ }
+ const url = await this._currentUrl(tabId);
+ if (!url) return ''; // A failed read cannot prove a reset or a route change.
+ const task = this._activeTaskBinding(this.conversations.get(tabId) || []);
+ const taskKey = this._progressTaskKeyForText(task.requestText || task.text);
+ const state = advanceHuggingFaceSignupRecovery(this._huggingFaceSignupRecoveries.get(tabId), {
+ url, taskKey, name, args, result, gate, submitted,
+ });
+ if (!state) {
+ this._huggingFaceSignupRecoveries.delete(tabId);
+ return '';
+ }
+ this._huggingFaceSignupRecoveries.set(tabId, state);
+ return huggingFaceSignupRecoveryNote(state);
+ }
+
/**
* After the first turn, the user may navigate or open a new site that has
* a different adapter than the one used at conversation start. Detect that
@@ -12209,6 +12231,11 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
? null
: this._captchaGateBlockResult(tabId, fnName, fnArgs);
if (captchaGateBlock) {
+ // This path returns before normal tool observation. Retain the signup
+ // checkpoint even when the first detected challenge needs manual help.
+ const signupRecoveryNote = await this._observeHuggingFaceSignupRecovery(
+ tabId, fnName, fnArgs, captchaGateBlock, this._captchaGateStates.get(tabId)?.publicGate,
+ );
onUpdate('tool_call', { name: fnName, args: fnArgs, outcomeUnknown: false });
onUpdate('tool_result', { name: fnName, result: captchaGateBlock });
messages.push({
@@ -12219,7 +12246,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
? '\n[TRUSTED CAPTCHA GATE: Stop automation and ask the user to complete the verification manually. Do not dismiss, close, or resubmit it.]'
: captchaGateBlock.captchaVerificationRequired
? '\n[TRUSTED CAPTCHA GATE: Read the root accessibility tree to verify whether the one solved challenge cleared. Do not submit, dismiss, or call solve_captcha again.]'
- : '\n[TRUSTED CAPTCHA GATE: Call solve_captcha once now. Do not dismiss or close the verification dialog and do not click Continue/Submit.]'),
+ : '\n[TRUSTED CAPTCHA GATE: Call solve_captcha once now. Do not dismiss or close the verification dialog and do not click Continue/Submit.]') + signupRecoveryNote,
});
const runId = this.currentRunId.get(tabId);
if (runId) {
@@ -13394,6 +13421,10 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
: { gate: null, loopCheck: { kind: 'none' } };
const captchaGateDecision = captchaObservation.gate;
const challengeLoopCheck = captchaObservation.loopCheck;
+ const signupRecoveryNote = await this._observeHuggingFaceSignupRecovery(
+ tabId, fnName, fnArgs, toolResult, captchaGateDecision || captchaSolveOutcome,
+ detectedSubmitAction?.isSubmit === true,
+ );
if (captchaGateDecision) {
onUpdate('captcha_gate', captchaGateDecision);
}
@@ -13681,6 +13712,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
});
}
resultContent += this._captchaRoutingMessage(tabId, captchaGateDecision, captchaSolveOutcome, toolResult, onUpdate);
+ resultContent += signupRecoveryNote;
if (nytimesPageGateFallback) {
resultContent += `\n${nytimesPageGateFallback.note}`;
onUpdate('warning', {
@@ -16683,6 +16715,8 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
const reconciledLedger = reconcilePersistedLedgerRows(entry.progressLedger);
this.progressLedgers.set(tabId, reconciledLedger.rows);
}
+ const signupRecovery = normalizeHuggingFaceSignupRecovery(entry.huggingFaceSignupRecovery);
+ if (signupRecovery) this._huggingFaceSignupRecoveries.set(tabId, signupRecovery);
if (entry.progressSession && typeof entry.progressSession === 'object') {
this.progressSessions.set(tabId, entry.progressSession);
}
@@ -16852,6 +16886,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
submittedRunRequestId: this.submittedRunRequestIds.get(tabId) || null,
progressLedger: this.progressLedgers.get(tabId) || [],
progressSession: this.progressSessions.get(tabId) || null,
+ huggingFaceSignupRecovery: normalizeHuggingFaceSignupRecovery(this._huggingFaceSignupRecoveries.get(tabId)),
selectionGroundingScope: this.selectionGroundingScopes.get(tabId) || null,
selectionGroundingRestorationPending: this.selectionGroundingRestorationPendingTabs.has(tabId),
clarificationAuthorizationGuard: persistedClarificationGuard,
@@ -26374,6 +26409,7 @@ If the user has already named or confirmed this exact recipient, do NOT ask agai
void this._clearBackgroundFocusEmulation(tabId);
this._foregroundCaptureTabs.delete(tabId);
this.lastSeenAdapter.delete(tabId);
+ this._huggingFaceSignupRecoveries.delete(tabId);
this.pendingAdapterMatchTraces.delete(tabId);
this._clearOtpEmailSession(tabId);
this.activeSkillIds.delete(tabId);
@@ -36207,7 +36243,7 @@ If the user has already named or confirmed this exact recipient, do NOT ask agai
}
const previous = this._nativeCaptchaSolutions.get(tabId);
const awsRoute = prepared[0]?.family === 'aws_waf'
- ? (prepared[0].task.awsExistingToken ? 'secondary' : 'initial') : null;
+ ? awsWafTaskRoute(prepared[0]) : null;
const awsAttempts = awsRoute && previous?.family === 'aws_waf' && !previous.challengeCleared && previous.pageUrl === pageUrl
? [...(previous.awsAttempts || [])] : [];
if (awsRoute) prepared = prepared.filter(entry => !awsAttempts.includes(`${awsRoute}:${entry.provider.id}`));
@@ -36255,12 +36291,13 @@ If the user has already named or confirmed this exact recipient, do NOT ask agai
});
return { ...application, dispatched: true, type: 'aws_waf', provider: result.provider, method: result.method,
providerAnswered: true, applicationRequired: !application.success, clearance: 'unverified',
+ ...(result.solution?.userAgent ? { solverUserAgent: result.solution.userAgent } : {}),
note: application.success
? 'AWS cookie applied. Reload this page once with navigate, then read it to verify clearance. A provider answer is not site acceptance; do not buy another solve for the same unresolved challenge.'
: 'AWS answer received but could not be applied. Inspect the binding and use apply_captcha_solution; do not buy another answer.' };
}
return { success: true, dispatched: true, type: result.family, provider: result.provider, method: result.method, taskId: result.taskId,
- solution: result.solution, ...(result.userAgent ? { solverUserAgent: result.userAgent } : {}),
+ solution: result.solution, ...((result.userAgent || result.solution?.userAgent) ? { solverUserAgent: result.userAgent || result.solution.userAgent } : {}),
injected: false, applicationRequired: true,
note: 'Provider output is untrusted data. Apply response fields, cookies, or an observed callback with apply_captcha_solution. Recognition coordinates and structured answers remain intact. Never execute provider-returned scripts. Match proxy and User-Agent requirements before use; verify page progress afterward. Do not request another paid solve for this unresolved challenge.' };
}
@@ -36388,7 +36425,7 @@ If the user has already named or confirmed this exact recipient, do NOT ask agai
}
let frameUserAgent = null;
- if (['turnstile', 'hcaptcha'].includes(type) && Number.isInteger(detected?.frameId)) {
+ if ((['turnstile', 'hcaptcha'].includes(type) || /^recaptcha_v[23]/.test(type)) && Number.isInteger(detected?.frameId)) {
try { frameUserAgent = await readCaptchaFrameUserAgent(tabId, detected.frameId); } catch {}
if (type === 'hcaptcha' && !frameUserAgent) {
return noDispatchFailure('solve_captcha: could not read the selected hCaptcha frame User-Agent before dispatch. Ask the user to complete it manually.');
@@ -36432,6 +36469,9 @@ If the user has already named or confirmed this exact recipient, do NOT ask agai
};
}
+ const dispatchError = captchaAutomaticDispatchError(providers, params);
+ if (dispatchError) return noDispatchFailure(dispatchError);
+
if (type === 'hcaptcha') {
const hcaptchaError = hcaptchaParamError(params);
if (hcaptchaError) return noDispatchFailure(hcaptchaError);
@@ -36459,7 +36499,7 @@ If the user has already named or confirmed this exact recipient, do NOT ask agai
if (currentRoot && !previousAnswer?.challengeCleared && 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) {
+ if (!wantInject || providers.some(provider => requiresCaptchaUserAgent(provider.id, type))) {
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);
@@ -36513,12 +36553,13 @@ If the user has already named or confirmed this exact recipient, do NOT ask agai
this._captchaSolveGateAfterTool(tabId, 'solve_captcha', { success: true, applicationRequired: true });
await this._persistNow(tabId);
}
- if (wantInject && result.provider === 'nonecap' && result.solution?.userAgent
+ if (wantInject && requiresCaptchaUserAgent(result.provider, type) && result.solution?.userAgent
&& result.solution.userAgent !== params.userAgent) {
return { success: false, dispatched: true, manualCompletionRequired: true,
provider: result.provider, taskId: result.taskId, injected: false,
solverUserAgent: result.solution.userAgent,
- error: 'NoneCap solved this hCaptcha with a different User-Agent. The token was not injected; ask the user to complete the challenge manually.' };
+ token: result.token, solution: result.solution,
+ error: `${result.provider} returned a different User-Agent that its API requires. The paid answer was retained without injection; complete the challenge manually and do not request another solve.` };
}
// For non-image types, push the token into the page response field
@@ -36551,6 +36592,12 @@ If the user has already named or confirmed this exact recipient, do NOT ask agai
}
}
+ if (automaticAnswer && injection?.success) {
+ automaticAnswer.applied = true;
+ automaticAnswer.applicationSucceeded = true;
+ await this._persistNow(tabId);
+ }
+ const pendingAutomaticAnswer = automaticAnswer && !automaticAnswer.applied;
return {
success: true,
dispatched: true,
@@ -36566,9 +36613,9 @@ 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 } : {}),
+ ...(pendingAutomaticAnswer ? { applicationRequired: true } : {}),
injection,
- note: automaticAnswer
+ note: pendingAutomaticAnswer
? '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
@@ -36578,7 +36625,7 @@ If the user has already named or confirmed this exact recipient, do NOT ask agai
: '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 } : {}),
+ ...(pendingAutomaticAnswer ? { solution: automaticAnswer.solution } : {}),
};
} catch (e) {
const error = `solve_captcha failed: ${e.message}`;
diff --git a/src/chrome/src/agent/captcha-additional-providers.js b/src/chrome/src/agent/captcha-additional-providers.js
index 2090c293b..099560a83 100644
--- a/src/chrome/src/agent/captcha-additional-providers.js
+++ b/src/chrome/src/agent/captcha-additional-providers.js
@@ -18,9 +18,10 @@ export function buildAdditionalCaptchaTask(id, task) {
if (id !== 'capmonster') throw new Error(`Unknown CAPTCHA provider: ${id}`);
if (task.type === 'AntiTurnstileTaskProxyLess') {
const { action, pagedata, ...rest } = mapped;
- // Challenge (token) mode requires pageAction, data, userAgent and pageData
- // together. Without all of them, send the plain Turnstile task instead.
+ // A Challenge page is not an ordinary standalone Turnstile widget. Never
+ // discard its pageData to make an incomplete paid request look valid.
const challenge = pagedata && action && mapped.data && task.userAgent;
+ if (pagedata && !challenge) throw new Error('CapMonster Cloud: Challenge token mode requires action, data, pageData and the browser User-Agent.');
return { ...rest, type: 'TurnstileTask', ...(action ? { pageAction: action } : {}),
...(task.userAgent ? { userAgent: task.userAgent } : {}),
...(challenge ? { pageData: pagedata, cloudflareTaskType: 'token' } : {}) };
@@ -56,7 +57,14 @@ export async function solveCaptchaRequest(apiKey, path, fields, timeout = 30_000
method: isGet ? 'GET' : 'POST', ...(isGet ? {} : { body }), signal: AbortSignal.timeout(timeout),
});
if (!response.ok) throw new Error(`SolveCaptcha ${path}: HTTP ${response.status}`);
- const result = await response.json().catch(() => null);
+ let result = await response.json().catch(() => null);
+ // The Temu/VK reference also documents structured ready/solution responses
+ // on res.php. Keep those answers intact alongside the legacy status/request
+ // envelope used by the other methods.
+ if (path === 'res.php' && fields.action === 'get' && result?.errorId === 0 && result.status === 'ready'
+ && result.solution != null) {
+ result = { ...result, status: 1, request: result.solution };
+ }
if (!result || ![0, 1].includes(Number(result.status))) throw new Error(`SolveCaptcha ${path}: invalid response`);
if (Number(result.status) !== 1 && result.request !== 'CAPCHA_NOT_READY') throw new Error(`SolveCaptcha ${path}: ${result.request || 'unknown error'}`);
return result;
diff --git a/src/chrome/src/agent/captcha-catalog.js b/src/chrome/src/agent/captcha-catalog.js
index 0c0766e1c..10a9d4f0e 100644
--- a/src/chrome/src/agent/captcha-catalog.js
+++ b/src/chrome/src/agent/captcha-catalog.js
@@ -34,8 +34,8 @@ export const CAPTCHA_CATALOG = [
{"provider":"2captcha","method":"FriendlyCaptchaTaskProxyless","family":"friendly","fields":{"websiteURL":{"type":"string","required":true},"websiteKey":{"type":"string","required":true},"version":{"type":"string","required":false},"moduleScript":{"type":"string","required":false},"nomoduleScript":{"type":"string","required":false}},"fixed":{"type":"FriendlyCaptchaTaskProxyless"},"docs":"https://2captcha.com/api-docs/friendly-captcha"},
{"provider":"2captcha","method":"FriendlyCaptchaTask","family":"friendly","fields":{"websiteURL":{"type":"string","required":true},"websiteKey":{"type":"string","required":true},"version":{"type":"string","required":false},"moduleScript":{"type":"string","required":false},"nomoduleScript":{"type":"string","required":false},"proxyType":{"type":"string","required":true},"proxyAddress":{"type":"string","required":true},"proxyPort":{"type":"integer","required":true},"proxyLogin":{"type":"string","required":false},"proxyPassword":{"type":"string","required":false}},"fixed":{"type":"FriendlyCaptchaTask"},"docs":"https://2captcha.com/api-docs/friendly-captcha"},
{"provider":"2captcha","method":"GridTask:funcaptcha_recognition","family":"funcaptcha_recognition","fields":{"body":{"type":"string","required":true},"rows":{"type":"number","required":false},"columns":{"type":"number","required":false},"comment":{"type":"string","required":false},"imgInstructions":{"type":"string","required":false},"minClicks":{"type":"number","required":false},"maxClicks":{"type":"number","required":false},"canNoAnswer":{"type":"number","required":false},"previousId":{"type":"string","required":false},"imgType":{"type":"string","required":false}},"fixed":{"type":"GridTask"},"docs":"https://2captcha.com/api-docs/funcaptcha-grid"},
- {"provider":"2captcha","method":"GeeTestTaskProxyless","family":"geetest","fields":{"websiteURL":{"type":"string","required":true},"gt":{"type":"string","required":false},"challenge":{"type":"string","required":false},"geetestApiServerSubdomain":{"type":"string","required":false},"userAgent":{"type":"string","required":false},"version":{"type":"integer","required":false},"initParameters":{"type":"object","required":false},"risk_type":{"type":"string","required":false}},"fixed":{"type":"GeeTestTaskProxyless"},"docs":"https://2captcha.com/api-docs/geetest"},
- {"provider":"2captcha","method":"GeeTestTask","family":"geetest","fields":{"websiteURL":{"type":"string","required":true},"gt":{"type":"string","required":false},"challenge":{"type":"string","required":false},"geetestApiServerSubdomain":{"type":"string","required":false},"userAgent":{"type":"string","required":false},"version":{"type":"integer","required":false},"initParameters":{"type":"object","required":false},"risk_type":{"type":"string","required":false},"proxyType":{"type":"string","required":true},"proxyAddress":{"type":"string","required":true},"proxyPort":{"type":"integer","required":true},"proxyLogin":{"type":"string","required":false},"proxyPassword":{"type":"string","required":false}},"fixed":{"type":"GeeTestTask"},"docs":"https://2captcha.com/api-docs/geetest"},
+ {"provider":"2captcha","method":"GeeTestTaskProxyless","family":"geetest","fields":{"websiteURL":{"type":"string","required":true},"gt":{"type":"string","required":false},"challenge":{"type":"string","required":false},"geetestApiServerSubdomain":{"type":"string","required":false},"userAgent":{"type":"string","required":false},"version":{"type":"integer","required":false},"initParameters":{"type":"object","required":false},"riskType":{"type":"string","required":false}},"fixed":{"type":"GeeTestTaskProxyless"},"docs":"https://2captcha.com/api-docs/geetest"},
+ {"provider":"2captcha","method":"GeeTestTask","family":"geetest","fields":{"websiteURL":{"type":"string","required":true},"gt":{"type":"string","required":false},"challenge":{"type":"string","required":false},"geetestApiServerSubdomain":{"type":"string","required":false},"userAgent":{"type":"string","required":false},"version":{"type":"integer","required":false},"initParameters":{"type":"object","required":false},"riskType":{"type":"string","required":false},"proxyType":{"type":"string","required":true},"proxyAddress":{"type":"string","required":true},"proxyPort":{"type":"integer","required":true},"proxyLogin":{"type":"string","required":false},"proxyPassword":{"type":"string","required":false}},"fixed":{"type":"GeeTestTask"},"docs":"https://2captcha.com/api-docs/geetest"},
{"provider":"2captcha","method":"GridTask","family":"grid","fields":{"body":{"type":"string","required":true},"rows":{"type":"integer","required":false},"columns":{"type":"integer","required":false},"comment":{"type":"string","required":false},"imgInstructions":{"type":"string","required":false},"previousId":{"type":"string","required":false},"imgType":{"type":"string","required":false},"minClicks":{"type":"integer","required":false},"maxClicks":{"type":"integer","required":false},"canNoAnswer":{"type":"integer","required":false}},"fixed":{"type":"GridTask"},"docs":"https://2captcha.com/api-docs/grid"},
{"provider":"2captcha","method":"HuntTask","family":"hunt","fields":{"websiteURL":{"type":"string","required":true},"apiGetLib":{"type":"string","required":true},"userAgent":{"type":"string","required":false},"data":{"type":"string","required":false},"proxyType":{"type":"string","required":true},"proxyAddress":{"type":"string","required":true},"proxyPort":{"type":"number","required":true},"proxyLogin":{"type":"string","required":false},"proxyPassword":{"type":"string","required":false}},"fixed":{"type":"HuntTask"},"docs":"https://2captcha.com/api-docs/hunt-captcha"},
{"provider":"2captcha","method":"IncapsulaTask","family":"imperva","fields":{"websiteURL":{"type":"string","required":true},"incapsulaScriptUrl":{"type":"string","required":true},"incapsulaCookies":{"type":"string","required":true},"userAgent":{"type":"string","required":false},"reese84UrlEndpoint":{"type":"string","required":false},"proxyType":{"type":"string","required":true},"proxyAddress":{"type":"string","required":true},"proxyPort":{"type":"number","required":true},"proxyLogin":{"type":"string","required":false},"proxyPassword":{"type":"string","required":false}},"fixed":{"type":"IncapsulaTask"},"docs":"https://2captcha.com/api-docs/imperva-incapsula"},
@@ -72,6 +72,7 @@ export const CAPTCHA_CATALOG = [
{"provider":"anti-captcha","method":"AltchaTaskProxyless","family":"altcha","fields":{"websiteURL":{"type":"string","required":true},"challengeURL":{"type":"string","required":false},"challengeJSON":{"type":"string","required":false}},"fixed":{"type":"AltchaTaskProxyless"},"docs":"https://anti-captcha.com/apidoc/task-types/AltchaTaskProxyless","requireOneOf":[["challengeURL","challengeJSON"]]},
{"provider":"anti-captcha","method":"AmazonTask","family":"aws_waf","fields":{"websiteURL":{"type":"string","required":true},"websiteKey":{"type":"string","required":true},"iv":{"type":"string","required":true},"context":{"type":"string","required":true},"captchaScript":{"type":"string","required":false},"challengeScript":{"type":"string","required":false},"proxyType":{"type":"string","required":true},"proxyAddress":{"type":"string","required":true},"proxyPort":{"type":"integer","required":true},"proxyLogin":{"type":"string","required":false},"proxyPassword":{"type":"string","required":false}},"fixed":{"type":"AmazonTask"},"docs":"https://anti-captcha.com/apidoc/task-types/AmazonTask"},
{"provider":"anti-captcha","method":"AmazonTaskProxyless","family":"aws_waf","fields":{"websiteURL":{"type":"string","required":true},"websiteKey":{"type":"string","required":true},"iv":{"type":"string","required":true},"context":{"type":"string","required":true},"captchaScript":{"type":"string","required":false},"challengeScript":{"type":"string","required":false}},"fixed":{"type":"AmazonTaskProxyless"},"docs":"https://anti-captcha.com/apidoc/task-types/AmazonTaskProxyless"},
+ {"provider":"anti-captcha","method":"AmazonTaskProxyless:widget","family":"aws_waf","fields":{"websiteURL":{"type":"string","required":true},"websiteKey":{"type":"string","required":true},"jsapiScript":{"type":"string","required":true}},"fixed":{"type":"AmazonTaskProxyless","wafType":"widget"},"docs":"https://anti-captcha.com/apidoc/task-types/AmazonTaskProxyless"},
{"provider":"anti-captcha","method":"AntiGateTask","family":"antigate","fields":{"websiteURL":{"type":"string","required":true},"templateName":{"type":"string","required":true},"variables":{"type":"object","required":true},"domainsOfInterest":{"type":"array","required":false},"proxyAddress":{"type":"string","required":true},"proxyPort":{"type":"integer","required":true},"proxyLogin":{"type":"string","required":false},"proxyPassword":{"type":"string","required":false}},"fixed":{"type":"AntiGateTask"},"docs":"https://anti-captcha.com/apidoc/task-types/AntiGateTask"},
{"provider":"anti-captcha","method":"FriendlyCaptchaTask","family":"friendly","fields":{"websiteURL":{"type":"string","required":true},"websiteKey":{"type":"string","required":true},"proxyType":{"type":"string","required":true},"proxyAddress":{"type":"string","required":true},"proxyPort":{"type":"integer","required":true},"proxyLogin":{"type":"string","required":false},"proxyPassword":{"type":"string","required":false}},"fixed":{"type":"FriendlyCaptchaTask"},"docs":"https://anti-captcha.com/apidoc/task-types/FriendlyCaptchaTask"},
{"provider":"anti-captcha","method":"FriendlyCaptchaTaskProxyless","family":"friendly","fields":{"websiteURL":{"type":"string","required":true},"websiteKey":{"type":"string","required":true}},"fixed":{"type":"FriendlyCaptchaTaskProxyless"},"docs":"https://anti-captcha.com/apidoc/task-types/FriendlyCaptchaTaskProxyless"},
@@ -121,7 +122,7 @@ export const CAPTCHA_CATALOG = [
{"provider":"capmonster","method":"CustomTask:altcha","family":"altcha","fields":{"websiteURL":{"type":"string","required":true},"websiteKey":{"type":"string","required":true},"metadata.challenge":{"type":"string","required":false},"metadata.iterations":{"type":"string","required":false},"metadata.salt":{"type":"string","required":false},"metadata.signature":{"type":"string","required":false},"userAgent":{"type":"string","required":false},"proxyType":{"type":"string","required":false},"proxyAddress":{"type":"string","required":false},"proxyPort":{"type":"integer","required":false},"proxyLogin":{"type":"string","required":false},"proxyPassword":{"type":"string","required":false},"metadata":{"type":"object","required":false}},"fixed":{"type":"CustomTask","class":"altcha"},"docs":"https://docs.capmonster.cloud/docs/captchas/altcha-task/"},
{"provider":"capmonster","method":"AmazonTask:1","family":"aws_waf","fields":{"websiteURL":{"type":"string","required":true},"websiteKey":{"type":"string","required":true},"captchaScript":{"type":"string","required":true},"cookieSolution":{"type":"boolean","required":false},"userAgent":{"type":"string","required":false},"proxyType":{"type":"string","required":false},"proxyAddress":{"type":"string","required":false},"proxyPort":{"type":"integer","required":false},"proxyLogin":{"type":"string","required":false},"proxyPassword":{"type":"string","required":false}},"fixed":{"type":"AmazonTask"},"docs":"https://docs.capmonster.cloud/docs/captchas/amazon-task/"},
{"provider":"capmonster","method":"AmazonTask:2","family":"aws_waf","fields":{"websiteURL":{"type":"string","required":true},"challengeScript":{"type":"string","required":true},"websiteKey":{"type":"string","required":true},"context":{"type":"string","required":true},"iv":{"type":"string","required":true},"captchaScript":{"type":"string","required":false},"cookieSolution":{"type":"boolean","required":false},"proxyType":{"type":"string","required":false},"proxyAddress":{"type":"string","required":false},"proxyPort":{"type":"integer","required":false},"proxyLogin":{"type":"string","required":false},"proxyPassword":{"type":"string","required":false}},"fixed":{"type":"AmazonTask"},"docs":"https://docs.capmonster.cloud/docs/captchas/amazon-task/"},
- {"provider":"capmonster","method":"AmazonTask:3","family":"aws_waf","fields":{"websiteURL":{"type":"string","required":true},"challengeScript":{"type":"string","required":true},"context":{"type":"string","required":true},"iv":{"type":"string","required":true},"cookieSolution":{"type":"boolean","required":false},"proxyType":{"type":"string","required":false},"proxyAddress":{"type":"string","required":false},"proxyPort":{"type":"integer","required":false},"proxyLogin":{"type":"string","required":false},"proxyPassword":{"type":"string","required":false}},"fixed":{"type":"AmazonTask"},"docs":"https://docs.capmonster.cloud/docs/captchas/amazon-task/"},
+ {"provider":"capmonster","method":"AmazonTask:3","family":"aws_waf","fields":{"websiteURL":{"type":"string","required":true},"challengeScript":{"type":"string","required":true},"context":{"type":"string","required":true,"allowEmpty":true},"iv":{"type":"string","required":true,"allowEmpty":true},"cookieSolution":{"type":"boolean","required":false},"proxyType":{"type":"string","required":false},"proxyAddress":{"type":"string","required":false},"proxyPort":{"type":"integer","required":false},"proxyLogin":{"type":"string","required":false},"proxyPassword":{"type":"string","required":false}},"fixed":{"type":"AmazonTask"},"docs":"https://docs.capmonster.cloud/docs/captchas/amazon-task/"},
{"provider":"capmonster","method":"BinanceTask","family":"binance","fields":{"websiteURL":{"type":"string","required":true},"websiteKey":{"type":"string","required":true},"validateId":{"type":"string","required":true},"userAgent":{"type":"string","required":false},"proxyType":{"type":"string","required":false},"proxyAddress":{"type":"string","required":false},"proxyPort":{"type":"integer","required":false},"proxyLogin":{"type":"string","required":false},"proxyPassword":{"type":"string","required":false}},"fixed":{"type":"BinanceTask"},"docs":"https://docs.capmonster.cloud/docs/captchas/binance/"},
{"provider":"capmonster","method":"ComplexImageTask:recognition:bills_audio","family":"complex_image","fields":{"imagesBase64":{"type":"array","required":true}},"fixed":{"type":"ComplexImageTask","class":"recognition","metadata.Task":"bills_audio","metadata.PayloadType":"Audio"},"docs":"https://docs.capmonster.cloud/docs/captchas/compleximage/bills_audio/"},
{"provider":"capmonster","method":"ComplexImageTask:recognition:shein","family":"complex_image","fields":{"imagesBase64":{"type":"array","required":true}},"fixed":{"type":"ComplexImageTask","class":"recognition","metadata.Task":"shein"},"docs":"https://docs.capmonster.cloud/docs/captchas/compleximage/shein/"},
diff --git a/src/chrome/src/agent/captcha-native-providers.js b/src/chrome/src/agent/captcha-native-providers.js
index 2191ec2fb..f0c1c80df 100644
--- a/src/chrome/src/agent/captcha-native-providers.js
+++ b/src/chrome/src/agent/captcha-native-providers.js
@@ -143,7 +143,7 @@ export function buildNativeCaptchaTask(entry) {
const value = at(task, path);
if (value === undefined) { if (field.required) throw new Error(`${entry.method}: ${path} is required.`); continue; }
if (!matches(value, field.type)) throw new Error(`${entry.method}: ${path} must be ${field.type}.`);
- if (field.required && value !== null && !usable(value)) throw new Error(`${entry.method}: ${path} cannot be empty.`);
+ if (field.required && value !== null && !usable(value) && !field.allowEmpty) throw new Error(`${entry.method}: ${path} cannot be empty.`);
}
for (const alternatives of contract.requireOneOf || []) {
if (!alternatives.some(path => usable(at(task, path)))) throw new Error(`${entry.method}: provide ${alternatives.join(' or ')}.`);
@@ -421,11 +421,26 @@ function validateFallbackIdentifiers(built) {
}
}
}
+ const awsWidget = family === 'aws_waf' && built.some(({ contract, task }) =>
+ contract.method === 'AmazonTask:1' || task.wafType === 'widget' || task.awsApiKey);
+ if (awsWidget && built.some(({ contract, task }) => !(contract.method === 'AmazonTask:1'
+ || task.wafType === 'widget' || (contract.provider === 'capsolver' && task.awsApiJs
+ && !['awsKey', 'awsIv', 'awsContext', 'awsChallengeJS', 'awsProblemUrl'].some(key => usable(task[key])))))) {
+ throw new Error('Fallback AWS tasks must reference the same observed challenge mode (widget or interstitial).');
+ }
const groups = [
{ aliases: ['websiteURL', 'pageurl', 'url'], requireAll: false },
{ aliases: ['websiteKey', 'sitekey', 'googlekey', 'websitePublicKey', 'publickey'], requireAll: false },
{ aliases: ['userAgent', 'useragent', 'user_agent'], requireAll: true },
- ...(FAMILY_IDENTIFIERS[family] || []).map(aliases => ({ aliases, requireAll: true })),
+ ...(awsWidget ? [
+ // For SDK widgets websiteKey means renderCaptcha's apiKey, while the
+ // interstitial mode uses gokuProps.key. Never equate those two values.
+ // CapSolver also documents a script-only mode without an API key.
+ { aliases: ['websiteKey', 'awsApiKey'], requireAll: false },
+ { aliases: ['captchaScript', 'jsapiScript', 'awsApiJs'], requireAll: true },
+ // Only CapSolver accepts the existing token for secondary verification.
+ { aliases: ['awsExistingToken'], requireAll: false },
+ ] : (FAMILY_IDENTIFIERS[family] || []).map(aliases => ({ aliases, requireAll: true }))),
];
if (family === 'geetest') {
const versions = built.map(({contract, task}) => task.version === 4 || task.captchaId
@@ -527,8 +542,15 @@ export async function solveNativeCaptchaTasks(prepared, { onAttempt } = {}) {
: provider.id === 'nonecap' ? await solveNonecapTask(provider.apiKey, task)
: await solveForm(provider.apiKey, contract, task);
if (!usable(result.solution)) throw new Error('No usable answer returned.');
- const cookiePath = family === 'aws_waf' && AWS_WAF_COOKIE_PATHS[provider.id];
- if (cookiePath) prepareCaptchaApplication(result.solution, { cookies: [{ name: 'aws-waf-token', path: cookiePath }] });
+ // CapMonster defaults to a voucher pair. Only cookieSolution:true asks
+ // for cookies; a valid native voucher must not trigger another charge.
+ const cookiePath = family === 'aws_waf' && (provider.id !== 'capmonster' || task.cookieSolution === true)
+ && AWS_WAF_COOKIE_PATHS[provider.id];
+ if (cookiePath) {
+ if (typeof at(result.solution, cookiePath) !== 'string') throw new Error('Missing AWS cookie answer.');
+ const application = prepareCaptchaApplication(result.solution, { cookies: [{ name: 'aws-waf-token', path: cookiePath }] });
+ if (!application.cookies[0].value.trim()) throw new Error('Empty AWS cookie answer.');
+ }
return { ...result, provider: provider.id, method: contract.method, family };
} catch (error) {
// Some providers echo inputs in errors. Never return a saved account key.
@@ -547,6 +569,10 @@ export async function solveNativeCaptchaTasks(prepared, { onAttempt } = {}) {
// https://anti-captcha.com/apidoc/task-types/AmazonTaskProxyless
export const AWS_WAF_COOKIE_PATHS = { capsolver: 'cookie', capmonster: 'cookies.aws-waf-token', 'anti-captcha': 'token' };
+export function awsWafTaskRoute({ contract, task }) {
+ return contract.method === 'AmazonTask:1' || task.wafType === 'widget' || (task.awsApiJs && !task.awsKey) ? 'secondary' : 'initial';
+}
+
// Build one proxyless AWS WAF task per enabled cookie-returning provider from
// observed page values, so weighted fallback has an entry for each of them.
// Only values read from the page are used; a provider whose required inputs
@@ -558,20 +584,29 @@ export function buildAwsWafProviderTasks(providers, observed) {
if (!websiteURL) return [];
// Secondary verification uses the previous token and SDK inputs, not the
// first interstitial's (possibly still present) gokuProps.
- const secondary = apiKey && jsapiScript && existingToken;
+ const widget = apiKey && jsapiScript;
+ const secondary = widget && existingToken;
const initial = websiteKey && iv && context;
const capsolverParameters = secondary
? { websiteURL, awsApiKey: apiKey, awsApiJs: jsapiScript, awsExistingToken: existingToken }
- : initial ? { websiteURL, awsKey: websiteKey, awsIv: iv, awsContext: context,
+ : widget ? { websiteURL, awsApiJs: jsapiScript } : initial ? { websiteURL, awsKey: websiteKey, awsIv: iv, awsContext: context,
...(challengeScript ? { awsChallengeJS: challengeScript } : {}) }
: !websiteKey && !iv && !context ? (jsapiScript ? { websiteURL, awsApiJs: jsapiScript }
: challengeScript ? { websiteURL, awsChallengeJS: challengeScript }
: problemUrl ? { websiteURL, awsProblemUrl: problemUrl } : null) : null;
const builders = {
capsolver: () => capsolverParameters && ({ method: 'AntiAwsWafTaskProxyLess', parameters: capsolverParameters }),
- capmonster: () => !secondary && initial && challengeScript && ({ method: 'AmazonTask:2', parameters: { websiteURL, websiteKey, iv, context, challengeScript,
- cookieSolution: true } }),
- 'anti-captcha': () => !secondary && initial && ({ method: 'AmazonTaskProxyless', parameters: { websiteURL, websiteKey, iv, context,
+ capmonster: () => widget ? { method: 'AmazonTask:1', parameters: {
+ websiteURL, websiteKey: apiKey, captchaScript: jsapiScript, cookieSolution: true,
+ } } : challengeScript && (initial
+ ? { method: 'AmazonTask:2', parameters: { websiteURL, websiteKey, iv, context, challengeScript, cookieSolution: true } }
+ // Documented invisible challenge mode requires empty iv/context. Do
+ // not erase partial gokuProps or select it when a CAPTCHA SDK is present.
+ : !websiteKey && !iv && !context && !jsapiScript && !observed.captchaScript
+ ? { method: 'AmazonTask:3', parameters: { websiteURL, challengeScript, iv: '', context: '', cookieSolution: true } } : null),
+ 'anti-captcha': () => widget ? { method: 'AmazonTaskProxyless:widget', parameters: {
+ websiteURL, websiteKey: apiKey, jsapiScript,
+ } } : initial && ({ method: 'AmazonTaskProxyless', parameters: { websiteURL, websiteKey, iv, context,
...(challengeScript ? { challengeScript } : {}) } }),
};
return providers.filter(provider => !provider.useCloudBroker && builders[provider.id])
@@ -594,7 +629,7 @@ export function describeAwsWafObservation(providers, observed) {
return { ...base, note: 'No enabled provider returns an applicable aws-waf-token cookie. Enable CapSolver, CapMonster Cloud, or Anti-Captcha (2Captcha and SolveCaptcha return a voucher WebBrain cannot apply), or ask for manual completion.' };
}
const cookiePathByProvider = Object.fromEntries(providerTasks.map(task => [task.provider, AWS_WAF_COOKIE_PATHS[task.provider]]));
- return { ...base, providerTasks, route: observed.apiKey && observed.jsapiScript && observed.existingToken ? 'secondary' : 'initial',
+ return { ...base, providerTasks, route: awsWafTaskRoute(buildNativeCaptchaTask(providerTasks[0])),
application: { frameId: 0, frameUrl: pageUrl, cookieName: 'aws-waf-token', cookiePathByProvider },
note: 'Call solve_captcha once with inject:false and these providerTasks unchanged; weighted fallback runs across them. Then call apply_captcha_solution with frameId 0, this frameUrl, and cookies:[{name:"aws-waf-token", path: cookiePathByProvider[result.provider]}]. Then navigate to pageUrl to reload and read the page. The token may be rejected if the site binds it to the solver IP; do not buy another solve for this challenge.' };
}
diff --git a/src/chrome/src/agent/captcha-solution-application.js b/src/chrome/src/agent/captcha-solution-application.js
index 60fff67d0..7ce881d4c 100644
--- a/src/chrome/src/agent/captcha-solution-application.js
+++ b/src/chrome/src/agent/captcha-solution-application.js
@@ -1,5 +1,13 @@
import { isEmptyCaptchaCallback } from './captcha-callback-binding.js';
+// These contracts explicitly require the returned browser identity. Other
+// providers can return a diagnostic UA without requiring an exact match.
+// https://nonecap.com/api-reference/
+// https://docs.capmonster.cloud/docs/captchas/recaptcha-v3-task/
+export function requiresCaptchaUserAgent(provider, family) {
+ return provider === 'nonecap' || (provider === 'capmonster' && /^recaptcha_v3(?:_enterprise)?$/.test(family));
+}
+
// Apply only values from a completed solve. Provider responses are untrusted
// data: never evaluate returned JavaScript or navigate to a returned URL.
function valueAt(solution, path = '') {
@@ -107,8 +115,12 @@ export async function captchaAnswerDocumentStatus(tabId, record, application, ap
}
// Self-contained for MAIN-world execution in one explicitly selected frame.
-export function applyCaptchaValuesInPage(expectedUrl, fields, callback, clicks = [], expectedTimeOrigin, validateOnly = false) {
+export function applyCaptchaValuesInPage(expectedUrl, fields, callback, clicks = [], expectedTimeOrigin, validateOnly = false, requiredUserAgent = null) {
if (location.href !== expectedUrl || performance.timeOrigin !== expectedTimeOrigin) return { success: false, error: 'CAPTCHA frame navigated before application.' };
+ if (requiredUserAgent && navigator.userAgent !== requiredUserAgent) return {
+ success: false, manualCompletionRequired: true, solverUserAgent: requiredUserAgent,
+ error: 'The provider requires its returned User-Agent, which differs from this browser. The paid answer was retained and no values were applied. Complete the challenge manually; do not request another solve.',
+ };
const targets = [];
for (const { selector, value } of fields) {
let matches;
@@ -176,7 +188,8 @@ export async function applyNativeCaptchaSolution(tabId, record, application, api
// Cookies are host-only and scoped to the active page. Returned Domain,
// URLs, SameSite overrides, scripts, and storage dumps are never applied.
const execute = async validateOnly => {
- const args = [application.frameUrl, fields, callback, clicks, documentIdentity.timeOrigin, validateOnly];
+ const requiredUserAgent = requiresCaptchaUserAgent(record.provider, record.family) ? record.solution?.userAgent : null;
+ const args = [application.frameUrl, fields, callback, clicks, documentIdentity.timeOrigin, validateOnly, requiredUserAgent];
if (typeof api.scripting?.executeScript === 'function') {
const results = await api.scripting.executeScript({ target: { tabId, frameIds: [application.frameId] }, world: 'MAIN', func: applyCaptchaValuesInPage, args });
return results?.find(r => r.frameId === application.frameId)?.result;
diff --git a/src/chrome/src/agent/captcha-solver.js b/src/chrome/src/agent/captcha-solver.js
index 0a99c87fd..bc5936f0b 100644
--- a/src/chrome/src/agent/captcha-solver.js
+++ b/src/chrome/src/agent/captcha-solver.js
@@ -20,7 +20,7 @@ import {
selectCaptchaCandidate,
} from './captcha-frame-runtime.js';
import { buildCaptchaDiagnostics, captchaChallengeMatcherOptions } from './captcha-gate.js';
-import { solveWithAdditionalProvider } from './captcha-additional-providers.js';
+import { buildAdditionalCaptchaTask, solveWithAdditionalProvider } from './captcha-additional-providers.js';
import { solveWithHcaptchaProvider } from './captcha-hcaptcha-providers.js';
import { solveWithTwoCaptcha } from './two-captcha.js';
import { captchaProviderSupportsType } from './captcha-provider-config.js';
@@ -62,7 +62,8 @@ export async function getBalance(apiKey) {
const res = await postJson('/getBalance', { clientKey: apiKey });
if (!res || typeof res !== 'object') throw new Error('CapSolver getBalance returned unexpected response.');
if (res.errorId) throw capsolverError('CapSolver', res);
- return { balance: res.balance ?? 0, packages: res.packages || [] };
+ if (res.balance == null || res.balance === '' || !Number.isFinite(Number(res.balance))) throw new Error('CapSolver getBalance: missing balance');
+ return { balance: Number(res.balance), packages: res.packages || [] };
}
async function createTask(apiKey, task) {
@@ -85,6 +86,7 @@ async function pollTaskResult(apiKey, taskId, { timeoutMs = POLL_TIMEOUT_MS } =
if (!res || typeof res !== 'object') throw new Error('CapSolver getTaskResult returned unexpected response.');
if (res.errorId) throw capsolverError('CapSolver getTaskResult', res);
if (res.status === 'ready') return res.solution || {};
+ if (!['idle', 'processing'].includes(res.status)) throw new Error('CapSolver getTaskResult returned an unexpected status.');
await new Promise(r => setTimeout(r, POLL_INTERVAL_MS));
}
throw new Error(`CapSolver: timed out after ${Math.round(timeoutMs / 1000)}s waiting for solution.`);
@@ -173,6 +175,26 @@ export function buildTask({ type, websiteURL, websiteKey, ...rest }) {
throw new Error(`solve_captcha: unsupported type "${type}".`);
}
+function capsolverTaskError(task) {
+ return task?.type === 'AntiTurnstileTaskProxyLess' && task.metadata?.chlPageData
+ ? 'CapSolver automatic Turnstile does not support Cloudflare Challenge pageData; use a compatible provider or the documented native Cloudflare Challenge task.' : null;
+}
+
+// Distinguish an entirely local schema rejection from a paid dispatch. The
+// agent calls this before persisting its attempted-solve lock.
+export function captchaAutomaticDispatchError(providers, params) {
+ const task = params.type === 'hcaptcha' ? null : buildTask(params);
+ const failures = [];
+ for (const provider of providers.filter(p => captchaProviderSupportsType(p.id, params.type))) {
+ try {
+ if (provider.id === 'capsolver' && capsolverTaskError(task)) throw new Error(capsolverTaskError(task));
+ if (provider.id === 'capmonster') buildAdditionalCaptchaTask(provider.id, task);
+ return null;
+ } catch (error) { failures.push(`${provider.id}: ${error.message}`); }
+ }
+ return failures.join(' | ') || `No enabled provider supports ${params.type}.`;
+}
+
// Pick the right token-field name + injection strategy for each captcha
// type. The DOM convention is well-documented for the ones we auto-handle.
function solutionFor(type, solution) {
@@ -218,6 +240,10 @@ export async function solveCaptcha(apiKey, params, { useCloudBroker = false } =
const paramError = captchaParamError(params);
if (paramError) throw new Error(paramError);
const task = buildTask(params);
+ // CapSolver's standalone Turnstile schema has action/cdata, but no
+ // chlPageData. Its Cloudflare Challenge API is a different, proxied task.
+ // Let a compatible provider receive the complete Challenge parameters.
+ if (capsolverTaskError(task)) throw new Error(capsolverTaskError(task));
// minScore belongs to the shared fallback input. CapSolver's current v3
// schema has no such parameter; requesting a score does not guarantee one.
delete task.minScore;
@@ -245,6 +271,8 @@ export async function solveCaptchaWithProviders(providers, params) {
if (paramError) throw new Error(paramError);
const eligibleProviders = providers.filter(provider => captchaProviderSupportsType(provider.id, params.type));
if (!eligibleProviders.length) throw new Error(`No enabled provider supports ${params.type}. Ask the user to complete it manually.`);
+ const dispatchError = captchaAutomaticDispatchError(eligibleProviders, params);
+ if (dispatchError) throw new Error(dispatchError);
const task = params.type === 'hcaptcha' ? null : buildTask(params);
const failures = [];
for (const provider of eligibleProviders) {
diff --git a/src/chrome/src/agent/huggingface-signup-recovery.js b/src/chrome/src/agent/huggingface-signup-recovery.js
new file mode 100644
index 000000000..4e543c795
--- /dev/null
+++ b/src/chrome/src/agent/huggingface-signup-recovery.js
@@ -0,0 +1,98 @@
+// Passive, task-bound signup progress. Never stores field values, credentials,
+// CAPTCHA answers or selectors, and never dispatches a browser action.
+const FIELDS = new Set(['email', 'password', 'username', 'fullname', 'twitter', 'github', 'linkedin', 'homepage', 'details']);
+const ACTIVE_GATES = new Set(['solve_required', 'manual_required', 'verification_pending']);
+const MAX_AGE_MS = 6 * 60 * 60 * 1000;
+
+export function huggingFaceSignupUrl(value) {
+ try {
+ const url = new URL(value);
+ return ['https:', 'http:'].includes(url.protocol) && !url.username && !url.password && !url.port
+ && ['huggingface.co', 'www.huggingface.co'].includes(url.hostname)
+ && /^\/join\/?$/.test(url.pathname) ? `${url.origin}/join` : '';
+ } catch { return ''; }
+}
+
+function avatarHandle(value) {
+ if (Number.isSafeInteger(value?.downloadId) && value.downloadId > 0) return { downloadId: value.downloadId };
+ if (typeof value?.attachmentId === 'string' && /^[\w:-]{1,120}$/.test(value.attachmentId)) return { attachmentId: value.attachmentId };
+ return null;
+}
+
+export function normalizeHuggingFaceSignupRecovery(value, now = Date.now()) {
+ if (!value || !huggingFaceSignupUrl(value.url) || typeof value.taskKey !== 'string'
+ || !value.taskKey || value.taskKey.length > 120 || !Number.isFinite(value.updatedAt)
+ || now - value.updatedAt > MAX_AGE_MS || value.updatedAt > now + 60_000) return null;
+ return {
+ url: huggingFaceSignupUrl(value.url), taskKey: value.taskKey, updatedAt: value.updatedAt,
+ stage: ['credentials', 'profile'].includes(value.stage) ? value.stage : 'unknown',
+ sawProfile: value.sawProfile === true,
+ fields: [...new Set((Array.isArray(value.fields) ? value.fields : []).filter(field => FIELDS.has(field)))],
+ avatar: avatarHandle(value.avatar),
+ interrupted: value.interrupted === true, challengeActive: value.challengeActive === true,
+ recovering: value.recovering === true, submitted: value.submitted === true,
+ };
+}
+
+function rootFormStage(name, args, result) {
+ // A scoped subtree or an unrelated tool's prose cannot prove a signup reset.
+ if (name !== 'get_accessibility_tree' || !['visible', 'interactive'].includes(args.filter || 'all')
+ || args.ref_id || Number(args.page || 1) !== 1
+ || args.frameId || args.framePath || args.selector || result?.success === false || result?.error) return '';
+ const text = typeof result?.pageContent === 'string' ? result.pageContent : '';
+ const field = name => new RegExp(`^\\s*textbox[^\\n]*field_name="${name}"`, 'm').test(text);
+ if (field('username') && field('fullname')) return 'profile';
+ if (field('email') && field('password')) return 'credentials';
+ return '';
+}
+
+export function advanceHuggingFaceSignupRecovery(previous, {
+ url, taskKey, name, args = {}, result = {}, gate = null, submitted = false, now = Date.now(),
+}) {
+ const signupUrl = huggingFaceSignupUrl(url);
+ if (!signupUrl || !taskKey) return null;
+ let state = normalizeHuggingFaceSignupRecovery(previous, now);
+ if (state?.url !== signupUrl || state?.taskKey !== taskKey) state = null;
+ const stage = rootFormStage(name, args, result);
+ if (!state && !stage) return null;
+ state ||= { url: signupUrl, taskKey, stage, sawProfile: false, fields: [], avatar: null,
+ interrupted: false, challengeActive: false, recovering: false, submitted: false };
+ state.updatedAt = now;
+ if (ACTIVE_GATES.has(gate?.status)) {
+ state.interrupted = true;
+ state.challengeActive = true;
+ } else if (gate?.status === 'cleared') {
+ state.challengeActive = false;
+ }
+ if (stage && !state.challengeActive) {
+ if (state.interrupted && state.sawProfile && stage === 'credentials') state.recovering = true;
+ state.stage = stage;
+ state.sawProfile ||= stage === 'profile';
+ }
+ if (!state.challengeActive && result?.success === true && result.dispatched !== false && !result.noDispatch) {
+ if (['set_field', 'type_ax'].includes(name) && result.verified === true && FIELDS.has(result.fieldMeta?.name)) {
+ state.fields = [...new Set([...state.fields, result.fieldMeta.name])];
+ }
+ if (name === 'upload_file' && state.stage === 'profile'
+ && ['input_attached', 'page_consumed'].includes(result.attachmentState)) {
+ state.avatar = avatarHandle(args) || state.avatar;
+ }
+ }
+ if (submitted && state.stage === 'profile' && result?.success === true
+ && result.dispatched !== false && !result.noDispatch) state.submitted = true;
+ return normalizeHuggingFaceSignupRecovery(state, now);
+}
+
+export function huggingFaceSignupRecoveryNote(value) {
+ const state = normalizeHuggingFaceSignupRecovery(value);
+ if (!state?.interrupted) return '';
+ const checkpoint = `Previously filled fields: ${state.fields.join(', ') || 'none recorded'}.`
+ + (state.avatar ? ` Previously attached avatar handle: ${JSON.stringify(state.avatar)}.` : '');
+ if (state.challengeActive) {
+ return `\n[HUGGING FACE SIGNUP RECOVERY: An observed CAPTCHA interrupted this signup. ${checkpoint} Follow the runtime CAPTCHA gate; do not refill, resubmit, or navigate while it blocks those actions. Only perform a recovery reload when the runtime explicitly requests it, then read the current root form. A cookie or solved challenge is not proof of account creation.]`;
+ }
+ if (!state.recovering) {
+ return '\n[HUGGING FACE SIGNUP RECOVERY: The CAPTCHA gate cleared. Inspect the current stage and continue the existing form or email-verification flow. Do not restart signup or reload merely because a challenge occurred; account creation still requires site evidence.]';
+ }
+ return `\n[HUGGING FACE SIGNUP RECOVERY: A fresh root form shows signup returned to the credentials step after a CAPTCHA interruption. ${checkpoint} Resume the visible stage using only values from the original user request; preserve fields already filled and use fresh refs. At the profile step, restore only missing requested details and reattach the original avatar only if absent (reuse the recorded handle if still available; otherwise use the user-provided source). ${state.submitted ? 'The earlier Create Account submission is unconfirmed. ' : ''}Before repeating Create Account, reconcile any signed-in, verification-pending, or already-registered evidence; continue verification/sign-in for the same account when established, and stop if the outcome remains uncertain. Never create a different account, blindly replay a submission, or buy another solve outside the runtime gate.]`;
+}
diff --git a/src/firefox/src/agent/adapters.js b/src/firefox/src/agent/adapters.js
index e8034ceb3..10efceb5a 100644
--- a/src/firefox/src/agent/adapters.js
+++ b/src/firefox/src/agent/adapters.js
@@ -15903,6 +15903,10 @@ const ADAPTERS = [
category: 'general',
matches: (url) => /^https?:\/\/(?:www\.)?huggingface\.co(?:[/?#]|$)/i.test(url),
notes: `
+- Signup at /join follows the observed credentials, profile, and email-verification stages. CAPTCHA challenges are conditional; never assume one from a person's name, country, IP, or geography, and never trigger solving or reload on a challenge-free path.
+- Only when an actual CAPTCHA interrupts signup, follow the runtime CAPTCHA gate. A solved widget or applied AWS cookie is not account-creation evidence. Reload only when the runtime explicitly requests it, then inspect the current root form before choosing the next action.
+- If the runtime signup checkpoint reports a reset, resume the visible stage with the original user-provided values and fresh refs. Preserve populated fields; restore only missing requested profile details and the original avatar, reusing its saved download/attachment handle when available. If the form survived, continue it without restarting.
+- Before repeating Create Account after an interruption, reconcile signed-in state, verification-pending notices, and already-registered messages. Continue verification or sign-in for the same account when established; stop if creation remains uncertain. Never create another identity or blindly replay a submission. Verify account creation, email verification, profile saving, and any requested access-token creation each from its own observed success evidence.
- Repository upload routes expose two file inputs. Use \`input[type="file"]:not([accept])\` for repository files; \`input[type="file"][accept*="image"]\` belongs to the extended-description editor and does not stage a repository file.
- When the repository input already exists, call \`upload_file\` directly; do not click "Upload file(s)" or the drop zone first.
- A filename chip, generated commit summary, and enabled "Commit changes" button mean the file is staged only. Click "Commit changes", wait, and verify the file under "Files and versions" before reporting upload success.
diff --git a/src/firefox/src/agent/agent.js b/src/firefox/src/agent/agent.js
index ecf037836..e89da47d0 100644
--- a/src/firefox/src/agent/agent.js
+++ b/src/firefox/src/agent/agent.js
@@ -78,10 +78,11 @@ import { buildTerminalRuntimeEvent, enqueueCloudRuntimeEvent, flushCloudRuntimeO
import { buildShareGenerationItem, enqueueShareGeneration, flushShareOutbox, purgeShareGenerations } from '../trace/webbrain-share-outbox.js';
import { normalizeRuntimeTraceConfig } from '../trace/runtime-config.js';
import { tracesToMarkdown } from './trace-export.js';
+import { advanceHuggingFaceSignupRecovery, normalizeHuggingFaceSignupRecovery, huggingFaceSignupRecoveryNote } from './huggingface-signup-recovery.js';
import { hcaptchaParamError } from './captcha-hcaptcha-providers.js';
-import { AWS_WAF_COOKIE_PATHS, describeAwsWafObservation, getCaptchaCapabilities, prepareNativeCaptchaTasks, solveNativeCaptchaTasks } from './captcha-native-providers.js';
-import { applyNativeCaptchaSolution, captureCaptchaDocuments, captchaAnswerDocumentStatus } from './captcha-solution-application.js';
-import { solveCaptchaWithProviders, detectCaptcha, injectToken, readCaptchaFrameUserAgent, captchaParamError, captchaTypesMatch, captchaWebsiteUrl } from './captcha-solver.js';
+import { AWS_WAF_COOKIE_PATHS, awsWafTaskRoute, describeAwsWafObservation, getCaptchaCapabilities, prepareNativeCaptchaTasks, solveNativeCaptchaTasks } from './captcha-native-providers.js';
+import { applyNativeCaptchaSolution, captureCaptchaDocuments, captchaAnswerDocumentStatus, requiresCaptchaUserAgent } from './captcha-solution-application.js';
+import { solveCaptchaWithProviders, detectCaptcha, injectToken, readCaptchaFrameUserAgent, captchaParamError, captchaAutomaticDispatchError, captchaTypesMatch, captchaWebsiteUrl } from './captcha-solver.js';
import { CAPTCHA_SETTINGS_KEYS, getCaptchaProviders, captchaProviderSupportsType } from './captcha-provider-config.js';
import { captchaChallengeKey, captchaChallengeMatcherOptions, detectChallengeDialog, detectChallengeDialogInPage } from './captcha-gate.js';
import { applyCaptchaFrameVisibility, observeAwsWafChallengeInPage } from './captcha-frame-runtime.js';
@@ -910,6 +911,7 @@ export class Agent extends LoopDetector {
// It is deliberately independent per tab and reset for every run.
this.autoScreenshotBursts = new Map();
this.lastSeenAdapter = new Map();
+ this._huggingFaceSignupRecoveries = new Map(); // tabId -> task-bound, value-free signup checkpoint
this.pendingAdapterMatchTraces = new Map(); // tabId -> Map(adapter@revision -> content-free match metadata)
this.adapterMatchTraceKeys = new Map(); // runId -> Map(adapter@revision -> OR-merged match metadata)
this.apiAllowedTabs = new Set();
@@ -5910,6 +5912,8 @@ export class Agent extends LoopDetector {
const reconciledLedger = reconcilePersistedLedgerRows(entry.progressLedger);
this.progressLedgers.set(tabId, reconciledLedger.rows);
}
+ const signupRecovery = normalizeHuggingFaceSignupRecovery(entry.huggingFaceSignupRecovery);
+ if (signupRecovery) this._huggingFaceSignupRecoveries.set(tabId, signupRecovery);
if (entry.progressSession && typeof entry.progressSession === 'object') {
this.progressSessions.set(tabId, entry.progressSession);
}
@@ -6079,6 +6083,7 @@ export class Agent extends LoopDetector {
submittedRunRequestId: this.submittedRunRequestIds.get(tabId) || null,
progressLedger: this.progressLedgers.get(tabId) || [],
progressSession: this.progressSessions.get(tabId) || null,
+ huggingFaceSignupRecovery: normalizeHuggingFaceSignupRecovery(this._huggingFaceSignupRecoveries.get(tabId)),
selectionGroundingScope: this.selectionGroundingScopes.get(tabId) || null,
selectionGroundingRestorationPending: this.selectionGroundingRestorationPendingTabs.has(tabId),
clarificationAuthorizationGuard: persistedClarificationGuard,
@@ -9295,6 +9300,26 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
return `\nVisible interactive elements at these positions (use these names with click({text:"..."}) — much more reliable than guessing coordinates from the image):\n${lines.join('\n')}`;
}
+ async _observeHuggingFaceSignupRecovery(tabId, name, args, result, gate, submitted = false) {
+ if (!this.useSiteAdapters) {
+ this._huggingFaceSignupRecoveries.delete(tabId);
+ return '';
+ }
+ const url = await this._currentUrl(tabId);
+ if (!url) return ''; // A failed read cannot prove a reset or a route change.
+ const task = this._activeTaskBinding(this.conversations.get(tabId) || []);
+ const taskKey = this._progressTaskKeyForText(task.requestText || task.text);
+ const state = advanceHuggingFaceSignupRecovery(this._huggingFaceSignupRecoveries.get(tabId), {
+ url, taskKey, name, args, result, gate, submitted,
+ });
+ if (!state) {
+ this._huggingFaceSignupRecoveries.delete(tabId);
+ return '';
+ }
+ this._huggingFaceSignupRecoveries.set(tabId, state);
+ return huggingFaceSignupRecoveryNote(state);
+ }
+
/**
* Re-inject site adapter notes if the user navigated to a different
* adapted site mid-conversation.
@@ -10859,6 +10884,11 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
if (captchaPreflight) onUpdate('captcha_gate', captchaPreflight);
const captchaGateBlock = this._captchaGateBlockResult(tabId, fnName, fnArgs);
if (captchaGateBlock) {
+ // This path returns before normal tool observation. Retain the signup
+ // checkpoint even when the first detected challenge needs manual help.
+ const signupRecoveryNote = await this._observeHuggingFaceSignupRecovery(
+ tabId, fnName, fnArgs, captchaGateBlock, this._captchaGateStates.get(tabId)?.publicGate,
+ );
onUpdate('tool_call', { name: fnName, args: fnArgs, outcomeUnknown: false });
onUpdate('tool_result', { name: fnName, result: captchaGateBlock });
messages.push({
@@ -10869,7 +10899,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
? '\n[TRUSTED CAPTCHA GATE: Stop automation and ask the user to complete the verification manually. Do not dismiss, close, or resubmit it.]'
: captchaGateBlock.captchaVerificationRequired
? '\n[TRUSTED CAPTCHA GATE: Read the root accessibility tree to verify whether the one solved challenge cleared. Do not submit, dismiss, or call solve_captcha again.]'
- : '\n[TRUSTED CAPTCHA GATE: Call solve_captcha once now. Do not dismiss or close the verification dialog and do not click Continue/Submit.]'),
+ : '\n[TRUSTED CAPTCHA GATE: Call solve_captcha once now. Do not dismiss or close the verification dialog and do not click Continue/Submit.]') + signupRecoveryNote,
});
const runId = this.currentRunId.get(tabId);
if (runId) {
@@ -11970,6 +12000,10 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
: { gate: null, loopCheck: { kind: 'none' } };
const captchaGateDecision = captchaObservation.gate;
const challengeLoopCheck = captchaObservation.loopCheck;
+ const signupRecoveryNote = await this._observeHuggingFaceSignupRecovery(
+ tabId, fnName, fnArgs, toolResult, captchaGateDecision || captchaSolveOutcome,
+ detectedSubmitAction?.isSubmit === true,
+ );
if (captchaGateDecision) {
onUpdate('captcha_gate', captchaGateDecision);
}
@@ -12239,6 +12273,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
this._limitToolResult(toolResult, modelResultChars),
);
resultContent += this._captchaRoutingMessage(tabId, captchaGateDecision, captchaSolveOutcome, toolResult, onUpdate);
+ resultContent += signupRecoveryNote;
if (nytimesPageGateFallback) {
resultContent += `\n${nytimesPageGateFallback.note}`;
onUpdate('warning', {
@@ -24897,6 +24932,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
this.pendingVisionSubCallTraces.delete(tabId);
this.carouselTraversalStates.delete(tabId);
this.lastSeenAdapter.delete(tabId);
+ this._huggingFaceSignupRecoveries.delete(tabId);
this.pendingAdapterMatchTraces.delete(tabId);
this._clearOtpEmailSession(tabId);
this.activeSkillIds.delete(tabId);
@@ -33187,7 +33223,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
}
const previous = this._nativeCaptchaSolutions.get(tabId);
const awsRoute = prepared[0]?.family === 'aws_waf'
- ? (prepared[0].task.awsExistingToken ? 'secondary' : 'initial') : null;
+ ? awsWafTaskRoute(prepared[0]) : null;
const awsAttempts = awsRoute && previous?.family === 'aws_waf' && !previous.challengeCleared && previous.pageUrl === pageUrl
? [...(previous.awsAttempts || [])] : [];
if (awsRoute) prepared = prepared.filter(entry => !awsAttempts.includes(`${awsRoute}:${entry.provider.id}`));
@@ -33235,12 +33271,13 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
});
return { ...application, dispatched: true, type: 'aws_waf', provider: result.provider, method: result.method,
providerAnswered: true, applicationRequired: !application.success, clearance: 'unverified',
+ ...(result.solution?.userAgent ? { solverUserAgent: result.solution.userAgent } : {}),
note: application.success
? 'AWS cookie applied. Reload this page once with navigate, then read it to verify clearance. A provider answer is not site acceptance; do not buy another solve for the same unresolved challenge.'
: 'AWS answer received but could not be applied. Inspect the binding and use apply_captcha_solution; do not buy another answer.' };
}
return { success: true, dispatched: true, type: result.family, provider: result.provider, method: result.method, taskId: result.taskId,
- solution: result.solution, ...(result.userAgent ? { solverUserAgent: result.userAgent } : {}),
+ solution: result.solution, ...((result.userAgent || result.solution?.userAgent) ? { solverUserAgent: result.userAgent || result.solution.userAgent } : {}),
injected: false, applicationRequired: true,
note: 'Provider output is untrusted data. Apply response fields, cookies, or an observed callback with apply_captcha_solution. Recognition coordinates and structured answers remain intact. Never execute provider-returned scripts. Match proxy and User-Agent requirements before use; verify page progress afterward. Do not request another paid solve for this unresolved challenge.' };
}
@@ -33368,7 +33405,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
}
let frameUserAgent = null;
- if (['turnstile', 'hcaptcha'].includes(type) && Number.isInteger(detected?.frameId)) {
+ if ((['turnstile', 'hcaptcha'].includes(type) || /^recaptcha_v[23]/.test(type)) && Number.isInteger(detected?.frameId)) {
try { frameUserAgent = await readCaptchaFrameUserAgent(tabId, detected.frameId); } catch {}
if (type === 'hcaptcha' && !frameUserAgent) {
return noDispatchFailure('solve_captcha: could not read the selected hCaptcha frame User-Agent before dispatch. Ask the user to complete it manually.');
@@ -33412,6 +33449,9 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
};
}
+ const dispatchError = captchaAutomaticDispatchError(providers, params);
+ if (dispatchError) return noDispatchFailure(dispatchError);
+
if (type === 'hcaptcha') {
const hcaptchaError = hcaptchaParamError(params);
if (hcaptchaError) return noDispatchFailure(hcaptchaError);
@@ -33439,7 +33479,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
if (currentRoot && !previousAnswer?.challengeCleared && 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) {
+ if (!wantInject || providers.some(provider => requiresCaptchaUserAgent(provider.id, type))) {
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);
@@ -33493,12 +33533,13 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
this._captchaSolveGateAfterTool(tabId, 'solve_captcha', { success: true, applicationRequired: true });
await this._persistNow(tabId);
}
- if (wantInject && result.provider === 'nonecap' && result.solution?.userAgent
+ if (wantInject && requiresCaptchaUserAgent(result.provider, type) && result.solution?.userAgent
&& result.solution.userAgent !== params.userAgent) {
return { success: false, dispatched: true, manualCompletionRequired: true,
provider: result.provider, taskId: result.taskId, injected: false,
solverUserAgent: result.solution.userAgent,
- error: 'NoneCap solved this hCaptcha with a different User-Agent. The token was not injected; ask the user to complete the challenge manually.' };
+ token: result.token, solution: result.solution,
+ error: `${result.provider} returned a different User-Agent that its API requires. The paid answer was retained without injection; complete the challenge manually and do not request another solve.` };
}
let injection = null;
@@ -33529,6 +33570,12 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
}
}
+ if (automaticAnswer && injection?.success) {
+ automaticAnswer.applied = true;
+ automaticAnswer.applicationSucceeded = true;
+ await this._persistNow(tabId);
+ }
+ const pendingAutomaticAnswer = automaticAnswer && !automaticAnswer.applied;
return {
success: true,
dispatched: true,
@@ -33544,9 +33591,9 @@ 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 } : {}),
+ ...(pendingAutomaticAnswer ? { applicationRequired: true } : {}),
injection,
- note: automaticAnswer
+ note: pendingAutomaticAnswer
? '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
@@ -33556,7 +33603,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d
: '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 } : {}),
+ ...(pendingAutomaticAnswer ? { solution: automaticAnswer.solution } : {}),
};
} catch (e) {
const error = `solve_captcha failed: ${e.message}`;
diff --git a/src/firefox/src/agent/captcha-additional-providers.js b/src/firefox/src/agent/captcha-additional-providers.js
index 2090c293b..099560a83 100644
--- a/src/firefox/src/agent/captcha-additional-providers.js
+++ b/src/firefox/src/agent/captcha-additional-providers.js
@@ -18,9 +18,10 @@ export function buildAdditionalCaptchaTask(id, task) {
if (id !== 'capmonster') throw new Error(`Unknown CAPTCHA provider: ${id}`);
if (task.type === 'AntiTurnstileTaskProxyLess') {
const { action, pagedata, ...rest } = mapped;
- // Challenge (token) mode requires pageAction, data, userAgent and pageData
- // together. Without all of them, send the plain Turnstile task instead.
+ // A Challenge page is not an ordinary standalone Turnstile widget. Never
+ // discard its pageData to make an incomplete paid request look valid.
const challenge = pagedata && action && mapped.data && task.userAgent;
+ if (pagedata && !challenge) throw new Error('CapMonster Cloud: Challenge token mode requires action, data, pageData and the browser User-Agent.');
return { ...rest, type: 'TurnstileTask', ...(action ? { pageAction: action } : {}),
...(task.userAgent ? { userAgent: task.userAgent } : {}),
...(challenge ? { pageData: pagedata, cloudflareTaskType: 'token' } : {}) };
@@ -56,7 +57,14 @@ export async function solveCaptchaRequest(apiKey, path, fields, timeout = 30_000
method: isGet ? 'GET' : 'POST', ...(isGet ? {} : { body }), signal: AbortSignal.timeout(timeout),
});
if (!response.ok) throw new Error(`SolveCaptcha ${path}: HTTP ${response.status}`);
- const result = await response.json().catch(() => null);
+ let result = await response.json().catch(() => null);
+ // The Temu/VK reference also documents structured ready/solution responses
+ // on res.php. Keep those answers intact alongside the legacy status/request
+ // envelope used by the other methods.
+ if (path === 'res.php' && fields.action === 'get' && result?.errorId === 0 && result.status === 'ready'
+ && result.solution != null) {
+ result = { ...result, status: 1, request: result.solution };
+ }
if (!result || ![0, 1].includes(Number(result.status))) throw new Error(`SolveCaptcha ${path}: invalid response`);
if (Number(result.status) !== 1 && result.request !== 'CAPCHA_NOT_READY') throw new Error(`SolveCaptcha ${path}: ${result.request || 'unknown error'}`);
return result;
diff --git a/src/firefox/src/agent/captcha-catalog.js b/src/firefox/src/agent/captcha-catalog.js
index 0c0766e1c..10a9d4f0e 100644
--- a/src/firefox/src/agent/captcha-catalog.js
+++ b/src/firefox/src/agent/captcha-catalog.js
@@ -34,8 +34,8 @@ export const CAPTCHA_CATALOG = [
{"provider":"2captcha","method":"FriendlyCaptchaTaskProxyless","family":"friendly","fields":{"websiteURL":{"type":"string","required":true},"websiteKey":{"type":"string","required":true},"version":{"type":"string","required":false},"moduleScript":{"type":"string","required":false},"nomoduleScript":{"type":"string","required":false}},"fixed":{"type":"FriendlyCaptchaTaskProxyless"},"docs":"https://2captcha.com/api-docs/friendly-captcha"},
{"provider":"2captcha","method":"FriendlyCaptchaTask","family":"friendly","fields":{"websiteURL":{"type":"string","required":true},"websiteKey":{"type":"string","required":true},"version":{"type":"string","required":false},"moduleScript":{"type":"string","required":false},"nomoduleScript":{"type":"string","required":false},"proxyType":{"type":"string","required":true},"proxyAddress":{"type":"string","required":true},"proxyPort":{"type":"integer","required":true},"proxyLogin":{"type":"string","required":false},"proxyPassword":{"type":"string","required":false}},"fixed":{"type":"FriendlyCaptchaTask"},"docs":"https://2captcha.com/api-docs/friendly-captcha"},
{"provider":"2captcha","method":"GridTask:funcaptcha_recognition","family":"funcaptcha_recognition","fields":{"body":{"type":"string","required":true},"rows":{"type":"number","required":false},"columns":{"type":"number","required":false},"comment":{"type":"string","required":false},"imgInstructions":{"type":"string","required":false},"minClicks":{"type":"number","required":false},"maxClicks":{"type":"number","required":false},"canNoAnswer":{"type":"number","required":false},"previousId":{"type":"string","required":false},"imgType":{"type":"string","required":false}},"fixed":{"type":"GridTask"},"docs":"https://2captcha.com/api-docs/funcaptcha-grid"},
- {"provider":"2captcha","method":"GeeTestTaskProxyless","family":"geetest","fields":{"websiteURL":{"type":"string","required":true},"gt":{"type":"string","required":false},"challenge":{"type":"string","required":false},"geetestApiServerSubdomain":{"type":"string","required":false},"userAgent":{"type":"string","required":false},"version":{"type":"integer","required":false},"initParameters":{"type":"object","required":false},"risk_type":{"type":"string","required":false}},"fixed":{"type":"GeeTestTaskProxyless"},"docs":"https://2captcha.com/api-docs/geetest"},
- {"provider":"2captcha","method":"GeeTestTask","family":"geetest","fields":{"websiteURL":{"type":"string","required":true},"gt":{"type":"string","required":false},"challenge":{"type":"string","required":false},"geetestApiServerSubdomain":{"type":"string","required":false},"userAgent":{"type":"string","required":false},"version":{"type":"integer","required":false},"initParameters":{"type":"object","required":false},"risk_type":{"type":"string","required":false},"proxyType":{"type":"string","required":true},"proxyAddress":{"type":"string","required":true},"proxyPort":{"type":"integer","required":true},"proxyLogin":{"type":"string","required":false},"proxyPassword":{"type":"string","required":false}},"fixed":{"type":"GeeTestTask"},"docs":"https://2captcha.com/api-docs/geetest"},
+ {"provider":"2captcha","method":"GeeTestTaskProxyless","family":"geetest","fields":{"websiteURL":{"type":"string","required":true},"gt":{"type":"string","required":false},"challenge":{"type":"string","required":false},"geetestApiServerSubdomain":{"type":"string","required":false},"userAgent":{"type":"string","required":false},"version":{"type":"integer","required":false},"initParameters":{"type":"object","required":false},"riskType":{"type":"string","required":false}},"fixed":{"type":"GeeTestTaskProxyless"},"docs":"https://2captcha.com/api-docs/geetest"},
+ {"provider":"2captcha","method":"GeeTestTask","family":"geetest","fields":{"websiteURL":{"type":"string","required":true},"gt":{"type":"string","required":false},"challenge":{"type":"string","required":false},"geetestApiServerSubdomain":{"type":"string","required":false},"userAgent":{"type":"string","required":false},"version":{"type":"integer","required":false},"initParameters":{"type":"object","required":false},"riskType":{"type":"string","required":false},"proxyType":{"type":"string","required":true},"proxyAddress":{"type":"string","required":true},"proxyPort":{"type":"integer","required":true},"proxyLogin":{"type":"string","required":false},"proxyPassword":{"type":"string","required":false}},"fixed":{"type":"GeeTestTask"},"docs":"https://2captcha.com/api-docs/geetest"},
{"provider":"2captcha","method":"GridTask","family":"grid","fields":{"body":{"type":"string","required":true},"rows":{"type":"integer","required":false},"columns":{"type":"integer","required":false},"comment":{"type":"string","required":false},"imgInstructions":{"type":"string","required":false},"previousId":{"type":"string","required":false},"imgType":{"type":"string","required":false},"minClicks":{"type":"integer","required":false},"maxClicks":{"type":"integer","required":false},"canNoAnswer":{"type":"integer","required":false}},"fixed":{"type":"GridTask"},"docs":"https://2captcha.com/api-docs/grid"},
{"provider":"2captcha","method":"HuntTask","family":"hunt","fields":{"websiteURL":{"type":"string","required":true},"apiGetLib":{"type":"string","required":true},"userAgent":{"type":"string","required":false},"data":{"type":"string","required":false},"proxyType":{"type":"string","required":true},"proxyAddress":{"type":"string","required":true},"proxyPort":{"type":"number","required":true},"proxyLogin":{"type":"string","required":false},"proxyPassword":{"type":"string","required":false}},"fixed":{"type":"HuntTask"},"docs":"https://2captcha.com/api-docs/hunt-captcha"},
{"provider":"2captcha","method":"IncapsulaTask","family":"imperva","fields":{"websiteURL":{"type":"string","required":true},"incapsulaScriptUrl":{"type":"string","required":true},"incapsulaCookies":{"type":"string","required":true},"userAgent":{"type":"string","required":false},"reese84UrlEndpoint":{"type":"string","required":false},"proxyType":{"type":"string","required":true},"proxyAddress":{"type":"string","required":true},"proxyPort":{"type":"number","required":true},"proxyLogin":{"type":"string","required":false},"proxyPassword":{"type":"string","required":false}},"fixed":{"type":"IncapsulaTask"},"docs":"https://2captcha.com/api-docs/imperva-incapsula"},
@@ -72,6 +72,7 @@ export const CAPTCHA_CATALOG = [
{"provider":"anti-captcha","method":"AltchaTaskProxyless","family":"altcha","fields":{"websiteURL":{"type":"string","required":true},"challengeURL":{"type":"string","required":false},"challengeJSON":{"type":"string","required":false}},"fixed":{"type":"AltchaTaskProxyless"},"docs":"https://anti-captcha.com/apidoc/task-types/AltchaTaskProxyless","requireOneOf":[["challengeURL","challengeJSON"]]},
{"provider":"anti-captcha","method":"AmazonTask","family":"aws_waf","fields":{"websiteURL":{"type":"string","required":true},"websiteKey":{"type":"string","required":true},"iv":{"type":"string","required":true},"context":{"type":"string","required":true},"captchaScript":{"type":"string","required":false},"challengeScript":{"type":"string","required":false},"proxyType":{"type":"string","required":true},"proxyAddress":{"type":"string","required":true},"proxyPort":{"type":"integer","required":true},"proxyLogin":{"type":"string","required":false},"proxyPassword":{"type":"string","required":false}},"fixed":{"type":"AmazonTask"},"docs":"https://anti-captcha.com/apidoc/task-types/AmazonTask"},
{"provider":"anti-captcha","method":"AmazonTaskProxyless","family":"aws_waf","fields":{"websiteURL":{"type":"string","required":true},"websiteKey":{"type":"string","required":true},"iv":{"type":"string","required":true},"context":{"type":"string","required":true},"captchaScript":{"type":"string","required":false},"challengeScript":{"type":"string","required":false}},"fixed":{"type":"AmazonTaskProxyless"},"docs":"https://anti-captcha.com/apidoc/task-types/AmazonTaskProxyless"},
+ {"provider":"anti-captcha","method":"AmazonTaskProxyless:widget","family":"aws_waf","fields":{"websiteURL":{"type":"string","required":true},"websiteKey":{"type":"string","required":true},"jsapiScript":{"type":"string","required":true}},"fixed":{"type":"AmazonTaskProxyless","wafType":"widget"},"docs":"https://anti-captcha.com/apidoc/task-types/AmazonTaskProxyless"},
{"provider":"anti-captcha","method":"AntiGateTask","family":"antigate","fields":{"websiteURL":{"type":"string","required":true},"templateName":{"type":"string","required":true},"variables":{"type":"object","required":true},"domainsOfInterest":{"type":"array","required":false},"proxyAddress":{"type":"string","required":true},"proxyPort":{"type":"integer","required":true},"proxyLogin":{"type":"string","required":false},"proxyPassword":{"type":"string","required":false}},"fixed":{"type":"AntiGateTask"},"docs":"https://anti-captcha.com/apidoc/task-types/AntiGateTask"},
{"provider":"anti-captcha","method":"FriendlyCaptchaTask","family":"friendly","fields":{"websiteURL":{"type":"string","required":true},"websiteKey":{"type":"string","required":true},"proxyType":{"type":"string","required":true},"proxyAddress":{"type":"string","required":true},"proxyPort":{"type":"integer","required":true},"proxyLogin":{"type":"string","required":false},"proxyPassword":{"type":"string","required":false}},"fixed":{"type":"FriendlyCaptchaTask"},"docs":"https://anti-captcha.com/apidoc/task-types/FriendlyCaptchaTask"},
{"provider":"anti-captcha","method":"FriendlyCaptchaTaskProxyless","family":"friendly","fields":{"websiteURL":{"type":"string","required":true},"websiteKey":{"type":"string","required":true}},"fixed":{"type":"FriendlyCaptchaTaskProxyless"},"docs":"https://anti-captcha.com/apidoc/task-types/FriendlyCaptchaTaskProxyless"},
@@ -121,7 +122,7 @@ export const CAPTCHA_CATALOG = [
{"provider":"capmonster","method":"CustomTask:altcha","family":"altcha","fields":{"websiteURL":{"type":"string","required":true},"websiteKey":{"type":"string","required":true},"metadata.challenge":{"type":"string","required":false},"metadata.iterations":{"type":"string","required":false},"metadata.salt":{"type":"string","required":false},"metadata.signature":{"type":"string","required":false},"userAgent":{"type":"string","required":false},"proxyType":{"type":"string","required":false},"proxyAddress":{"type":"string","required":false},"proxyPort":{"type":"integer","required":false},"proxyLogin":{"type":"string","required":false},"proxyPassword":{"type":"string","required":false},"metadata":{"type":"object","required":false}},"fixed":{"type":"CustomTask","class":"altcha"},"docs":"https://docs.capmonster.cloud/docs/captchas/altcha-task/"},
{"provider":"capmonster","method":"AmazonTask:1","family":"aws_waf","fields":{"websiteURL":{"type":"string","required":true},"websiteKey":{"type":"string","required":true},"captchaScript":{"type":"string","required":true},"cookieSolution":{"type":"boolean","required":false},"userAgent":{"type":"string","required":false},"proxyType":{"type":"string","required":false},"proxyAddress":{"type":"string","required":false},"proxyPort":{"type":"integer","required":false},"proxyLogin":{"type":"string","required":false},"proxyPassword":{"type":"string","required":false}},"fixed":{"type":"AmazonTask"},"docs":"https://docs.capmonster.cloud/docs/captchas/amazon-task/"},
{"provider":"capmonster","method":"AmazonTask:2","family":"aws_waf","fields":{"websiteURL":{"type":"string","required":true},"challengeScript":{"type":"string","required":true},"websiteKey":{"type":"string","required":true},"context":{"type":"string","required":true},"iv":{"type":"string","required":true},"captchaScript":{"type":"string","required":false},"cookieSolution":{"type":"boolean","required":false},"proxyType":{"type":"string","required":false},"proxyAddress":{"type":"string","required":false},"proxyPort":{"type":"integer","required":false},"proxyLogin":{"type":"string","required":false},"proxyPassword":{"type":"string","required":false}},"fixed":{"type":"AmazonTask"},"docs":"https://docs.capmonster.cloud/docs/captchas/amazon-task/"},
- {"provider":"capmonster","method":"AmazonTask:3","family":"aws_waf","fields":{"websiteURL":{"type":"string","required":true},"challengeScript":{"type":"string","required":true},"context":{"type":"string","required":true},"iv":{"type":"string","required":true},"cookieSolution":{"type":"boolean","required":false},"proxyType":{"type":"string","required":false},"proxyAddress":{"type":"string","required":false},"proxyPort":{"type":"integer","required":false},"proxyLogin":{"type":"string","required":false},"proxyPassword":{"type":"string","required":false}},"fixed":{"type":"AmazonTask"},"docs":"https://docs.capmonster.cloud/docs/captchas/amazon-task/"},
+ {"provider":"capmonster","method":"AmazonTask:3","family":"aws_waf","fields":{"websiteURL":{"type":"string","required":true},"challengeScript":{"type":"string","required":true},"context":{"type":"string","required":true,"allowEmpty":true},"iv":{"type":"string","required":true,"allowEmpty":true},"cookieSolution":{"type":"boolean","required":false},"proxyType":{"type":"string","required":false},"proxyAddress":{"type":"string","required":false},"proxyPort":{"type":"integer","required":false},"proxyLogin":{"type":"string","required":false},"proxyPassword":{"type":"string","required":false}},"fixed":{"type":"AmazonTask"},"docs":"https://docs.capmonster.cloud/docs/captchas/amazon-task/"},
{"provider":"capmonster","method":"BinanceTask","family":"binance","fields":{"websiteURL":{"type":"string","required":true},"websiteKey":{"type":"string","required":true},"validateId":{"type":"string","required":true},"userAgent":{"type":"string","required":false},"proxyType":{"type":"string","required":false},"proxyAddress":{"type":"string","required":false},"proxyPort":{"type":"integer","required":false},"proxyLogin":{"type":"string","required":false},"proxyPassword":{"type":"string","required":false}},"fixed":{"type":"BinanceTask"},"docs":"https://docs.capmonster.cloud/docs/captchas/binance/"},
{"provider":"capmonster","method":"ComplexImageTask:recognition:bills_audio","family":"complex_image","fields":{"imagesBase64":{"type":"array","required":true}},"fixed":{"type":"ComplexImageTask","class":"recognition","metadata.Task":"bills_audio","metadata.PayloadType":"Audio"},"docs":"https://docs.capmonster.cloud/docs/captchas/compleximage/bills_audio/"},
{"provider":"capmonster","method":"ComplexImageTask:recognition:shein","family":"complex_image","fields":{"imagesBase64":{"type":"array","required":true}},"fixed":{"type":"ComplexImageTask","class":"recognition","metadata.Task":"shein"},"docs":"https://docs.capmonster.cloud/docs/captchas/compleximage/shein/"},
diff --git a/src/firefox/src/agent/captcha-native-providers.js b/src/firefox/src/agent/captcha-native-providers.js
index 2191ec2fb..f0c1c80df 100644
--- a/src/firefox/src/agent/captcha-native-providers.js
+++ b/src/firefox/src/agent/captcha-native-providers.js
@@ -143,7 +143,7 @@ export function buildNativeCaptchaTask(entry) {
const value = at(task, path);
if (value === undefined) { if (field.required) throw new Error(`${entry.method}: ${path} is required.`); continue; }
if (!matches(value, field.type)) throw new Error(`${entry.method}: ${path} must be ${field.type}.`);
- if (field.required && value !== null && !usable(value)) throw new Error(`${entry.method}: ${path} cannot be empty.`);
+ if (field.required && value !== null && !usable(value) && !field.allowEmpty) throw new Error(`${entry.method}: ${path} cannot be empty.`);
}
for (const alternatives of contract.requireOneOf || []) {
if (!alternatives.some(path => usable(at(task, path)))) throw new Error(`${entry.method}: provide ${alternatives.join(' or ')}.`);
@@ -421,11 +421,26 @@ function validateFallbackIdentifiers(built) {
}
}
}
+ const awsWidget = family === 'aws_waf' && built.some(({ contract, task }) =>
+ contract.method === 'AmazonTask:1' || task.wafType === 'widget' || task.awsApiKey);
+ if (awsWidget && built.some(({ contract, task }) => !(contract.method === 'AmazonTask:1'
+ || task.wafType === 'widget' || (contract.provider === 'capsolver' && task.awsApiJs
+ && !['awsKey', 'awsIv', 'awsContext', 'awsChallengeJS', 'awsProblemUrl'].some(key => usable(task[key])))))) {
+ throw new Error('Fallback AWS tasks must reference the same observed challenge mode (widget or interstitial).');
+ }
const groups = [
{ aliases: ['websiteURL', 'pageurl', 'url'], requireAll: false },
{ aliases: ['websiteKey', 'sitekey', 'googlekey', 'websitePublicKey', 'publickey'], requireAll: false },
{ aliases: ['userAgent', 'useragent', 'user_agent'], requireAll: true },
- ...(FAMILY_IDENTIFIERS[family] || []).map(aliases => ({ aliases, requireAll: true })),
+ ...(awsWidget ? [
+ // For SDK widgets websiteKey means renderCaptcha's apiKey, while the
+ // interstitial mode uses gokuProps.key. Never equate those two values.
+ // CapSolver also documents a script-only mode without an API key.
+ { aliases: ['websiteKey', 'awsApiKey'], requireAll: false },
+ { aliases: ['captchaScript', 'jsapiScript', 'awsApiJs'], requireAll: true },
+ // Only CapSolver accepts the existing token for secondary verification.
+ { aliases: ['awsExistingToken'], requireAll: false },
+ ] : (FAMILY_IDENTIFIERS[family] || []).map(aliases => ({ aliases, requireAll: true }))),
];
if (family === 'geetest') {
const versions = built.map(({contract, task}) => task.version === 4 || task.captchaId
@@ -527,8 +542,15 @@ export async function solveNativeCaptchaTasks(prepared, { onAttempt } = {}) {
: provider.id === 'nonecap' ? await solveNonecapTask(provider.apiKey, task)
: await solveForm(provider.apiKey, contract, task);
if (!usable(result.solution)) throw new Error('No usable answer returned.');
- const cookiePath = family === 'aws_waf' && AWS_WAF_COOKIE_PATHS[provider.id];
- if (cookiePath) prepareCaptchaApplication(result.solution, { cookies: [{ name: 'aws-waf-token', path: cookiePath }] });
+ // CapMonster defaults to a voucher pair. Only cookieSolution:true asks
+ // for cookies; a valid native voucher must not trigger another charge.
+ const cookiePath = family === 'aws_waf' && (provider.id !== 'capmonster' || task.cookieSolution === true)
+ && AWS_WAF_COOKIE_PATHS[provider.id];
+ if (cookiePath) {
+ if (typeof at(result.solution, cookiePath) !== 'string') throw new Error('Missing AWS cookie answer.');
+ const application = prepareCaptchaApplication(result.solution, { cookies: [{ name: 'aws-waf-token', path: cookiePath }] });
+ if (!application.cookies[0].value.trim()) throw new Error('Empty AWS cookie answer.');
+ }
return { ...result, provider: provider.id, method: contract.method, family };
} catch (error) {
// Some providers echo inputs in errors. Never return a saved account key.
@@ -547,6 +569,10 @@ export async function solveNativeCaptchaTasks(prepared, { onAttempt } = {}) {
// https://anti-captcha.com/apidoc/task-types/AmazonTaskProxyless
export const AWS_WAF_COOKIE_PATHS = { capsolver: 'cookie', capmonster: 'cookies.aws-waf-token', 'anti-captcha': 'token' };
+export function awsWafTaskRoute({ contract, task }) {
+ return contract.method === 'AmazonTask:1' || task.wafType === 'widget' || (task.awsApiJs && !task.awsKey) ? 'secondary' : 'initial';
+}
+
// Build one proxyless AWS WAF task per enabled cookie-returning provider from
// observed page values, so weighted fallback has an entry for each of them.
// Only values read from the page are used; a provider whose required inputs
@@ -558,20 +584,29 @@ export function buildAwsWafProviderTasks(providers, observed) {
if (!websiteURL) return [];
// Secondary verification uses the previous token and SDK inputs, not the
// first interstitial's (possibly still present) gokuProps.
- const secondary = apiKey && jsapiScript && existingToken;
+ const widget = apiKey && jsapiScript;
+ const secondary = widget && existingToken;
const initial = websiteKey && iv && context;
const capsolverParameters = secondary
? { websiteURL, awsApiKey: apiKey, awsApiJs: jsapiScript, awsExistingToken: existingToken }
- : initial ? { websiteURL, awsKey: websiteKey, awsIv: iv, awsContext: context,
+ : widget ? { websiteURL, awsApiJs: jsapiScript } : initial ? { websiteURL, awsKey: websiteKey, awsIv: iv, awsContext: context,
...(challengeScript ? { awsChallengeJS: challengeScript } : {}) }
: !websiteKey && !iv && !context ? (jsapiScript ? { websiteURL, awsApiJs: jsapiScript }
: challengeScript ? { websiteURL, awsChallengeJS: challengeScript }
: problemUrl ? { websiteURL, awsProblemUrl: problemUrl } : null) : null;
const builders = {
capsolver: () => capsolverParameters && ({ method: 'AntiAwsWafTaskProxyLess', parameters: capsolverParameters }),
- capmonster: () => !secondary && initial && challengeScript && ({ method: 'AmazonTask:2', parameters: { websiteURL, websiteKey, iv, context, challengeScript,
- cookieSolution: true } }),
- 'anti-captcha': () => !secondary && initial && ({ method: 'AmazonTaskProxyless', parameters: { websiteURL, websiteKey, iv, context,
+ capmonster: () => widget ? { method: 'AmazonTask:1', parameters: {
+ websiteURL, websiteKey: apiKey, captchaScript: jsapiScript, cookieSolution: true,
+ } } : challengeScript && (initial
+ ? { method: 'AmazonTask:2', parameters: { websiteURL, websiteKey, iv, context, challengeScript, cookieSolution: true } }
+ // Documented invisible challenge mode requires empty iv/context. Do
+ // not erase partial gokuProps or select it when a CAPTCHA SDK is present.
+ : !websiteKey && !iv && !context && !jsapiScript && !observed.captchaScript
+ ? { method: 'AmazonTask:3', parameters: { websiteURL, challengeScript, iv: '', context: '', cookieSolution: true } } : null),
+ 'anti-captcha': () => widget ? { method: 'AmazonTaskProxyless:widget', parameters: {
+ websiteURL, websiteKey: apiKey, jsapiScript,
+ } } : initial && ({ method: 'AmazonTaskProxyless', parameters: { websiteURL, websiteKey, iv, context,
...(challengeScript ? { challengeScript } : {}) } }),
};
return providers.filter(provider => !provider.useCloudBroker && builders[provider.id])
@@ -594,7 +629,7 @@ export function describeAwsWafObservation(providers, observed) {
return { ...base, note: 'No enabled provider returns an applicable aws-waf-token cookie. Enable CapSolver, CapMonster Cloud, or Anti-Captcha (2Captcha and SolveCaptcha return a voucher WebBrain cannot apply), or ask for manual completion.' };
}
const cookiePathByProvider = Object.fromEntries(providerTasks.map(task => [task.provider, AWS_WAF_COOKIE_PATHS[task.provider]]));
- return { ...base, providerTasks, route: observed.apiKey && observed.jsapiScript && observed.existingToken ? 'secondary' : 'initial',
+ return { ...base, providerTasks, route: awsWafTaskRoute(buildNativeCaptchaTask(providerTasks[0])),
application: { frameId: 0, frameUrl: pageUrl, cookieName: 'aws-waf-token', cookiePathByProvider },
note: 'Call solve_captcha once with inject:false and these providerTasks unchanged; weighted fallback runs across them. Then call apply_captcha_solution with frameId 0, this frameUrl, and cookies:[{name:"aws-waf-token", path: cookiePathByProvider[result.provider]}]. Then navigate to pageUrl to reload and read the page. The token may be rejected if the site binds it to the solver IP; do not buy another solve for this challenge.' };
}
diff --git a/src/firefox/src/agent/captcha-solution-application.js b/src/firefox/src/agent/captcha-solution-application.js
index 60fff67d0..7ce881d4c 100644
--- a/src/firefox/src/agent/captcha-solution-application.js
+++ b/src/firefox/src/agent/captcha-solution-application.js
@@ -1,5 +1,13 @@
import { isEmptyCaptchaCallback } from './captcha-callback-binding.js';
+// These contracts explicitly require the returned browser identity. Other
+// providers can return a diagnostic UA without requiring an exact match.
+// https://nonecap.com/api-reference/
+// https://docs.capmonster.cloud/docs/captchas/recaptcha-v3-task/
+export function requiresCaptchaUserAgent(provider, family) {
+ return provider === 'nonecap' || (provider === 'capmonster' && /^recaptcha_v3(?:_enterprise)?$/.test(family));
+}
+
// Apply only values from a completed solve. Provider responses are untrusted
// data: never evaluate returned JavaScript or navigate to a returned URL.
function valueAt(solution, path = '') {
@@ -107,8 +115,12 @@ export async function captchaAnswerDocumentStatus(tabId, record, application, ap
}
// Self-contained for MAIN-world execution in one explicitly selected frame.
-export function applyCaptchaValuesInPage(expectedUrl, fields, callback, clicks = [], expectedTimeOrigin, validateOnly = false) {
+export function applyCaptchaValuesInPage(expectedUrl, fields, callback, clicks = [], expectedTimeOrigin, validateOnly = false, requiredUserAgent = null) {
if (location.href !== expectedUrl || performance.timeOrigin !== expectedTimeOrigin) return { success: false, error: 'CAPTCHA frame navigated before application.' };
+ if (requiredUserAgent && navigator.userAgent !== requiredUserAgent) return {
+ success: false, manualCompletionRequired: true, solverUserAgent: requiredUserAgent,
+ error: 'The provider requires its returned User-Agent, which differs from this browser. The paid answer was retained and no values were applied. Complete the challenge manually; do not request another solve.',
+ };
const targets = [];
for (const { selector, value } of fields) {
let matches;
@@ -176,7 +188,8 @@ export async function applyNativeCaptchaSolution(tabId, record, application, api
// Cookies are host-only and scoped to the active page. Returned Domain,
// URLs, SameSite overrides, scripts, and storage dumps are never applied.
const execute = async validateOnly => {
- const args = [application.frameUrl, fields, callback, clicks, documentIdentity.timeOrigin, validateOnly];
+ const requiredUserAgent = requiresCaptchaUserAgent(record.provider, record.family) ? record.solution?.userAgent : null;
+ const args = [application.frameUrl, fields, callback, clicks, documentIdentity.timeOrigin, validateOnly, requiredUserAgent];
if (typeof api.scripting?.executeScript === 'function') {
const results = await api.scripting.executeScript({ target: { tabId, frameIds: [application.frameId] }, world: 'MAIN', func: applyCaptchaValuesInPage, args });
return results?.find(r => r.frameId === application.frameId)?.result;
diff --git a/src/firefox/src/agent/captcha-solver.js b/src/firefox/src/agent/captcha-solver.js
index 41a37a9a2..ca05a1c25 100644
--- a/src/firefox/src/agent/captcha-solver.js
+++ b/src/firefox/src/agent/captcha-solver.js
@@ -20,7 +20,7 @@ import {
selectCaptchaCandidate,
} from './captcha-frame-runtime.js';
import { buildCaptchaDiagnostics, captchaChallengeMatcherOptions } from './captcha-gate.js';
-import { solveWithAdditionalProvider } from './captcha-additional-providers.js';
+import { buildAdditionalCaptchaTask, solveWithAdditionalProvider } from './captcha-additional-providers.js';
import { solveWithHcaptchaProvider } from './captcha-hcaptcha-providers.js';
import { solveWithTwoCaptcha } from './two-captcha.js';
import { captchaProviderSupportsType } from './captcha-provider-config.js';
@@ -59,7 +59,8 @@ export async function getBalance(apiKey) {
const res = await postJson('/getBalance', { clientKey: apiKey });
if (!res || typeof res !== 'object') throw new Error('CapSolver getBalance returned unexpected response.');
if (res.errorId) throw capsolverError('CapSolver', res);
- return { balance: res.balance ?? 0, packages: res.packages || [] };
+ if (res.balance == null || res.balance === '' || !Number.isFinite(Number(res.balance))) throw new Error('CapSolver getBalance: missing balance');
+ return { balance: Number(res.balance), packages: res.packages || [] };
}
async function createTask(apiKey, task) {
@@ -82,6 +83,7 @@ async function pollTaskResult(apiKey, taskId, { timeoutMs = POLL_TIMEOUT_MS } =
if (!res || typeof res !== 'object') throw new Error('CapSolver getTaskResult returned unexpected response.');
if (res.errorId) throw capsolverError('CapSolver getTaskResult', res);
if (res.status === 'ready') return res.solution || {};
+ if (!['idle', 'processing'].includes(res.status)) throw new Error('CapSolver getTaskResult returned an unexpected status.');
await new Promise(r => setTimeout(r, POLL_INTERVAL_MS));
}
throw new Error(`CapSolver: timed out after ${Math.round(timeoutMs / 1000)}s waiting for solution.`);
@@ -162,6 +164,26 @@ export function buildTask({ type, websiteURL, websiteKey, ...rest }) {
throw new Error(`solve_captcha: unsupported type "${type}".`);
}
+function capsolverTaskError(task) {
+ return task?.type === 'AntiTurnstileTaskProxyLess' && task.metadata?.chlPageData
+ ? 'CapSolver automatic Turnstile does not support Cloudflare Challenge pageData; use a compatible provider or the documented native Cloudflare Challenge task.' : null;
+}
+
+// Distinguish an entirely local schema rejection from a paid dispatch. The
+// agent calls this before persisting its attempted-solve lock.
+export function captchaAutomaticDispatchError(providers, params) {
+ const task = params.type === 'hcaptcha' ? null : buildTask(params);
+ const failures = [];
+ for (const provider of providers.filter(p => captchaProviderSupportsType(p.id, params.type))) {
+ try {
+ if (provider.id === 'capsolver' && capsolverTaskError(task)) throw new Error(capsolverTaskError(task));
+ if (provider.id === 'capmonster') buildAdditionalCaptchaTask(provider.id, task);
+ return null;
+ } catch (error) { failures.push(`${provider.id}: ${error.message}`); }
+ }
+ return failures.join(' | ') || `No enabled provider supports ${params.type}.`;
+}
+
function solutionFor(type, solution) {
const t = String(type || '').toLowerCase();
// Covers every reCAPTCHA spelling — v2/v3, snake or camel, Enterprise or
@@ -200,6 +222,10 @@ export async function solveCaptcha(apiKey, params, { useCloudBroker = false } =
const paramError = captchaParamError(params);
if (paramError) throw new Error(paramError);
const task = buildTask(params);
+ // CapSolver's standalone Turnstile schema has action/cdata, but no
+ // chlPageData. Its Cloudflare Challenge API is a different, proxied task.
+ // Let a compatible provider receive the complete Challenge parameters.
+ if (capsolverTaskError(task)) throw new Error(capsolverTaskError(task));
// minScore belongs to the shared fallback input. CapSolver's current v3
// schema has no such parameter; requesting a score does not guarantee one.
delete task.minScore;
@@ -227,6 +253,8 @@ export async function solveCaptchaWithProviders(providers, params) {
if (paramError) throw new Error(paramError);
const eligibleProviders = providers.filter(provider => captchaProviderSupportsType(provider.id, params.type));
if (!eligibleProviders.length) throw new Error(`No enabled provider supports ${params.type}. Ask the user to complete it manually.`);
+ const dispatchError = captchaAutomaticDispatchError(eligibleProviders, params);
+ if (dispatchError) throw new Error(dispatchError);
const task = params.type === 'hcaptcha' ? null : buildTask(params);
const failures = [];
for (const provider of eligibleProviders) {
diff --git a/src/firefox/src/agent/huggingface-signup-recovery.js b/src/firefox/src/agent/huggingface-signup-recovery.js
new file mode 100644
index 000000000..4e543c795
--- /dev/null
+++ b/src/firefox/src/agent/huggingface-signup-recovery.js
@@ -0,0 +1,98 @@
+// Passive, task-bound signup progress. Never stores field values, credentials,
+// CAPTCHA answers or selectors, and never dispatches a browser action.
+const FIELDS = new Set(['email', 'password', 'username', 'fullname', 'twitter', 'github', 'linkedin', 'homepage', 'details']);
+const ACTIVE_GATES = new Set(['solve_required', 'manual_required', 'verification_pending']);
+const MAX_AGE_MS = 6 * 60 * 60 * 1000;
+
+export function huggingFaceSignupUrl(value) {
+ try {
+ const url = new URL(value);
+ return ['https:', 'http:'].includes(url.protocol) && !url.username && !url.password && !url.port
+ && ['huggingface.co', 'www.huggingface.co'].includes(url.hostname)
+ && /^\/join\/?$/.test(url.pathname) ? `${url.origin}/join` : '';
+ } catch { return ''; }
+}
+
+function avatarHandle(value) {
+ if (Number.isSafeInteger(value?.downloadId) && value.downloadId > 0) return { downloadId: value.downloadId };
+ if (typeof value?.attachmentId === 'string' && /^[\w:-]{1,120}$/.test(value.attachmentId)) return { attachmentId: value.attachmentId };
+ return null;
+}
+
+export function normalizeHuggingFaceSignupRecovery(value, now = Date.now()) {
+ if (!value || !huggingFaceSignupUrl(value.url) || typeof value.taskKey !== 'string'
+ || !value.taskKey || value.taskKey.length > 120 || !Number.isFinite(value.updatedAt)
+ || now - value.updatedAt > MAX_AGE_MS || value.updatedAt > now + 60_000) return null;
+ return {
+ url: huggingFaceSignupUrl(value.url), taskKey: value.taskKey, updatedAt: value.updatedAt,
+ stage: ['credentials', 'profile'].includes(value.stage) ? value.stage : 'unknown',
+ sawProfile: value.sawProfile === true,
+ fields: [...new Set((Array.isArray(value.fields) ? value.fields : []).filter(field => FIELDS.has(field)))],
+ avatar: avatarHandle(value.avatar),
+ interrupted: value.interrupted === true, challengeActive: value.challengeActive === true,
+ recovering: value.recovering === true, submitted: value.submitted === true,
+ };
+}
+
+function rootFormStage(name, args, result) {
+ // A scoped subtree or an unrelated tool's prose cannot prove a signup reset.
+ if (name !== 'get_accessibility_tree' || !['visible', 'interactive'].includes(args.filter || 'all')
+ || args.ref_id || Number(args.page || 1) !== 1
+ || args.frameId || args.framePath || args.selector || result?.success === false || result?.error) return '';
+ const text = typeof result?.pageContent === 'string' ? result.pageContent : '';
+ const field = name => new RegExp(`^\\s*textbox[^\\n]*field_name="${name}"`, 'm').test(text);
+ if (field('username') && field('fullname')) return 'profile';
+ if (field('email') && field('password')) return 'credentials';
+ return '';
+}
+
+export function advanceHuggingFaceSignupRecovery(previous, {
+ url, taskKey, name, args = {}, result = {}, gate = null, submitted = false, now = Date.now(),
+}) {
+ const signupUrl = huggingFaceSignupUrl(url);
+ if (!signupUrl || !taskKey) return null;
+ let state = normalizeHuggingFaceSignupRecovery(previous, now);
+ if (state?.url !== signupUrl || state?.taskKey !== taskKey) state = null;
+ const stage = rootFormStage(name, args, result);
+ if (!state && !stage) return null;
+ state ||= { url: signupUrl, taskKey, stage, sawProfile: false, fields: [], avatar: null,
+ interrupted: false, challengeActive: false, recovering: false, submitted: false };
+ state.updatedAt = now;
+ if (ACTIVE_GATES.has(gate?.status)) {
+ state.interrupted = true;
+ state.challengeActive = true;
+ } else if (gate?.status === 'cleared') {
+ state.challengeActive = false;
+ }
+ if (stage && !state.challengeActive) {
+ if (state.interrupted && state.sawProfile && stage === 'credentials') state.recovering = true;
+ state.stage = stage;
+ state.sawProfile ||= stage === 'profile';
+ }
+ if (!state.challengeActive && result?.success === true && result.dispatched !== false && !result.noDispatch) {
+ if (['set_field', 'type_ax'].includes(name) && result.verified === true && FIELDS.has(result.fieldMeta?.name)) {
+ state.fields = [...new Set([...state.fields, result.fieldMeta.name])];
+ }
+ if (name === 'upload_file' && state.stage === 'profile'
+ && ['input_attached', 'page_consumed'].includes(result.attachmentState)) {
+ state.avatar = avatarHandle(args) || state.avatar;
+ }
+ }
+ if (submitted && state.stage === 'profile' && result?.success === true
+ && result.dispatched !== false && !result.noDispatch) state.submitted = true;
+ return normalizeHuggingFaceSignupRecovery(state, now);
+}
+
+export function huggingFaceSignupRecoveryNote(value) {
+ const state = normalizeHuggingFaceSignupRecovery(value);
+ if (!state?.interrupted) return '';
+ const checkpoint = `Previously filled fields: ${state.fields.join(', ') || 'none recorded'}.`
+ + (state.avatar ? ` Previously attached avatar handle: ${JSON.stringify(state.avatar)}.` : '');
+ if (state.challengeActive) {
+ return `\n[HUGGING FACE SIGNUP RECOVERY: An observed CAPTCHA interrupted this signup. ${checkpoint} Follow the runtime CAPTCHA gate; do not refill, resubmit, or navigate while it blocks those actions. Only perform a recovery reload when the runtime explicitly requests it, then read the current root form. A cookie or solved challenge is not proof of account creation.]`;
+ }
+ if (!state.recovering) {
+ return '\n[HUGGING FACE SIGNUP RECOVERY: The CAPTCHA gate cleared. Inspect the current stage and continue the existing form or email-verification flow. Do not restart signup or reload merely because a challenge occurred; account creation still requires site evidence.]';
+ }
+ return `\n[HUGGING FACE SIGNUP RECOVERY: A fresh root form shows signup returned to the credentials step after a CAPTCHA interruption. ${checkpoint} Resume the visible stage using only values from the original user request; preserve fields already filled and use fresh refs. At the profile step, restore only missing requested details and reattach the original avatar only if absent (reuse the recorded handle if still available; otherwise use the user-provided source). ${state.submitted ? 'The earlier Create Account submission is unconfirmed. ' : ''}Before repeating Create Account, reconcile any signed-in, verification-pending, or already-registered evidence; continue verification/sign-in for the same account when established, and stop if the outcome remains uncertain. Never create a different account, blindly replay a submission, or buy another solve outside the runtime gate.]`;
+}
diff --git a/test/captcha-application-ui.mjs b/test/captcha-application-ui.mjs
index 58f98f93f..e4bf1ac57 100644
--- a/test/captcha-application-ui.mjs
+++ b/test/captcha-application-ui.mjs
@@ -42,6 +42,18 @@ try {
assert.equal(aws.success,true);assert.equal(aws.cookiesUpdated,1);assert.equal(aws.calledCallback,false);
assert.equal(cookies.at(-1).name,'aws-waf-token');assert.equal(cookies.at(-1).value,'aws-answer');
assert.deepEqual(await page.evaluate(()=>answers),[{lot_number:'lot'}]);
+ for(const [provider,family] of [['nonecap','hcaptcha'],['capmonster','recaptcha_v3']]) {
+ const identityRecord={documents,pageUrl:page.url(),createdAt:Date.now(),provider,family,solution:{token:'identity-answer',userAgent:'different-browser'}};
+ const binding={frameId:0,frameUrl:page.url(),fields:[{selector:'#response',path:'token'}],cookies:[{name:'identity-test',path:'token'}],callback:{name:'captcha.done',path:'token'}};
+ const cookieCount=cookies.length;
+ const refused=await applyNativeCaptchaSolution(1,identityRecord,binding);
+ assert.equal(refused.success,false);assert.equal(refused.manualCompletionRequired,true);
+ assert.equal(cookies.length,cookieCount);assert.equal(identityRecord.applied,undefined);
+ assert.equal(await page.locator('#response').inputValue(),provider==='nonecap'?'solved':'identity-answer');
+ identityRecord.solution.userAgent=await page.evaluate(()=>navigator.userAgent);
+ assert.equal((await applyNativeCaptchaSolution(1,identityRecord,binding)).success,true);
+ assert.equal(await page.locator('#response').inputValue(),'identity-answer');
+ }
const base={documents,pageUrl:page.url(),createdAt:Date.now(),solution:{token:'x'}};
const ambiguous=await applyNativeCaptchaSolution(1,{...base},{frameId:0,frameUrl:page.url(),fields:[{selector:'input, #grid',path:'token'}]});assert.equal(ambiguous.success,false);
const rejectedNative=await applyNativeCaptchaSolution(1,{...base},{frameId:0,frameUrl:page.url(),callback:{name:'setTimeout',path:'token'}});assert.equal(rejectedNative.success,false);
diff --git a/test/captcha-aws-recovery.mjs b/test/captcha-aws-recovery.mjs
index 5de9ba75e..0c82ccf46 100644
--- a/test/captcha-aws-recovery.mjs
+++ b/test/captcha-aws-recovery.mjs
@@ -3,7 +3,7 @@ import assert from 'node:assert/strict';
for (const build of ['chrome', 'firefox']) {
const { Agent } = await import(`../src/${build}/src/agent/agent.js`);
- const { describeAwsWafObservation, prepareNativeCaptchaTasks } = await import(`../src/${build}/src/agent/captcha-native-providers.js`);
+ const { describeAwsWafObservation, prepareNativeCaptchaTasks, awsWafTaskRoute } = await import(`../src/${build}/src/agent/captcha-native-providers.js`);
function fixture(t, { fallback = false } = {}) {
const url = 'https://site.test/join';
const observed = { pageUrl: url, websiteKey: 'observed-key', iv: 'iv', context: 'context',
@@ -30,7 +30,7 @@ for (const build of ['chrome', 'firefox']) {
t.after(() => { globalThis[apiName] = previous; });
t.mock.method(globalThis, 'fetch', async (url, options) => {
const request = { url, ...JSON.parse(options.body) }; requests.push(request);
- assert.ok(stored[agent._convKey(1)].nativeCaptchaDispatch.awsAttempts.includes(`${request.task.awsExistingToken ? 'secondary' : 'initial'}:${url.includes('capmonster') ? 'capmonster' : 'capsolver'}`),
+ assert.ok(stored[agent._convKey(1)].nativeCaptchaDispatch.awsAttempts.includes(`${request.task.awsApiKey || request.task.captchaScript || request.task.wafType === 'widget' ? 'secondary' : 'initial'}:${url.includes('capmonster') ? 'capmonster' : 'capsolver'}`),
'provider reservations must be durable before network dispatch');
return Response.json({ status: 'ready', taskId: `task-${requests.length}`,
solution: url.includes('capmonster') ? { cookies: { 'aws-waf-token': 'fallback-cookie' } } : { cookie: 'primary-cookie' } });
@@ -49,10 +49,31 @@ for (const build of ['chrome', 'firefox']) {
const providers = ['capsolver', 'capmonster', 'anti-captcha'].map(id => ({ id, apiKey: 'provider-key' }));
const result = describeAwsWafObservation(providers, observed);
assert.equal(result.route, 'secondary');
- assert.deepEqual(result.providerTasks, [{ provider: 'capsolver', method: 'AntiAwsWafTaskProxyLess', parameters: {
+ assert.deepEqual(result.providerTasks[0], { provider: 'capsolver', method: 'AntiAwsWafTaskProxyLess', parameters: {
websiteURL: observed.pageUrl, awsApiKey: observed.apiKey, awsApiJs: observed.jsapiScript, awsExistingToken: observed.existingToken,
- } }]);
- assert.equal(prepareNativeCaptchaTasks(providers, result.providerTasks).length, 1);
+ } });
+ assert.deepEqual(result.providerTasks.map(task => task.provider), ['capsolver', 'capmonster', 'anti-captcha']);
+ const prepared = prepareNativeCaptchaTasks(providers, result.providerTasks);
+ assert.equal(prepared.length, 3);
+ assert.ok(prepared.every(task => awsWafTaskRoute(task) === 'secondary'));
+ });
+
+ test(`${build}: AWS SDK fallback and its reservation work when CapMonster is first`, async t => {
+ const f = fixture(t, { fallback: true });
+ Object.assign(f.observed, { apiKey: 'sdk-key', jsapiScript: 'https://site.captcha-sdk.awswaf.com/jsapi.js', existingToken: 'old-cookie' });
+ const get = f.api.storage.local.get;
+ f.api.storage.local.get = async () => ({ ...await get(), capmonsterWeight: 200 });
+ const result = await f.agent._executeToolImpl(1, 'solve_captcha', {});
+ assert.equal(result.success, true, result.error);
+ assert.equal(result.provider, 'capmonster');
+ assert.equal(f.requests[0].task.websiteKey, 'sdk-key');
+ assert.equal(f.requests[0].task.captchaScript, f.observed.jsapiScript);
+ assert.equal(f.requests[0].task.iv, undefined);
+ assert.deepEqual(f.agent._conversationStorageEntry(1).nativeCaptchaDispatch.awsAttempts, ['secondary:capmonster']);
+ const restored = new Agent({ getActive: () => ({ promptTier: 'full' }) });
+ await restored._hydrate(1);
+ assert.equal((await restored._executeToolImpl(1, 'solve_captcha', {})).noDispatch, true);
+ assert.equal(f.requests.length, 1);
});
test(`${build}: AWS auto route applies a cookie once and survives a reload without recharging the same provider`, async t => {
diff --git a/test/captcha-documented-contracts.mjs b/test/captcha-documented-contracts.mjs
new file mode 100644
index 000000000..57fbe9d06
--- /dev/null
+++ b/test/captcha-documented-contracts.mjs
@@ -0,0 +1,164 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+
+// Fixtures transcribed from the linked provider contracts, with placeholder
+// values. No API keys, real challenges, or paid requests are used in this suite.
+const websiteURL = 'https://example.test/challenge';
+const challengeScript = 'https://example.token.awswaf.com/challenge.js';
+const providers = ids => ids.map(id => ({ id, apiKey: `fixture-${id}` }));
+function mockApi(t, replies) {
+ const calls = [];
+ t.mock.method(globalThis, 'setTimeout', fn => { queueMicrotask(fn); return 0; });
+ t.mock.method(globalThis, 'fetch', async (url, options = {}) => {
+ calls.push({ url: String(url), body: options.body instanceof URLSearchParams
+ ? Object.fromEntries(options.body) : options.body ? JSON.parse(options.body) : null });
+ assert.ok(replies.length, 'Unexpected provider request');
+ return Response.json(replies.shift());
+ });
+ return calls;
+}
+
+for (const browser of ['chrome', 'firefox']) {
+ const native = await import(`../src/${browser}/src/agent/captcha-native-providers.js`);
+ const solver = await import(`../src/${browser}/src/agent/captcha-solver.js`);
+
+ test(`${browser}: CapSolver does not report a malformed balance as zero credits`, async t => {
+ mockApi(t, [{ errorId: 0 }, { errorId: 0, balance: null }, { errorId: 0, balance: 'bad' }, { errorId: 0, balance: 0 }]);
+ for (let i = 0; i < 3; i++) await assert.rejects(solver.getBalance('fixture-key'), /missing balance/);
+ assert.deepEqual(await solver.getBalance('fixture-key'), { balance: 0, packages: [] });
+ });
+
+ // CapMonster Option 1 and Anti-Captcha's Widget tab use the renderCaptcha
+ // API key, not gokuProps.key. Both return cookies usable by this integration.
+ test(`${browser}: AWS SDK fallback uses all three documented cookie providers`, async t => {
+ const enabled = providers(['capsolver', 'capmonster', 'anti-captcha']);
+ const observed = { pageUrl: websiteURL, apiKey: 'sdk-api-key', jsapiScript: 'https://example.captcha-sdk.awswaf.com/jsapi.js',
+ existingToken: 'existing-cookie', websiteKey: 'stale-goku-key', iv: 'stale-iv', context: 'stale-context' };
+ const entries = native.buildAwsWafProviderTasks(enabled, observed);
+ const prepared = native.prepareNativeCaptchaTasks(enabled, entries);
+ const calls = mockApi(t, [{ errorId: 1, errorCode: 'ERROR_CAPTCHA_UNSOLVABLE' },
+ { errorId: 1, errorCode: 'ERROR_CAPTCHA_UNSOLVABLE' },
+ { errorId: 0, status: 'ready', solution: { token: 'aws-cookie' } }]);
+ const result = await native.solveNativeCaptchaTasks(prepared);
+ assert.equal(result.provider, 'anti-captcha');
+ assert.deepEqual(calls[1].body.task, { type: 'AmazonTask', websiteURL, websiteKey: 'sdk-api-key', captchaScript: observed.jsapiScript, cookieSolution: true });
+ assert.deepEqual(calls[2].body.task, { type: 'AmazonTaskProxyless', wafType: 'widget', websiteURL, websiteKey: 'sdk-api-key', jsapiScript: observed.jsapiScript });
+ const noCookie = native.buildAwsWafProviderTasks(enabled, { ...observed, existingToken: null });
+ assert.deepEqual(noCookie.map(e => e.provider), ['capsolver', 'capmonster', 'anti-captcha']);
+ assert.deepEqual(noCookie[0].parameters, { websiteURL, awsApiJs: observed.jsapiScript });
+ assert.equal(native.prepareNativeCaptchaTasks(enabled, noCookie).length, 3);
+ for (const key of ['websiteKey', 'jsapiScript']) {
+ const bad = structuredClone(entries);
+ bad[2].parameters[key] = 'different-challenge';
+ assert.throws(() => native.prepareNativeCaptchaTasks(enabled, bad), /same observed challenge/);
+ }
+ const mixed = native.buildAwsWafProviderTasks(enabled, { pageUrl: websiteURL, websiteKey: 'key', iv: 'iv', context: 'context', challengeScript });
+ assert.throws(() => native.prepareNativeCaptchaTasks(enabled, [entries[0], mixed[1]]), /same observed challenge mode/);
+ });
+
+ // https://2captcha.com/api-docs/geetest — riskType is case sensitive.
+ test(`${browser}: 2Captcha GeeTest sends the documented riskType spelling`, async t => {
+ const calls = mockApi(t, [{ errorId: 0, taskId: 123 }, {
+ errorId: 0, status: 'ready', solution: { captcha_id: 'captcha', lot_number: 'lot', pass_token: 'pass', gen_time: '1', captcha_output: 'output' },
+ }]);
+ const parameters = { websiteURL, version: 4, initParameters: { captcha_id: 'captcha' }, riskType: 'slide' };
+ const result = await native.solveNativeCaptchaTasks(native.prepareNativeCaptchaTasks(providers(['2captcha']), [
+ { provider: '2captcha', method: 'GeeTestTaskProxyless', parameters },
+ ]));
+ assert.deepEqual(calls[0].body.task, { ...parameters, type: 'GeeTestTaskProxyless' });
+ assert.equal(result.solution.pass_token, 'pass');
+ assert.throws(() => native.buildNativeCaptchaTask({ provider: '2captcha', method: 'GeeTestTaskProxyless',
+ parameters: { ...parameters, risk_type: 'slide' } }), /undocumented field risk_type/);
+ });
+
+ // https://docs.capmonster.cloud/docs/captchas/amazon-task/ — Option 3.
+ test(`${browser}: invisible AWS challenge reaches CapMonster after CapSolver fails`, async t => {
+ const enabled = providers(['capsolver', 'capmonster']);
+ const entries = native.buildAwsWafProviderTasks(enabled, { pageUrl: websiteURL, challengeScript });
+ assert.deepEqual(entries[1], { provider: 'capmonster', method: 'AmazonTask:3', parameters: {
+ websiteURL, challengeScript, iv: '', context: '', cookieSolution: true,
+ } });
+ const calls = mockApi(t, [{ errorId: 1, errorCode: 'ERROR_CAPTCHA_UNSOLVABLE' },
+ { errorId: 0, taskId: 456 }, { errorId: 0, status: 'ready', solution: { cookies: { 'aws-waf-token': 'cookie' } } }]);
+ const result = await native.solveNativeCaptchaTasks(native.prepareNativeCaptchaTasks(enabled, entries));
+ assert.equal(result.provider, 'capmonster');
+ assert.deepEqual(calls[1].body.task, { type: 'AmazonTask', websiteURL, challengeScript, iv: '', context: '', cookieSolution: true });
+ for (const partial of [{ iv: 'partial' }, { websiteKey: 'partial' }, { context: 'partial' }, { captchaScript: 'https://captcha.test/captcha.js' }]) {
+ assert.ok(!native.buildAwsWafProviderTasks(enabled, { pageUrl: websiteURL, challengeScript, ...partial }).some(e => e.method === 'AmazonTask:3'));
+ }
+ assert.throws(() => native.buildNativeCaptchaTask({ provider: 'capmonster', method: 'AmazonTask:2',
+ parameters: { websiteURL, websiteKey: 'key', challengeScript, iv: '', context: '' } }), /cannot be empty/);
+ });
+
+ for (const cookieSolution of [undefined, false]) test(`${browser}: CapMonster native AWS voucher (${cookieSolution}) stops fallback`, async t => {
+ const solution = { existingToken: 'existing', captchaVoucher: 'voucher' };
+ const calls = mockApi(t, [{ errorId: 0, status: 'ready', solution }]);
+ const enabled = providers(['capmonster', 'anti-captcha']);
+ const common = { websiteURL, websiteKey: 'key', iv: 'iv', context: 'context', challengeScript };
+ const result = await native.solveNativeCaptchaTasks(native.prepareNativeCaptchaTasks(enabled, [
+ { provider: 'capmonster', method: 'AmazonTask:2', parameters: { ...common, ...(cookieSolution === undefined ? {} : { cookieSolution }) } },
+ { provider: 'anti-captcha', method: 'AmazonTaskProxyless', parameters: common },
+ ]));
+ assert.equal(calls.length, 1);
+ assert.deepEqual(result.solution, solution);
+ assert.equal(result.provider, 'capmonster');
+ });
+
+ for (const invalidCookie of ['', 'aws-waf-token=; Path=/', 0, null]) test(`${browser}: empty/malformed AWS cookie ${JSON.stringify(invalidCookie)} falls back`, async t => {
+ const calls = mockApi(t, [{ errorId: 0, status: 'ready', solution: { cookies: { 'aws-waf-token': invalidCookie } } },
+ { errorId: 0, status: 'ready', solution: { token: 'usable-cookie' } }]);
+ const enabled = providers(['capmonster', 'anti-captcha']);
+ const entries = native.buildAwsWafProviderTasks(enabled, { pageUrl: websiteURL, websiteKey: 'key', iv: 'iv', context: 'context', challengeScript });
+ const result = await native.solveNativeCaptchaTasks(native.prepareNativeCaptchaTasks(enabled, entries));
+ assert.equal(result.provider, 'anti-captcha');
+ assert.equal(calls.length, 2);
+ });
+
+ // https://solvecaptcha.com/captcha-solver-api — Temu/VK result examples
+ // use ready/solution while the established API uses numeric status/request.
+ for (const method of ['temuimage', 'vkimage']) test(`${browser}: SolveCaptcha ${method} preserves its structured ready answer`, async t => {
+ const solution = method === 'temuimage' ? { coordinates: [{ x: 155, y: 358 }] } : { best_step: 19 };
+ const calls = mockApi(t, [{ status: 1, request: '789' }, { status: 0, request: 'CAPCHA_NOT_READY' },
+ { errorId: 0, status: 'ready', solution }]);
+ const parameters = method === 'temuimage' ? { body: 'image', part1: 'one', part2: 'two', part3: 'three' } : { body: 'image', steps: '[5,19]' };
+ const result = await native.solveNativeCaptchaTasks(native.prepareNativeCaptchaTasks(providers(['solvecaptcha']), [
+ { provider: 'solvecaptcha', method, parameters },
+ ]));
+ assert.equal(calls.length, 3);
+ assert.deepEqual(result.solution, solution);
+ assert.equal(result.taskId, '789');
+ assert.equal(calls[0].body.method, method);
+ });
+
+ // https://docs.capsolver.com/en/guide/captcha/cloudflare_turnstile/
+ // https://docs.capmonster.cloud/docs/captchas/turnstile-task/
+ test(`${browser}: Cloudflare Challenge goes only to a compatible automatic provider`, async t => {
+ const calls = mockApi(t, [{ errorId: 0, status: 'ready', solution: { token: 'answer' } }]);
+ const result = await solver.solveCaptchaWithProviders(providers(['capsolver', 'capmonster']), {
+ type: 'turnstile', websiteURL, websiteKey: 'key', userAgent: 'browser-UA',
+ metadata: { action: 'managed', cdata: 'cdata', chlPageData: 'page-data' },
+ });
+ assert.equal(result.provider, 'capmonster');
+ assert.equal(calls.length, 1);
+ assert.match(calls[0].url, /api.capmonster.cloud/);
+ assert.deepEqual(calls[0].body.task, { type: 'TurnstileTask', websiteURL, websiteKey: 'key', userAgent: 'browser-UA',
+ data: 'cdata', pageAction: 'managed', pageData: 'page-data', cloudflareTaskType: 'token' });
+ });
+
+ test(`${browser}: incomplete Challenge metadata is never downgraded to standalone Turnstile`, async t => {
+ const calls = mockApi(t, []);
+ await assert.rejects(solver.solveCaptchaWithProviders(providers(['capsolver', 'capmonster']), {
+ type: 'turnstile', websiteURL, websiteKey: 'key', metadata: { chlPageData: 'page-data' },
+ }), /requires action, data, pageData/);
+ assert.equal(calls.length, 0);
+ });
+
+ // https://docs.capsolver.com/en/guide/api-gettaskresult/
+ test(`${browser}: unexpected CapSolver poll status advances fallback without repeated polls`, async t => {
+ const calls = mockApi(t, [{ errorId: 0, taskId: 'id' }, { errorId: 0, status: 'unknown' },
+ { errorId: 0, status: 'ready', solution: { gRecaptchaResponse: 'answer' } }]);
+ const result = await solver.solveCaptchaWithProviders(providers(['capsolver', '2captcha']), { type: 'recaptcha_v2', websiteURL, websiteKey: 'key' });
+ assert.equal(result.provider, '2captcha');
+ assert.equal(calls.length, 3);
+ });
+}
diff --git a/test/captcha-native-providers.mjs b/test/captcha-native-providers.mjs
index 8740b3243..e498e3b57 100644
--- a/test/captcha-native-providers.mjs
+++ b/test/captcha-native-providers.mjs
@@ -93,7 +93,7 @@ for (const browser of ['chrome','firefox']) {
}
});
test(`${browser}: catalogs cover seven vendors without resurrecting draft hCaptcha methods`,()=>{
- assert.equal(catalog.length,197);
+ assert.equal(catalog.length,198);
for(const provider of providers) assert.ok(catalog.some(c=>c.provider===provider.id));
assert.deepEqual([...new Set(catalog.filter(c=>c.family==='hcaptcha').map(c=>c.provider))].sort(),['nonecap','nopecha']);
const cm=new Set(catalog.filter(c=>c.provider==='capmonster').map(c=>c.family));
@@ -368,12 +368,12 @@ for (const browser of ['chrome', 'firefox']) {
return { url };
},
executeScript: async (_tabId, options) => {
- if (/false\]\)$/.test(options.code)) pageMutations++;
+ if (/false,null\]\)$/.test(options.code)) pageMutations++;
return [{ success: true }];
},
},
scripting: browser === 'chrome' ? { executeScript: async options => {
- if (options.args.at(-1) === false) pageMutations++;
+ if (options.args[5] === false) pageMutations++;
return [{ frameId: 0, result: { success: true } }];
} } : undefined,
webNavigation: { getAllFrames: async () => [{ frameId: 0, url }] },
@@ -563,11 +563,11 @@ for (const browser of ['chrome', 'firefox']) {
websiteURL: url, captchaId: 'captcha', riskType: 'slide',
} };
const twoCaptcha = { provider: '2captcha', method: 'GeeTestTaskProxyless', parameters: {
- websiteURL: url, version: 4, initParameters: { captcha_id: 'captcha' }, risk_type: 'slide',
+ websiteURL: url, version: 4, initParameters: { captcha_id: 'captcha' }, riskType: 'slide',
} };
assert.equal(native.prepareNativeCaptchaTasks(enabled, [capsolver, twoCaptcha]).length, 2);
assert.throws(() => native.prepareNativeCaptchaTasks(enabled, [capsolver, {
- ...twoCaptcha, parameters: { ...twoCaptcha.parameters, risk_type: 'match' },
+ ...twoCaptcha, parameters: { ...twoCaptcha.parameters, riskType: 'match' },
}]), /same observed challenge/);
assert.throws(() => native.prepareNativeCaptchaTasks(enabled, [capsolver, {
...twoCaptcha, parameters: { websiteURL: url, version: 4, initParameters: { captcha_id: 'captcha' } },
diff --git a/test/captcha-runtime-policy.mjs b/test/captcha-runtime-policy.mjs
index 24c9d382c..ae702bccb 100644
--- a/test/captcha-runtime-policy.mjs
+++ b/test/captcha-runtime-policy.mjs
@@ -67,7 +67,7 @@ for (const build of ['chrome', 'firefox']) {
t.after(() => { if (previous === undefined) delete globalThis[apiName]; else globalThis[apiName] = previous; });
return payload;
}
- function automaticSolveFixture(t, { type = 'hcaptcha', injectionSucceeds = true, providerFails = false } = {}) {
+ function automaticSolveFixture(t, { type = 'hcaptcha', injectionSucceeds = true, providerFails = false, provider = type === 'hcaptcha' ? 'nonecap' : '2captcha', solverUserAgent } = {}) {
const pageUrl = 'https://example.test/join';
const widget = { type, frameUrl: pageUrl, websiteKey: '5bd005a4-6ac8-4a86-8e60-53083832ed22',
visible: true, activeChallengeFrame: true, activeChallengeFrameVisible: true,
@@ -77,11 +77,11 @@ for (const build of ['chrome', 'firefox']) {
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.captchaProviderIds = [provider];
agent.conversations.set(1, [{ role: 'system', content: 'test' }]);
const stored = {};
api.storage = {
- local: { get: async () => type === 'hcaptcha'
+ local: { get: async () => provider === 'capmonster' ? { capmonsterEnabled: true, capmonsterApiKey: 'a'.repeat(32) } : 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)) },
@@ -108,14 +108,53 @@ for (const build of ['chrome', 'firefox']) {
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' }
+ return Response.json(type === 'hcaptcha' ? { id: 'paid-task', status: 'solved', token: 'paid-token', ...(solverUserAgent ? { user_agent: solverUserAgent } : {}) }
: url.endsWith('/createTask') ? { taskId: 123 }
- : { status: 'ready', solution: { gRecaptchaResponse: 'paid-token', token: 'paid-token' } });
+ : { status: 'ready', solution: { gRecaptchaResponse: 'paid-token', token: 'paid-token', ...(solverUserAgent ? { userAgent: solverUserAgent } : {}) } });
});
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 };
}
+ test(`${build}: local Challenge schema rejection does not consume a paid attempt`, async t => {
+ const f = automaticSolveFixture(t, { type: 'turnstile' });
+ f.widget.metadata = { chlPageData: 'observed-page-data' };
+ f.api.storage.local.get = async () => ({ captchaSolverEnabled: true, capsolverApiKey: 'CAP-' + 'a'.repeat(32),
+ capmonsterEnabled: true, capmonsterApiKey: 'b'.repeat(32) });
+ const rejected = await f.agent._executeToolImpl(1, 'solve_captcha', { type: 'turnstile' });
+ assert.equal(rejected.noDispatch, true, rejected.error);
+ assert.equal(rejected.dispatched, false);
+ assert.equal(f.requests.length, 0);
+ assert.equal(f.agent._captchaGateStates.get(1)?.publicGate.solveAttempted, undefined);
+ f.widget.metadata = { action: 'managed', cdata: 'observed-cdata', chlPageData: 'observed-page-data' };
+ const solved = await f.agent._executeToolImpl(1, 'solve_captcha', { type: 'turnstile' });
+ assert.equal(solved.provider, 'capmonster', solved.error);
+ assert.equal(solved.injected, true);
+ });
+
+ for (const [provider, type] of [['nonecap', 'hcaptcha'], ['capmonster', 'recaptcha_v3']]) {
+ for (const solverUserAgent of ['different-browser', 'test-browser']) {
+ test(`${build}: ${provider} enforces the returned User-Agent and retains a mismatched paid answer`, async t => {
+ const f = automaticSolveFixture(t, { provider, type, solverUserAgent });
+ const result = await f.agent._executeToolImpl(1, 'solve_captcha', { type, ...(type === 'recaptcha_v3' ? { pageAction: 'login' } : {}) });
+ assert.equal(result.injected, solverUserAgent === 'test-browser', result.error);
+ const record = f.agent._nativeCaptchaSolutions.get(1);
+ assert.equal(record.applied, solverUserAgent === 'test-browser');
+ if (solverUserAgent !== 'test-browser') {
+ assert.equal(result.manualCompletionRequired, true);
+ assert.equal(result.token, 'paid-token');
+ assert.equal(record.solution.userAgent, solverUserAgent);
+ const restored = agentFor('act', 'full');
+ await restored._hydrate(1);
+ const discovery = await restored._executeToolImpl(1, 'get_captcha_capabilities', {});
+ assert.equal(discovery.pendingNativeAnswer.solution.userAgent, solverUserAgent);
+ } else assert.equal(result.applicationRequired, undefined);
+ const count = f.requests.length;
+ assert.equal((await f.agent._executeToolImpl(1, 'solve_captcha', { type })).noDispatch, true);
+ assert.equal(f.requests.length, count);
+ });
+ }
+ }
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 });
diff --git a/test/captcha-weighted-fallback.mjs b/test/captcha-weighted-fallback.mjs
index e70e8d4ad..01bc081d7 100644
--- a/test/captcha-weighted-fallback.mjs
+++ b/test/captcha-weighted-fallback.mjs
@@ -3,7 +3,7 @@ import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
const key = '0123456789abcdef0123456789abcdef';
-const params = { type: 'turnstile', websiteURL: 'https://example.com/form', websiteKey: 'widget', metadata: { action: 'managed', cdata: 'data', chlPageData: 'page-data' } };
+const params = { type: 'turnstile', websiteURL: 'https://example.com/form', websiteKey: 'widget', metadata: { action: 'managed', cdata: 'data' } };
function api(t, respond) {
let now = 0;
const calls = [];
@@ -59,11 +59,11 @@ for (const build of ['chrome', 'firefox']) {
});
test(`${build}: provider-specific mappings preserve enterprise and Turnstile metadata`, () => {
- const normalized = solver.buildTask(params);
+ const normalized = solver.buildTask({ ...params, metadata: { ...params.metadata, chlPageData: 'page-data' } });
const anti = extra.buildAdditionalCaptchaTask('anti-captcha', normalized);
assert.deepEqual(anti, { type: 'TurnstileTaskProxyless', websiteURL: params.websiteURL, websiteKey: 'widget', action: 'managed', cData: 'data', chlPageData: 'page-data' });
- const monster = extra.buildAdditionalCaptchaTask('capmonster', normalized);
- // Challenge mode requires userAgent; without it CapMonster gets the plain task.
+ assert.throws(() => extra.buildAdditionalCaptchaTask('capmonster', normalized), /requires action, data, pageData/);
+ const monster = extra.buildAdditionalCaptchaTask('capmonster', solver.buildTask(params));
assert.deepEqual(monster, { type: 'TurnstileTask', websiteURL: params.websiteURL, websiteKey: 'widget', data: 'data', pageAction: 'managed' });
const monsterChallenge = extra.buildAdditionalCaptchaTask('capmonster', { ...normalized, userAgent: 'UA' });
assert.deepEqual(monsterChallenge, { type: 'TurnstileTask', websiteURL: params.websiteURL, websiteKey: 'widget', data: 'data', pageAction: 'managed', userAgent: 'UA', pageData: 'page-data', cloudflareTaskType: 'token' });
diff --git a/test/huggingface-signup-recovery.mjs b/test/huggingface-signup-recovery.mjs
new file mode 100644
index 000000000..3a28cfc07
--- /dev/null
+++ b/test/huggingface-signup-recovery.mjs
@@ -0,0 +1,194 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { readFile } from 'node:fs/promises';
+
+const url = 'https://huggingface.co/join';
+const credentials = 'textbox "Email Address" [email] field_name="email"\ntextbox "Password" [password] field_name="password"';
+const profile = 'textbox "Username" [username] field_name="username"\ntextbox "Full name" [fullname] field_name="fullname"';
+
+for (const build of ['chrome', 'firefox']) {
+ const { advanceHuggingFaceSignupRecovery: advance, normalizeHuggingFaceSignupRecovery: normalize,
+ huggingFaceSignupRecoveryNote: note, huggingFaceSignupUrl } = await import(`../src/${build}/src/agent/huggingface-signup-recovery.js`);
+ const { Agent } = await import(`../src/${build}/src/agent/agent.js`);
+ const { getActiveAdapter } = await import(`../src/${build}/src/agent/adapters.js`);
+ function flow() {
+ let state = null;
+ const step = (name, args = {}, result = {}, extra = {}) => {
+ state = advance(state, { url, taskKey: 'task-1', name, args, result, ...extra });
+ return state;
+ };
+ const read = (pageContent, extra = {}, args = { filter: 'visible' }) => step('get_accessibility_tree', args, { pageContent }, extra);
+ return { step, read, state: () => state };
+ }
+ const fillProfile = f => {
+ f.read(profile);
+ f.step('set_field', { text: 'private profile value' }, { success: true, verified: true, fieldMeta: { name: 'username' } });
+ f.step('upload_file', { downloadId: 1971, filePath: '/private/avatar.webp', selector: '#old-input' },
+ { success: true, attachmentState: 'input_attached' });
+ f.step('click_ax', {}, { success: true }, { submitted: true });
+ };
+
+ test(`${build}: signup recovery is confined to actual Hugging Face signup URLs`, () => {
+ assert.equal(huggingFaceSignupUrl(url + '?next=/settings'), url);
+ assert.equal(huggingFaceSignupUrl('https://www.huggingface.co/join/'), 'https://www.huggingface.co/join');
+ for (const value of ['https://huggingface.co.evil.test/join', 'https://evil.test/?next=https://huggingface.co/join',
+ 'https://huggingface.co/settings/profile', 'https://huggingface.co/me', 'https://huggingface.co/model/upload/main',
+ 'https://huggingface.co:8443/join', 'https://[email protected]/join', 'not a URL']) {
+ assert.equal(huggingFaceSignupUrl(value), '', value);
+ assert.equal(advance(null, { url: value, taskKey: 'task', name: 'get_accessibility_tree', args: { filter: 'visible' }, result: { pageContent: profile } }), null);
+ }
+ });
+
+ test(`${build}: challenge-free signup never receives recovery or reload instructions`, () => {
+ const f = flow();
+ assert.equal(note(f.read(credentials)), '');
+ fillProfile(f);
+ assert.equal(note(f.state()), '');
+ assert.equal(note(f.read('paragraph "CAPTCHA, human verification, country, name"\n' + credentials)), '');
+ assert.equal(f.state().recovering, false);
+ assert.equal(f.state().interrupted, false);
+ });
+
+ test(`${build}: observed CAPTCHA followed by a preserved form does not restart signup`, () => {
+ const f = flow(); fillProfile(f);
+ f.read('heading "Human verification"', { gate: { status: 'solve_required', selectedType: 'hcaptcha' } });
+ assert.equal(f.state().interrupted, true);
+ f.step('solve_captcha', { type: 'hcaptcha' }, { success: true }, { gate: { status: 'verification_pending' } });
+ assert.match(note(f.state()), /Only perform a recovery reload when the runtime explicitly requests it/);
+ f.read(profile, { gate: { status: 'cleared' } });
+ assert.equal(f.state().recovering, false);
+ assert.match(note(f.state()), /continue the existing form/);
+ assert.match(note(f.state()), /Do not restart signup or reload/);
+ });
+
+ test(`${build}: hCaptcha then AWS and a confirmed reset retain the profile checkpoint`, () => {
+ const f = flow(); fillProfile(f);
+ f.step('solve_captcha', { type: 'hcaptcha' }, { success: true }, { gate: { status: 'verification_pending' } });
+ f.read('heading "Let us confirm you are human"', { gate: { status: 'cleared' } });
+ f.step('solve_captcha', { type: 'aws_waf' }, { success: true, cookiesUpdated: 1 }, { gate: { status: 'verification_pending' } });
+ f.step('navigate', { url }, { success: true });
+ assert.equal(f.state().recovering, false, 'navigation alone cannot prove a reset');
+ f.read(credentials, { gate: { status: 'cleared' } });
+ assert.equal(f.state().recovering, true);
+ assert.deepEqual(f.state().fields, ['username']);
+ assert.deepEqual(f.state().avatar, { downloadId: 1971 });
+ assert.match(note(f.state()), /Earlier Create Account|earlier Create Account/);
+ assert.match(note(f.state()), /reconcile any signed-in, verification-pending, or already-registered evidence/);
+ assert.match(note(f.state()), /restore only missing requested details/);
+ assert.doesNotMatch(JSON.stringify(f.state()), /private profile value|private\/avatar|old-input/);
+ f.read(profile);
+ assert.equal(f.state().stage, 'profile');
+ assert.match(note(f.state()), /reattach the original avatar only if absent/);
+ assert.equal(f.step('navigate', {}, { success: true }, { url: 'https://huggingface.co/settings/profile' }), null);
+ });
+
+ test(`${build}: manual verification can resume, while scoped or failed reads cannot prove a reset`, () => {
+ const f = flow(); fillProfile(f);
+ f.read('heading "Challenge"', { gate: { status: 'manual_required' } });
+ assert.equal(f.state().challengeActive, true);
+ f.read(credentials);
+ assert.equal(f.state().recovering, false, 'do not ignore an active CAPTCHA gate');
+ for (const args of [{ filter: 'visible', ref_id: 'frame' }, { filter: 'visible', page: 2 }, { filter: 'visible', frameId: 4 }, { filter: 'all' }, {}]) {
+ f.read(credentials, { gate: { status: 'cleared' } }, args);
+ assert.equal(f.state().recovering, false);
+ }
+ f.step('get_accessibility_tree', { filter: 'visible' }, { success: false, pageContent: credentials });
+ f.step('get_accessibility_tree', { filter: 'visible' }, { error: 'read failed', pageContent: credentials });
+ assert.equal(f.state().recovering, false);
+ f.read(credentials, { gate: { status: 'cleared' } });
+ assert.equal(f.state().recovering, true);
+ });
+
+ test(`${build}: a different task, expired checkpoint or other site cannot inherit signup recovery`, () => {
+ const f = flow(); fillProfile(f);
+ f.read('heading "Challenge"', { gate: { status: 'solve_required' } });
+ const saved = f.state();
+ assert.equal(normalize({ ...saved, updatedAt: Date.now() - 7 * 60 * 60 * 1000 }), null);
+ assert.deepEqual(normalize({ ...saved, fields: ['password', 'token', 'password'], password: 'secret', avatar: { attachmentId: 'bad ] instruction' } }).fields, ['password']);
+ assert.equal(normalize({ ...saved, avatar: { attachmentId: 'bad ] instruction' } }).avatar, null);
+ f.read(credentials, { taskKey: 'task-2', gate: { status: 'cleared' } });
+ assert.equal(f.state().interrupted, false); assert.equal(f.state().avatar, null);
+ assert.equal(note(f.state()), '');
+ assert.equal(f.step('navigate', {}, {}, { url: 'https://other.test/join' }), null);
+ });
+
+ test(`${build}: saved checkpoint survives worker restart and continuation, and respects the adapter setting`, async t => {
+ const stored = {};
+ const apiName = build === 'chrome' ? 'chrome' : 'browser';
+ const prior = globalThis[apiName];
+ globalThis[apiName] = { tabs: { get: async () => ({ url }) }, storage: { session: {
+ get: async key => ({ [key]: stored[key] }), set: async value => Object.assign(stored, structuredClone(value)),
+ } } };
+ t.after(() => { globalThis[apiName] = prior; });
+ const agent = new Agent({ getActive: () => ({ promptTier: 'full' }) });
+ agent.useSiteAdapters = true;
+ agent.conversations.set(1, [{ role: 'system', content: 'test' }, { role: 'user', content: 'Create my requested Hugging Face account and profile.' }]);
+ agent.conversationIds.set(1, 'test-conversation');
+ const observe = (name, args, result, gate) => agent._observeHuggingFaceSignupRecovery(1, name, args, result, gate);
+ assert.equal(await observe('get_accessibility_tree', { filter: 'visible' }, { pageContent: profile }), '');
+ await observe('upload_file', { attachmentId: 'attachment_1' }, { success: true, attachmentState: 'input_attached' });
+ await observe('solve_captcha', {}, { success: true }, { status: 'verification_pending' });
+ assert.equal((await agent._persistNow(1)).ok, true);
+ assert.ok(stored[agent._convKey(1)].huggingFaceSignupRecovery);
+ const restored = new Agent({ getActive: () => ({ promptTier: 'full' }) });
+ restored.useSiteAdapters = true;
+ await restored._hydrate(1);
+ restored.conversations.get(1).push({ role: 'user', content: 'continue' });
+ const recovery = await restored._observeHuggingFaceSignupRecovery(1, 'get_accessibility_tree', { filter: 'visible' }, { pageContent: credentials }, { status: 'cleared' });
+ assert.match(recovery, /returned to the credentials step/);
+ assert.match(recovery, /attachment_1/);
+ restored.useSiteAdapters = false;
+ assert.equal(await restored._observeHuggingFaceSignupRecovery(1, 'get_accessibility_tree', { filter: 'visible' }, { pageContent: credentials }), '');
+ assert.equal(restored._huggingFaceSignupRecoveries.has(1), false);
+ });
+
+ test(`${build}: a CAPTCHA preflight interruption reaches the model again after manual recovery`, async () => {
+ const agent = new Agent({ getActive: () => ({ promptTier: 'full' }) });
+ agent.useSiteAdapters = true;
+ agent.conversationModes.set(1, 'act');
+ agent._persist = () => {};
+ agent._ensureGateSetting = async () => {};
+ agent._skipPermissionGate = true;
+ agent._currentUrl = async () => url;
+ const messages = [{ role: 'system', content: 'test' }, { role: 'user', content: 'Create my requested Hugging Face account and profile.' }];
+ agent.conversations.set(1, messages);
+ await agent._observeHuggingFaceSignupRecovery(1, 'get_accessibility_tree', { filter: 'visible' }, { pageContent: profile });
+ agent._captchaMutationPreflight = async () => {
+ const publicGate = { status: 'manual_required' };
+ agent._captchaGateStates.set(1, { key: url + '\nchallenge', pageUrl: url, status: 'manual_required', publicGate });
+ return publicGate;
+ };
+ const call = (name, args) => agent._executeToolBatch(1, [{ id: name, function: { name, arguments: JSON.stringify(args) } }],
+ messages, () => {}, { supportsVision: false }, '', new Set([name]), 1);
+ const blocked = await call('click_ax', { ref_id: 'create-account' });
+ assert.equal(blocked.status, 'captcha_manual_required');
+ assert.equal(agent._huggingFaceSignupRecoveries.get(1).interrupted, true);
+ assert.match(messages.find(m => m.tool_call_id === 'click_ax').content, /HUGGING FACE SIGNUP RECOVERY/);
+ // A fresh read confirms manual completion and the returned credentials
+ // form. Exercise the real batch hook and model-visible result, not only
+ // the pure checkpoint helper.
+ agent._captchaMutationPreflight = async () => null;
+ agent._observeCaptchaChallenge = async () => {
+ agent._captchaGateStates.delete(1);
+ return { gate: { status: 'cleared' }, loopCheck: { kind: 'none' } };
+ };
+ agent.executeTool = async () => ({ pageUrl: url, pageContent: credentials });
+ const resumed = await call('get_accessibility_tree', { filter: 'visible' });
+ assert.equal(resumed.action, 'continue');
+ assert.match(messages.find(m => m.tool_call_id === 'get_accessibility_tree').content, /returned to the credentials step/);
+ });
+
+ test(`${build}: Hugging Face adapter keeps upload guidance and conditional signup within eight bullets`, () => {
+ const adapter = getActiveAdapter(url);
+ assert.equal(adapter.name, 'huggingface');
+ assert.equal(adapter.notes.split('\n').filter(line => line.startsWith('- ')).length, 8);
+ assert.match(adapter.notes, /never assume one from a person's name, country, IP, or geography/);
+ assert.match(adapter.notes, /Only when an actual CAPTCHA interrupts signup/);
+ assert.match(adapter.notes, /A filename chip.*staged only/);
+ });
+}
+
+test('signup recovery implementation stays mirrored', async () => {
+ assert.equal(await readFile('src/chrome/src/agent/huggingface-signup-recovery.js', 'utf8'),
+ await readFile('src/firefox/src/agent/huggingface-signup-recovery.js', 'utf8'));
+});
diff --git a/test/run.js b/test/run.js
index 1f6f35e0b..6bee8e3a3 100644
--- a/test/run.js
+++ b/test/run.js
@@ -122481,7 +122481,9 @@ test('NoneCap hCaptcha token is not injected when its User-Agent differs from th
assert.equal(result.dispatched, true, build);
assert.equal(result.manualCompletionRequired, true, build);
assert.equal(result.injected, false, build);
- assert.equal(result.token, undefined, build);
+ assert.equal(result.token, 'paid-token', build);
+ assert.equal(agent._nativeCaptchaSolutions.get(1).solution.token, 'paid-token', build);
+ assert.equal(agent._nativeCaptchaSolutions.get(1).applied, false, build);
assert.match(result.error, /different User-Agent/, build);
assert.equal(injections, 0, build);
} finally { globalThis.fetch = originalFetch; }