diff --git a/.env.example b/.env.example index 98e8fe6..454884c 100644 --- a/.env.example +++ b/.env.example @@ -1,24 +1,24 @@ -CAPTCHA_API_KEY=your_api_key -# Blank uses an official provider demo for reCAPTCHA v2 and Yandex SmartCaptcha. -# Other examples require a URL. -TARGET_URL= +CAPTCHA_API_KEY=your_captcha_solver_api_key HEADLESS=false -# Blank uses the Chrome for Testing downloaded by Puppeteer. -BROWSER_EXECUTABLE_PATH= -# Optional overrides when using your own pages: -SUCCESS_SELECTOR= -SUBMIT_SELECTOR= -CALLBACK_NAME= -RECAPTCHA_SITEKEY= -RECAPTCHA_ACTION= -RECAPTCHA_MIN_SCORE=0.3 -YANDEX_SUCCESS_TEXT=Hello, user! -# Required for Tencent except the trigger, which can stay blank if the page opens it automatically. -TENCENT_TRIGGER_SELECTOR= -TENCENT_SUCCESS_SELECTOR= -# Required only for the two *_proxy.js examples; no default public proxy. +# Before running, set the matching *_TARGET_URL to the page you want to test. +# Replace example.com placeholders with your own URL; these pages do not contain CAPTCHA demos. +# Use a public demo or a page you own or are authorized to test. +RECAPTCHA_V2_TARGET_URL=https://www.google.com/recaptcha/api2/demo +# Required only by callback examples when the page does not use the default callback name. +RECAPTCHA_V2_CALLBACK=verifyDemoRecaptcha +# Proxy examples require the address and port. Credentials are optional. PROXY_TYPE=http PROXY_ADDRESS= PROXY_PORT= PROXY_LOGIN= PROXY_PASSWORD= +RECAPTCHA_ENTERPRISE_TARGET_URL=https://example.com/page_with_recaptcha_v2_enterprise +RECAPTCHA_V3_TARGET_URL=https://example.com/page_with_recaptcha_v3 +TURNSTILE_TARGET_URL=https://example.com/page_with_turnstile +TURNSTILE_CHALLENGE_TARGET_URL=https://example.com/page_with_turnstile_challenge +YANDEX_TARGET_URL=https://captcha-api.yandex.ru/demo +TENCENT_TARGET_URL=https://example.com/page_with_tencent_captcha +# Optional: set this when the Tencent script URL cannot be captured from the page. +TENCENT_SCRIPT_URL= +GEETEST_V3_TARGET_URL=https://example.com/page_with_geetest_v3 +GEETEST_V4_TARGET_URL=https://example.com/page_with_geetest_v4 diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 17022e7..cee04c7 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -5,24 +5,16 @@ on: permissions: contents: read jobs: - lint: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v5 - - uses: actions/setup-node@v6 - with: - node-version: '22.12' - cache: npm - - run: npm ci - - run: npm run lint test: runs-on: ubuntu-latest + strategy: + matrix: + node-version: ['22.12', '24'] steps: - uses: actions/checkout@v5 - uses: actions/setup-node@v6 with: - node-version: '22.12' + node-version: ${{ matrix.node-version }} cache: npm - run: npm ci - - run: node scripts/check.js - - run: npm test + - run: npm run check diff --git a/.prettierrc.json b/.prettierrc.json new file mode 100644 index 0000000..554f2a3 --- /dev/null +++ b/.prettierrc.json @@ -0,0 +1,4 @@ +{ + "singleQuote": true, + "printWidth": 100 +} diff --git a/AGENTS.md b/AGENTS.md index e56cab0..f901550 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -3,10 +3,12 @@ - Use JavaScript ES modules and Node.js 22.12+. Browser automation uses Puppeteer. - Use `@captcha-solver-api/javascript-sdk` for CAPTCHA solving. Do not duplicate its HTTP client. - Keep API keys in environment variables or ignored `.env`; never commit keys or artifacts. -- Demo targets live in `config/demos.js`. Update `docs/TESTING.md` after live verification. +- Keep each demo target in its example so files in `examples/` remain standalone. Update + `docs/TESTING.md` after live verification. - Keep every example understandable on its own: show SDK setup, task creation, solving, result logging, browser injection, and acceptance verification. - Document every function with JSDoc and run `npm run lint` before committing. +- After changing JavaScript, run `npm run lint`; before committing, run `npm run check`. - `npm run check` and `npm test` must pass. Local tests must not call the paid API. - Live tests require explicit user authorization and use one attempt per example by default. - Confirm page acceptance; receiving an API token alone does not prove success. diff --git a/README.md b/README.md index 41028aa..2957697 100644 --- a/README.md +++ b/README.md @@ -1,24 +1,30 @@ -![Captcha Solver Puppeteer JavaScript Examples](assets/puppeteer-javascript-examples-banner.png) +# Captcha Solver Puppeteer JavaScript Examples -# Captcha solving examples with JavaScript and Puppeteer +![Captcha Solver Puppeteer JavaScript Examples](assets/puppeteer-javascript-examples-banner.png) Examples of solving popular captcha types with [`@captcha-solver-api/javascript-sdk`](https://www.npmjs.com/package/@captcha-solver-api/javascript-sdk) and [Puppeteer](https://pptr.dev/). -Each example shows how to: +Use the examples only on demo pages or websites you are authorized to test. + +> [!IMPORTANT] +> Live examples create paid CAPTCHA tasks. Run them only with an API key you are authorized to use +> and against a target you own or have explicit permission to test. + +Each browser example shows how to: 1. Open a page and collect captcha parameters. 2. Send a task to Captcha Solver. 3. Apply the solution in the browser. -4. Check that the page accepted the solution. +4. Check the strongest acceptance signal exposed by the page and state its exact boundary. ## Installation Requirements: - Node.js 22.12 or newer -- A Captcha Solver API key with a positive balance +- A Captcha Solver API key with a positive balance for live examples ```bash git clone https://github.com/captcha-solver-api/captcha-solver-puppeteer-javascript-examples.git @@ -41,80 +47,154 @@ Copy-Item .env.example .env Set your API key in `.env`: ```dotenv -CAPTCHA_API_KEY=your_api_key +CAPTCHA_API_KEY=your_captcha_solver_api_key ``` +The npm example commands load this file through Node.js `--env-file-if-exists=.env`; using +`process.env` in source code does not load `.env` by itself. + ## Run ```bash -npm run example:recaptcha-v2 +npm run recaptcha-v2 +npm run recaptcha-v2-callback +npm run recaptcha-v2-callback-auto +npm run recaptcha-v2-proxy +npm run recaptcha-v2-callback-proxy +npm run recaptcha-v2-enterprise +npm run recaptcha-v3 +npm run turnstile +npm run turnstile-challenge +npm run yandex +npm run yandex-image +npm run tencent +npm run geetest-v3 +npm run geetest-v4 +npm run image-to-text +npm run coordinates +npm run balance ``` -Chrome opens in visible mode. Set `HEADLESS=true` in `.env` to run it in the -background. Every example launches Chrome through `puppeteer-extra` with -`puppeteer-extra-plugin-stealth`, which reduces common automation fingerprints. -Stealth is not a substitute for permission to automate a website. - -Each run prints numbered steps, the CAPTCHA parameters sent to the API, the -complete solution including its token, how the solution is applied, and the -demo page's acceptance message. Image bodies are shown as their base64 length; -API keys and proxy credentials are redacted. - -Every example is intentionally self-contained and written as a linear tutorial: -SDK and browser setup, page navigation, parameter collection, task creation, -`solver.solve()`, solution application, form submission, and acceptance check -are all visible in the same file. Some code is repeated so that an example can -be copied without also copying hidden project helpers. +Browser examples open Chrome in visible mode. Set `HEADLESS=true` in `.env` to run them in the +background. They launch Chrome through `puppeteer-extra` with `puppeteer-extra-plugin-stealth`, +which reduces common automation fingerprints. Stealth is not a substitute for permission to +automate a website. + +Task examples log the ID returned by the SDK when the task is created, followed by the solver +result. Browser examples then separately verify page acceptance. Receiving a solution from the SDK +proves only that the service completed the task; it does not prove that the target page accepted +the result. When a page exposes only a callback-delivery signal, the example states that narrower +boundary instead of claiming server-side acceptance. Image and balance examples print their +applicable SDK result without inventing a browser acceptance step. The balance example does not +create a task and therefore has no task ID. Image bodies are never printed, and API keys must +remain in `.env`. + +Token injection and submission are site-specific. The included browser code demonstrates one +target's flow; for another target, you must inspect the page and determine the correct response +field, callback, submission action, and acceptance signal yourself. + +Tencent confirms that the intercepted page callback received the same ticket and random string. +This proves callback delivery, not server-side acceptance; add a target-specific acceptance check +when the page exposes one. + +Every example is intentionally self-contained and written as a linear tutorial. Browser examples +show SDK and browser setup, page navigation, parameter collection, task creation, `solver.solve()`, +solution application, site-specific submission or callback delivery, and the applicable acceptance +check in one file. Image-only, coordinate, and balance examples show their complete SDK flow +without inventing browser steps. Some code is repeated so that an example can be copied without +also copying hidden project helpers. ## Examples -| Captcha | File | Command | -|---|---|---| -| reCAPTCHA v2 | [`recaptcha_v2.js`](examples/reCAPTCHA/recaptcha_v2.js) | `npm run example:recaptcha-v2` | -| reCAPTCHA v2 + proxy | [`recaptcha_v2_proxy.js`](examples/reCAPTCHA/recaptcha_v2_proxy.js) | `npm run example:recaptcha-v2-proxy` | -| reCAPTCHA v2 callback | [`recaptcha_v2_callback_variant1.js`](examples/reCAPTCHA/recaptcha_v2_callback_variant1.js) | `npm run example:callback` | -| reCAPTCHA v2 callback, automatic discovery | [`recaptcha_v2_callback_variant2.js`](examples/reCAPTCHA/recaptcha_v2_callback_variant2.js) | `npm run example:callback-auto` | -| reCAPTCHA v2 callback + proxy | [`recaptcha_v2_callback_proxy.js`](examples/reCAPTCHA/recaptcha_v2_callback_proxy.js) | `npm run example:callback-proxy` | -| reCAPTCHA v3 | [`recaptcha_v3.js`](examples/reCAPTCHA/recaptcha_v3.js) | `npm run example:recaptcha-v3` | -| reCAPTCHA v3 interception | [`recaptcha_v3_extended_js_script.js`](examples/reCAPTCHA/recaptcha_v3_extended_js_script.js) | `npm run example:recaptcha-v3-extended` | -| Cloudflare Turnstile | [`cloudflare_turnstile.js`](examples/cloudflare/cloudflare_turnstile.js) | `npm run example:turnstile` | -| Cloudflare Challenge | [`cloudflare_challenge_page.js`](examples/cloudflare/cloudflare_challenge_page.js) | `npm run example:challenge` | -| Tencent CAPTCHA | [`tencent.js`](examples/tencent/tencent.js) | `npm run example:tencent` | -| Yandex SmartCaptcha | [`yandex_smartcaptcha.js`](examples/yandex/yandex_smartcaptcha.js) | `npm run example:yandex-smartcaptcha` | -| Image captcha, screenshot | [`normal_captcha_screenshot.js`](examples/normal_captcha/normal_captcha_screenshot.js) | `npm run example:image` | -| Image captcha, original pixels through canvas | [`normal_captcha_canvas.js`](examples/normal_captcha/normal_captcha_canvas.js) | `npm run example:image-canvas` | -| Image captcha with parameters | [`normal_captcha_screenshot_params.js`](examples/normal_captcha/normal_captcha_screenshot_params.js) | `npm run example:image-params` | -| Coordinates | [`coordinates.js`](examples/coordinates/coordinates.js) | `npm run example:coordinates` | - -The reCAPTCHA v2 and Yandex SmartCaptcha examples use the official provider -demos by default. Every other browser example requires `TARGET_URL` in `.env` -for a page you are authorized to test. - -## Proxy +| Captcha | File | Command | +| -------------------------------- | ------------------------------------------------------------------------------------- | ------------------------------------- | +| reCAPTCHA v2 form | [`recaptcha_v2.js`](examples/reCAPTCHA/recaptcha_v2.js) | `npm run recaptcha-v2` | +| reCAPTCHA v2 named callback | [`recaptcha_v2_callback.js`](examples/reCAPTCHA/recaptcha_v2_callback.js) | `npm run recaptcha-v2-callback` | +| reCAPTCHA v2 discovered callback | [`recaptcha_v2_callback_auto.js`](examples/reCAPTCHA/recaptcha_v2_callback_auto.js) | `npm run recaptcha-v2-callback-auto` | +| reCAPTCHA v2 with proxy | [`recaptcha_v2_proxy.js`](examples/reCAPTCHA/recaptcha_v2_proxy.js) | `npm run recaptcha-v2-proxy` | +| reCAPTCHA v2 callback + proxy | [`recaptcha_v2_callback_proxy.js`](examples/reCAPTCHA/recaptcha_v2_callback_proxy.js) | `npm run recaptcha-v2-callback-proxy` | +| reCAPTCHA v2 Enterprise | [`recaptcha_v2_enterprise.js`](examples/reCAPTCHA/recaptcha_v2_enterprise.js) | `npm run recaptcha-v2-enterprise` | +| reCAPTCHA v3 | [`recaptcha_v3.js`](examples/reCAPTCHA/recaptcha_v3.js) | `npm run recaptcha-v3` | +| Cloudflare Turnstile | [`turnstile.js`](examples/cloudflare/turnstile.js) | `npm run turnstile` | +| Cloudflare Challenge | [`turnstile_challenge.js`](examples/cloudflare/turnstile_challenge.js) | `npm run turnstile-challenge` | +| Tencent CAPTCHA | [`tencent.js`](examples/tencent/tencent.js) | `npm run tencent` | +| Yandex SmartCaptcha | [`yandex_smartcaptcha.js`](examples/yandex/yandex_smartcaptcha.js) | `npm run yandex` | +| Yandex image challenge | [`yandex_smartcaptcha_image.js`](examples/yandex/yandex_smartcaptcha_image.js) | `npm run yandex-image` | +| GeeTest v3 | [`geetest_v3.js`](examples/geetest/geetest_v3.js) | `npm run geetest-v3` | +| GeeTest v4 | [`geetest_v4.js`](examples/geetest/geetest_v4.js) | `npm run geetest-v4` | +| Image-to-text | [`image_to_text.js`](examples/normal_captcha/image_to_text.js) | `npm run image-to-text` | +| Coordinates | [`coordinates.js`](examples/coordinates/coordinates.js) | `npm run coordinates` | +| Balance | [`balance.js`](examples/balance.js) | `npm run balance` | + +The folders group examples by CAPTCHA family. Each file remains standalone and includes its own +SDK setup, task creation, solution handling, and applicable result check. Browser examples also +include browser setup, solution delivery, and an acceptance or callback-delivery check. SDK-only +image, coordinate, and balance examples print the result relevant to their task. + +### Target configuration + +The standard reCAPTCHA v2 form example and Yandex SmartCaptcha example use official provider demos +by default. The named-callback and discovered-callback reCAPTCHA examples require a page that +actually exposes the corresponding callback flow. Set `RECAPTCHA_V2_TARGET_URL` to a compatible +page you own or are authorized to test; for the named-callback variants, also set +`RECAPTCHA_V2_CALLBACK` to the page's callback name. + +Other browser targets can be configured with `RECAPTCHA_ENTERPRISE_TARGET_URL`, +`RECAPTCHA_V3_TARGET_URL`, `TURNSTILE_TARGET_URL`, `TURNSTILE_CHALLENGE_TARGET_URL`, +`TENCENT_TARGET_URL`, `YANDEX_TARGET_URL`, `GEETEST_V3_TARGET_URL`, and +`GEETEST_V4_TARGET_URL`. The `example.com/page_with_...` values in `.env.example` are placeholders, +not working CAPTCHA demos. Replace them before running those examples. Changing a URL does not +automatically adapt selectors, callbacks, submission, or acceptance checks to a different page. + +For Tencent, set `TENCENT_SCRIPT_URL` only when the example cannot capture the script URL from the +page. + +### Proxy configuration + +The two proxy examples require `PROXY_ADDRESS` and `PROXY_PORT`. `PROXY_TYPE` defaults to `http`; +set `PROXY_LOGIN` and `PROXY_PASSWORD` when the proxy requires authentication: ```dotenv PROXY_TYPE=http -PROXY_ADDRESS=proxy.example.com +PROXY_ADDRESS=127.0.0.1 PROXY_PORT=8080 PROXY_LOGIN= PROXY_PASSWORD= ``` -The browser and API task use the same proxy. +Both proxy examples send the same proxy settings to Chromium and `Tasks.RecaptchaV2` so the +browser and solver present the same network identity. + +> [!IMPORTANT] +> CAPTCHA-solving tasks are paid API operations. Local checks use fixtures and +> do not call the paid service. Run live tests only with explicit authorization. ## Checks ```bash npm run lint +npm run format:check npm run check npm test ``` -`normal_captcha_screenshot.js` sends the pixels as rendered by Chrome. -`normal_captcha_canvas.js` draws the loaded image into a canvas and sends its -original pixel data, avoiding viewport scaling and screenshot effects. Canvas -capture only works when the page permits reading the image without a CORS-tainted -canvas. +`npm run check` runs linting, formatting, syntax and workflow-guide validation, and the complete +local regression suite. These checks use local fixtures and do not create paid tasks. + +`npm start` runs the Turnstile Challenge example. To run one explicitly authorized live attempt, +pass an example name to the live runner: + +```bash +npm run test:live -- recaptcha-v2 +``` + +Running `npm run test:live` without an example name attempts every example command except Tencent +and can create multiple paid tasks. Some examples also require target, callback, or proxy settings +described above. Prefer selecting one example explicitly. Tencent is never included in the default +set and must be selected with `npm run test:live -- tencent`. + +`examples/normal_captcha/image_to_text.js` reads a local sample image and sends its base64 +contents through the SDK. ## Useful links @@ -129,4 +209,4 @@ canvas. ## License -This project is licensed under the [MIT License](https://github.com/captcha-solver-api/tencent-captcha-puppeteer-demo/blob/main/LICENSE). +This project is licensed under the [MIT License](LICENSE.md). diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..8c6a982 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,5 @@ +# Security policy + +Please report security issues through GitHub's private vulnerability reporting +feature for this repository. Do not disclose a suspected vulnerability in a +public issue. diff --git a/assets/coordinates-captcha.png b/assets/coordinates-captcha.png new file mode 100644 index 0000000..7b01414 Binary files /dev/null and b/assets/coordinates-captcha.png differ diff --git a/assets/text-captcha.png b/assets/text-captcha.png new file mode 100644 index 0000000..e9d6a8a Binary files /dev/null and b/assets/text-captcha.png differ diff --git a/assets/yandex-smartcaptcha-main.png b/assets/yandex-smartcaptcha-main.png new file mode 100644 index 0000000..92addc3 Binary files /dev/null and b/assets/yandex-smartcaptcha-main.png differ diff --git a/assets/yandex-smartcaptcha-task.png b/assets/yandex-smartcaptcha-task.png new file mode 100644 index 0000000..80cf090 Binary files /dev/null and b/assets/yandex-smartcaptcha-task.png differ diff --git a/config/demos.js b/config/demos.js deleted file mode 100644 index ecea2c2..0000000 --- a/config/demos.js +++ /dev/null @@ -1,5 +0,0 @@ -/** Built-in targets are limited to official CAPTCHA provider demos. */ -export const demos = Object.freeze({ - recaptchaV2: 'https://www.google.com/recaptcha/api2/demo', - yandexSmartCaptcha: 'https://captcha-api.yandex.ru/demo', -}); diff --git a/docs/TESTING.md b/docs/TESTING.md index 27e9ddb..61085e9 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -1,66 +1,63 @@ # Test status -Automated checks validated on October 27, 2026 with Node.js 22.12, Node.js 24, -and Chrome 155. +Automated checks validated on November 18, 2026 with local Node.js 24 and Chrome 155. The CI +matrix also covers Node.js 22.12. ## Automated checks - `npm run lint`: passed. - `npm run check`: passed (includes lint). -- `npm test`: 16 browser integration tests passed. +- `npm test`: 16 browser integration tests and 1 SDK request test passed. - `npm audit --package-lock-only`: passed with no known vulnerabilities. - Tests use a local page fixture and a local API stub. They do not spend API balance. - Browser fixtures use the same Puppeteer Extra stealth setup as the examples. -- Covered flows: reCAPTCHA v2, proxy task construction, known and discovered - callbacks, reCAPTCHA v3 script parsing and interception, embedded Turnstile, - Cloudflare Challenge and Tencent interception, Yandex SmartCaptcha token - injection, image capture, coordinate - scaling, solution injection, and visible success verification. +- Covered flows: reCAPTCHA v2 form, named callback, discovered callback, proxy form and proxy + callback variants, reCAPTCHA v3 script parsing, embedded Turnstile, + reCAPTCHA Enterprise, Cloudflare Challenge navigation/HTTP verification and Tencent interception, Yandex + SmartCaptcha token injection, GeeTest v3/v4 submission, solution injection, and visible success + verification. +- The Yandex image test verifies that the example sends `SmartCaptchaTask` with `image` and + `imgInstructions`, without calling the paid API. ## Live demo checks The following examples received a solution from Captcha Solver and the demo page confirmed that the answer was accepted: -- `recaptcha_v2.js` — official Google reCAPTCHA v2 demo. -- `recaptcha_v2_callback_variant1.js`. -- `recaptcha_v2_callback_variant2.js`. -- `recaptcha_v3.js`. -- `recaptcha_v3_extended_js_script.js`. -- `cloudflare_turnstile.js` — the API returned a solution and the configured +- `examples/reCAPTCHA/recaptcha_v2.js` — official Google reCAPTCHA v2 demo. +- `examples/reCAPTCHA/recaptcha_v3.js`. +- `examples/cloudflare/turnstile.js` — the API returned a solution and the configured test page confirmed acceptance on October 12, 2026. -- `normal_captcha_screenshot.js`. -- `normal_captcha_canvas.js`. -- `normal_captcha_screenshot_params.js`. -- `coordinates.js`. ## Pending checks -- `yandex_smartcaptcha.js`: task construction, token injection, form submission, +- `examples/reCAPTCHA/recaptcha_v2_enterprise.js`, `examples/geetest/geetest_v3.js`, and + `examples/geetest/geetest_v4.js`: task + construction, solution submission, and acceptance verification pass against + local browser fixtures. They have not been live-tested from this repository. +- `examples/coordinates/coordinates.js`, `examples/normal_captcha/image_to_text.js`, and + `examples/balance.js`: syntax, lint, formatting, and + workflow-guide checks pass. Their paid API calls were not run locally. +- `examples/yandex/yandex_smartcaptcha_image.js`: the specialized `SmartCaptchaTask` request and returned + coordinates pass against a local API stub. Its paid API call was not run locally. +- `examples/yandex/yandex_smartcaptcha.js`: task construction, token injection, form submission, and page success verification pass against the local browser fixture. The official Yandex demo has not been live-tested from this repository yet. -- `tencent.js`: its parameter interception, SDK task fields, complete callback +- `examples/tencent/tencent.js`: its parameter interception, SDK task fields, complete callback response, and page success verification pass against the local browser fixture. - One live attempt on October 27, 2026 used - `https://common-web.intlgame.com/jssdk/li_captcha_new.html`. The example - captured `appId` and the Tencent script URL, and the API returned `ret: 0`, a + One authorized live attempt on October 27, 2026 used a configured Tencent + target. The example captured `appId` and the Tencent script URL, and the API returned `ret: 0`, a ticket, and `randstr`. The original page callback received the complete result, but this mobile-WebView page closed the CAPTCHA without exposing a visible DOM success state, so the configured acceptance selector timed out. The attempt is not recorded as a page pass and was not retried. -- `cloudflare_challenge_page.js`: tested against a configured target on October +- `examples/cloudflare/turnstile_challenge.js`: tested against a configured target on October 12, 2026. The example captured the live `sitekey`, `action`, `cData`, `chlPageData`, and browser User-Agent and created an API task. One task returned a solution, but the page did not confirm acceptance; after fixing the browser User-Agent mismatch, the next single task returned `ERROR_CAPTCHA_UNSOLVABLE`. The runner did not retry it or report a page pass. The interception, SDK task, callback, and visible-success verification pass against the local browser fixture. -- `recaptcha_v2_proxy.js` and `recaptcha_v2_callback_proxy.js`: tested on - October 12, 2026 with an authenticated EU HTTP proxy. Proxy authentication and - outbound connectivity succeeded, and both examples created `RecaptchaV2Task` - requests using the same proxy as Chrome. Each single API task returned - `ERROR_CAPTCHA_UNSOLVABLE`; the runner did not retry either task or report a - page pass. Proxy credentials were not written to the repository or report. Raw live reports and failure screenshots stay in the ignored `artifacts/` directory and are not committed. diff --git a/eslint.config.js b/eslint.config.js index 1b5d91a..ce319c2 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -11,20 +11,40 @@ export default [ ecmaVersion: 2024, sourceType: 'module', globals: { - Buffer: 'readonly', clearInterval: 'readonly', clearTimeout: 'readonly', - console: 'readonly', document: 'readonly', Event: 'readonly', - getComputedStyle: 'readonly', location: 'readonly', navigator: 'readonly', Node: 'readonly', - process: 'readonly', setInterval: 'readonly', setTimeout: 'readonly', - URL: 'readonly', WeakMap: 'readonly', WeakSet: 'readonly', window: 'readonly', + Buffer: 'readonly', + clearInterval: 'readonly', + clearTimeout: 'readonly', + console: 'readonly', + document: 'readonly', + Event: 'readonly', + fetch: 'readonly', + getComputedStyle: 'readonly', + location: 'readonly', + navigator: 'readonly', + Node: 'readonly', + process: 'readonly', + setInterval: 'readonly', + setTimeout: 'readonly', + URL: 'readonly', + WeakMap: 'readonly', + WeakSet: 'readonly', + window: 'readonly', }, }, rules: { 'no-console': 'off', 'no-unused-vars': ['error', { argsIgnorePattern: '^_' }], - 'jsdoc/require-jsdoc': ['error', { - contexts: ['FunctionDeclaration'], - require: { ArrowFunctionExpression: false, FunctionDeclaration: true, FunctionExpression: false }, - }], + 'jsdoc/require-jsdoc': [ + 'error', + { + contexts: ['FunctionDeclaration'], + require: { + ArrowFunctionExpression: false, + FunctionDeclaration: true, + FunctionExpression: false, + }, + }, + ], }, }, ]; diff --git a/examples/balance.js b/examples/balance.js new file mode 100644 index 0000000..064f413 --- /dev/null +++ b/examples/balance.js @@ -0,0 +1,35 @@ +import { pathToFileURL } from 'node:url'; +import { CaptchaClient } from '@captcha-solver-api/javascript-sdk'; + +/** + * This example checks the current Captcha Solver account balance. It creates an SDK client, + * requests the balance without creating a CAPTCHA task, and prints the returned amount. + * It uses CaptchaClient.getBalance(). + * + * How it works: + * STEP-01 - Create the SDK client. + * STEP-02 - Request and print the account balance. + * STEP-03 - Report request errors. + */ + +/** Request and print the current account balance. */ +export function main() { + // STEP-01: Create the SDK client with the API key from CAPTCHA_API_KEY. + const client = new CaptchaClient({ + clientKey: process.env.CAPTCHA_API_KEY || 'YOUR_API_KEY', + }); + + // STEP-02: Request and print the account balance. + return client.getBalance().then((balance) => { + console.log(balance); + return balance; + }); +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + // STEP-03: Report request errors. + main().catch((error) => { + console.error(error); + process.exitCode = 1; + }); +} diff --git a/examples/cloudflare/cloudflare_challenge_page.js b/examples/cloudflare/cloudflare_challenge_page.js deleted file mode 100644 index 2f7ae62..0000000 --- a/examples/cloudflare/cloudflare_challenge_page.js +++ /dev/null @@ -1,98 +0,0 @@ -/** - * Solve a Cloudflare managed Challenge page. - * The Turnstile render call is intercepted before navigation so dynamic fields - * and the original callback remain available in the browser. - */ -import { pathToFileURL } from 'node:url'; -import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; -import puppeteer from 'puppeteer-extra'; -import StealthPlugin from 'puppeteer-extra-plugin-stealth'; - -puppeteer.use(StealthPlugin()); - -/** Install the Turnstile render interceptor before page scripts run. */ -async function installInterceptor(page) { - await page.evaluateOnNewDocument(() => { - const timer = setInterval(() => { - const turnstile = window.turnstile; - if (!turnstile || turnstile.__captchaPatched || typeof turnstile.render !== 'function') return; - const originalRender = turnstile.render; - Object.defineProperty(turnstile, '__captchaPatched', { value: true }); - turnstile.render = function render(container, options = {}) { - window.__turnstileParams = { - websiteURL: location.href, - websiteKey: options.sitekey, - action: options.action, - data: options.cData, - pagedata: options.chlPageData, - userAgent: navigator.userAgent, - }; - window.__turnstileCallback = options.callback; - return originalRender.call(turnstile, container, options); - }; - clearInterval(timer); - }, 10); - }); -} - -/** Solve the managed Challenge on an already opened page. */ -export async function solveCaptcha(page, solver) { - if (!process.env.TARGET_URL) throw new Error('Set TARGET_URL for this example.'); - console.log('1. Installing the Turnstile interceptor'); - await installInterceptor(page); - console.log('2. Opening the Cloudflare Challenge page'); - await page.goto(process.env.TARGET_URL, { waitUntil: 'domcontentloaded' }); - - const selector = process.env.SUCCESS_SELECTOR || 'p[class*="successMessage"]'; - const handle = await page.waitForFunction((successSelector) => { - if (document.querySelector('#cf-error-details')?.textContent.includes('you have been blocked')) { - return { blocked: true }; - } - const success = document.querySelector(successSelector); - if (success?.getClientRects().length && success.textContent.trim()) { - return { success: success.textContent.trim() }; - } - return window.__turnstileParams ? { params: window.__turnstileParams } : false; - }, {}, selector); - const state = await handle.jsonValue(); - await handle.dispose(); - if (state.blocked) throw new Error('Cloudflare blocked the browser before a task was created.'); - if (state.success) return `Already passed: ${state.success}`; - - console.log('3. Captured Challenge parameters', state.params); - const task = new Tasks.TurnstileProxyless(state.params); - console.log('4. Sending the task to Captcha Solver'); - const solution = await solver.solve(task); - console.log('5. Solution received', solution); - if (!solution.token) throw new Error('Captcha Solver returned an empty token.'); - - // Token injection and submission are site-specific; adapt this step to the target page. - console.log('6. Passing the token to the original Turnstile callback'); - await page.evaluate((token) => { - if (typeof window.__turnstileCallback !== 'function') throw new Error('Turnstile callback was not found.'); - window.__turnstileCallback(token); - }, solution.token); - await page.waitForSelector(selector, { visible: true }); - return page.$eval(selector, (element) => element.textContent.trim()); -} - -/** Run the complete standalone Cloudflare Challenge example. */ -export async function main() { - const apiKey = process.env.CAPTCHA_API_KEY; - if (!apiKey || apiKey === 'your_api_key') throw new Error('Set CAPTCHA_API_KEY.'); - const solver = new CaptchaClient({ clientKey: apiKey }); - const browser = await puppeteer.launch({ - headless: process.env.HEADLESS === 'true', - executablePath: process.env.BROWSER_EXECUTABLE_PATH || undefined, - }); - try { - const page = await browser.newPage(); - console.log('Captcha solved successfully:', await solveCaptcha(page, solver)); - } finally { - await browser.close(); - } -} - -if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { - main().catch((error) => { console.error('Example failed:', error.message); process.exitCode = 1; }); -} diff --git a/examples/cloudflare/cloudflare_turnstile.js b/examples/cloudflare/cloudflare_turnstile.js deleted file mode 100644 index d9f16f6..0000000 --- a/examples/cloudflare/cloudflare_turnstile.js +++ /dev/null @@ -1,75 +0,0 @@ -/** - * Solve an embedded Cloudflare Turnstile widget. - * The example reads the widget parameters, solves them through the SDK, fills - * the response field, submits the form, and confirms page acceptance. - */ -import { pathToFileURL } from 'node:url'; -import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; -import puppeteer from 'puppeteer-extra'; -import StealthPlugin from 'puppeteer-extra-plugin-stealth'; - -puppeteer.use(StealthPlugin()); - -/** Solve Turnstile on an already opened page. */ -export async function solveCaptcha(page, solver) { - if (!process.env.TARGET_URL) throw new Error('Set TARGET_URL for this example.'); - console.log('1. Opening the Turnstile page'); - await page.goto(process.env.TARGET_URL, { waitUntil: 'domcontentloaded' }); - await page.waitForSelector('.cf-turnstile[data-sitekey]'); - - console.log('2. Reading Turnstile widget parameters'); - const captcha = await page.$eval('.cf-turnstile[data-sitekey]', (widget) => ({ - websiteKey: widget.dataset.sitekey, - action: widget.dataset.action, - data: widget.dataset.cdata, - })); - const task = new Tasks.TurnstileProxyless({ - websiteURL: page.url(), - ...captcha, - userAgent: await page.evaluate(() => navigator.userAgent), - }); - - console.log('3. Sending the task to Captcha Solver', task.toDict()); - const solution = await solver.solve(task); - console.log('4. Solution received', solution); - if (!solution.token) throw new Error('Captcha Solver returned an empty token.'); - - // Token injection and submission are site-specific; adapt this step to the target page. - console.log('5. Writing the token into cf-turnstile-response'); - await page.evaluate((token) => { - const fields = document.getElementsByName('cf-turnstile-response'); - if (!fields.length) throw new Error('cf-turnstile-response field was not found.'); - for (const field of fields) { - field.value = token; - field.dispatchEvent(new Event('input', { bubbles: true })); - field.dispatchEvent(new Event('change', { bubbles: true })); - } - }, solution.token); - - console.log('6. Submitting and waiting for page acceptance'); - await page.click(process.env.SUBMIT_SELECTOR || 'button[type="submit"], input[type="submit"]'); - const selector = process.env.SUCCESS_SELECTOR || 'p[class*="successMessage"]'; - await page.waitForSelector(selector, { visible: true }); - return page.$eval(selector, (element) => element.textContent.trim()); -} - -/** Run the complete standalone Turnstile example. */ -export async function main() { - const apiKey = process.env.CAPTCHA_API_KEY; - if (!apiKey || apiKey === 'your_api_key') throw new Error('Set CAPTCHA_API_KEY.'); - const solver = new CaptchaClient({ clientKey: apiKey }); - const browser = await puppeteer.launch({ - headless: process.env.HEADLESS === 'true', - executablePath: process.env.BROWSER_EXECUTABLE_PATH || undefined, - }); - try { - const page = await browser.newPage(); - console.log('Captcha solved successfully:', await solveCaptcha(page, solver)); - } finally { - await browser.close(); - } -} - -if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { - main().catch((error) => { console.error('Example failed:', error.message); process.exitCode = 1; }); -} diff --git a/examples/cloudflare/turnstile.js b/examples/cloudflare/turnstile.js new file mode 100644 index 0000000..b773a01 --- /dev/null +++ b/examples/cloudflare/turnstile.js @@ -0,0 +1,130 @@ +import { pathToFileURL } from 'node:url'; +import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; +import puppeteer from 'puppeteer-extra'; +import StealthPlugin from 'puppeteer-extra-plugin-stealth'; + +/** + * This example shows how to solve a standalone Cloudflare Turnstile widget without using a proxy. + * It opens the page, extracts the site key and browser User-Agent, sends the task to the service, + * inserts the returned token into the form, and checks the page confirmation. It uses + * Tasks.TurnstileProxyless and CaptchaClient.solve(). + * + * To use this example on another page, change the target URL and update the widget and form + * selectors. Token injection and submission are site-specific. You must inspect the target page + * and determine the correct way to pass the token yourself. + * + * How it works: + * STEP-01 - Configure the target and create the SDK client. + * STEP-02 - Launch Chromium and open the target page. + * STEP-03 - Extract the Turnstile parameters from the page. + * STEP-04 - Create the task and wait for the solver result. + * STEP-05 - Log the solution and inject its token into the form. + * STEP-06 - Submit the form and verify that the page accepts the token. + * STEP-07 - Handle errors and close Chromium. + */ + +puppeteer.use(StealthPlugin()); + +/** Solve a task with the SDK and log the task ID returned by createTask(). */ +function solveAndLogTaskId(solver, task) { + const loggingSolver = Object.create(solver); + loggingSolver.createTask = (...args) => + solver.createTask(...args).then((taskId) => { + console.log('Task ID:', taskId); + return taskId; + }); + return loggingSolver.solve(task); +} + +// STEP-01: Read the target URL and create the SDK client. +const websiteURL = process.env.TURNSTILE_TARGET_URL || 'https://example.com/page_with_turnstile'; +const client = new CaptchaClient({ + clientKey: process.env.CAPTCHA_API_KEY || 'YOUR_API_KEY', +}); + +let browser; + +/** + * Solve and submit Turnstile on an opened Puppeteer page. + * @param {import('puppeteer').Page} page Open Puppeteer page. + * @param {CaptchaClient} solver Configured Captcha Solver client. + * @returns {Promise} Page text that confirms acceptance. + */ +export function solveCaptcha(page, solver = client) { + const widgetSelector = '.cf-turnstile[data-sitekey], [data-sitekey]'; + const responseSelector = '[name="cf-turnstile-response"]'; + const submitSelector = 'button[type="submit"], input[type="submit"]'; + const successSelector = 'p[class*="successMessage"]'; + + // STEP-02: Open the configured page containing Turnstile. + return ( + page + .goto(process.env.TURNSTILE_TARGET_URL || websiteURL, { waitUntil: 'domcontentloaded' }) + .then(() => page.waitForSelector(widgetSelector)) + // STEP-03: Read the public site key and browser User-Agent from the page. + .then(() => + Promise.all([ + page.$eval(widgetSelector, (element) => element.getAttribute('data-sitekey')), + page.evaluate(() => navigator.userAgent), + ]), + ) + // STEP-04: Build the task and wait for the solver result. + .then(([websiteKey, userAgent]) => { + if (!websiteKey) throw new Error('Turnstile site key not found.'); + const task = new Tasks.TurnstileProxyless({ + websiteURL: page.url(), + websiteKey, + userAgent, + }); + return solveAndLogTaskId(solver, task); + }) + // STEP-05: Log the solution and inject its token into the form. + .then((solution) => { + console.log('Solution:', solution); + if (!solution.token) throw new Error('Captcha Solver returned an empty Turnstile token.'); + + // Token injection and submission are site-specific; adapt this step to the target page. + // Turnstile forms submit the token through cf-turnstile-response. + return page.$eval( + responseSelector, + (input, token) => { + input.value = token; + input.dispatchEvent(new Event('input', { bubbles: true })); + input.dispatchEvent(new Event('change', { bubbles: true })); + }, + solution.token, + ); + }) + // STEP-06: Submit the form and require an explicit page confirmation. + .then(() => page.click(submitSelector)) + .then(() => page.waitForSelector(successSelector, { visible: true })) + .then(() => page.$eval(successSelector, (element) => element.textContent.trim())) + ); +} + +/** Run the complete standalone Turnstile example. */ +export function main() { + // Launch Chromium and create a browser page. + return ( + puppeteer + .launch({ + headless: process.env.HEADLESS === 'true', + }) + .then((instance) => { + browser = instance; + return browser.newPage(); + }) + .then((page) => solveCaptcha(page)) + .then((message) => console.log(`Page confirmation: ${message}`)) + // STEP-07: Always close Chromium and let callers handle failures. + .finally(() => browser?.close()) + ); +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + // Report errors and set a nonzero exit code when this file runs directly. + main().catch((error) => { + console.error(error); + process.exitCode = 1; + }); +} diff --git a/examples/cloudflare/turnstile_challenge.js b/examples/cloudflare/turnstile_challenge.js new file mode 100644 index 0000000..ae4bfa4 --- /dev/null +++ b/examples/cloudflare/turnstile_challenge.js @@ -0,0 +1,206 @@ +import { pathToFileURL } from 'node:url'; +import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; +import puppeteer from 'puppeteer-extra'; +import StealthPlugin from 'puppeteer-extra-plugin-stealth'; + +/** + * This example shows how to solve a Cloudflare Turnstile Challenge without using a proxy. It + * intercepts the challenge parameters while the page loads, sends them to the service, passes the + * returned token to the original callback, and verifies both the page confirmation and a fresh + * clearance cookie. It uses Tasks.TurnstileProxyless and CaptchaClient.solve(). + * + * To use this example on another challenge page, change the target URL and verify the interception + * logic, User-Agent, callback, success selector, and clearance requirements. Challenge behavior is + * site-specific, so inspect and debug the page before adapting the solution application step. + * Token injection and submission are site-specific. You must inspect the target page and + * determine the correct way to pass the token yourself. + * + * How it works: + * STEP-01 - Configure the target, timeout, and SDK client. + * STEP-02 - Launch Chromium and install the parameter interceptor. + * STEP-03 - Open the target and capture its challenge parameters. + * STEP-04 - Create the task and wait for the solver result. + * STEP-05 - Log the solution and pass its token to the page callback. + * STEP-06 - Verify the page confirmation and a fresh clearance cookie. + * STEP-07 - Handle errors and close Chromium. + */ + +puppeteer.use(StealthPlugin()); + +/** Solve a task with the SDK and log the task ID returned by createTask(). */ +function solveAndLogTaskId(solver, task) { + const loggingSolver = Object.create(solver); + loggingSolver.createTask = (...args) => + solver.createTask(...args).then((taskId) => { + console.log('Task ID:', taskId); + return taskId; + }); + return loggingSolver.solve(task); +} + +// STEP-01: Read the settings and create the SDK client. +const websiteURL = + process.env.TURNSTILE_CHALLENGE_TARGET_URL || 'https://example.com/page_with_turnstile_challenge'; +const parameterCaptureTimeout = 30_000; +const challengeNavigationTimeout = 60_000; +const successSelector = 'p[class*="successMessage"]'; +const challengeConfirmation = 'challenge cleared and target page loaded.'; +const client = new CaptchaClient({ + clientKey: process.env.CAPTCHA_API_KEY || 'YOUR_API_KEY', +}); + +let browser; + +/** Install the Turnstile render interceptor before page scripts run. */ +function installInterceptor(page) { + return page.evaluateOnNewDocument(() => { + const interceptionInterval = setInterval(() => { + const turnstile = window.turnstile; + if (!turnstile || turnstile.__captchaPatched || typeof turnstile.render !== 'function') + return; + + const originalRender = turnstile.render; + Object.defineProperty(turnstile, '__captchaPatched', { value: true }); + turnstile.render = function render(container, options = {}) { + window.__turnstileParams = { + websiteURL: location.href, + websiteKey: options.sitekey, + action: options.action, + data: options.cData, + pagedata: options.chlPageData, + userAgent: navigator.userAgent, + }; + window.__turnstileCallback = options.callback; + return originalRender.call(turnstile, container, options); + }; + clearInterval(interceptionInterval); + }, 10); + }); +} + +/** + * Solve a managed Turnstile Challenge on an opened Puppeteer page. + * @param {import('puppeteer').Page} page Open Puppeteer page. + * @param {CaptchaClient} solver Configured Captcha Solver client. + * @returns {Promise} Page text that confirms acceptance. + */ +export function solveCaptcha(page, solver = client) { + let previousClearance; + + // STEP-02: Install the interceptor before the target initializes Turnstile. + return ( + installInterceptor(page) + // STEP-03: Open the target and wait for challenge parameters or an existing success state. + .then(() => + page.goto(process.env.TURNSTILE_CHALLENGE_TARGET_URL || websiteURL, { + waitUntil: 'domcontentloaded', + }), + ) + .then(() => + page.waitForFunction( + (selector) => { + if ( + document + .querySelector('#cf-error-details') + ?.textContent.includes('you have been blocked') + ) { + return { blocked: true }; + } + const success = document.querySelector(selector); + if (success?.getClientRects().length && success.textContent.trim()) { + return { success: success.textContent.trim() }; + } + return window.__turnstileParams ? { params: window.__turnstileParams } : false; + }, + { timeout: parameterCaptureTimeout }, + successSelector, + ), + ) + .then((handle) => + handle.jsonValue().finally(() => { + return handle.dispose(); + }), + ) + .then((state) => { + if (state.blocked) { + throw new Error('Cloudflare blocked the browser before a task was created.'); + } + if (state.success) return { alreadyPassed: state.success }; + + return page.cookies().then((cookies) => { + previousClearance = cookies.find((cookie) => cookie.name === 'cf_clearance')?.value; + // STEP-04: Build the task and wait for the solver result. + return solveAndLogTaskId(solver, new Tasks.TurnstileProxyless(state.params)); + }); + }) + // STEP-05: Log the solution and pass its token to the original page callback. + .then((solution) => { + if (solution.alreadyPassed) return `Already passed: ${solution.alreadyPassed}`; + + console.log('Solution:', solution); + if (!solution.token) throw new Error('Captcha Solver returned an empty Turnstile token.'); + + // Token injection and submission are site-specific; adapt this step to the target page. + // Call the exact callback registered by this challenge page. + return ( + Promise.all([ + page.waitForResponse( + (response) => + response.request().isNavigationRequest() && response.frame() === page.mainFrame(), + { timeout: challengeNavigationTimeout }, + ), + page.evaluate((token) => { + if (typeof window.__turnstileCallback !== 'function') { + throw new Error('Turnstile callback was not found.'); + } + window.__turnstileCallback(token); + }, solution.token), + ]) + .then(([response]) => { + if (!response.ok()) { + throw new Error(`Challenge navigation returned HTTP ${response.status()}.`); + } + return page.waitForSelector(successSelector, { visible: true }); + }) + // STEP-06: Require a fresh cookie as well as the page confirmation. + .then(() => page.cookies()) + .then((cookies) => { + const currentClearance = cookies.find( + (cookie) => cookie.name === 'cf_clearance', + )?.value; + if (!currentClearance || currentClearance === previousClearance) { + throw new Error('Cloudflare did not issue a new cf_clearance cookie.'); + } + return challengeConfirmation; + }) + ); + }) + ); +} + +/** Run the complete standalone Turnstile Challenge example. */ +export function main() { + // Launch Chromium and create a browser page. + return ( + puppeteer + .launch({ + headless: process.env.HEADLESS === 'true', + }) + .then((instance) => { + browser = instance; + return browser.newPage(); + }) + .then((page) => solveCaptcha(page)) + .then((message) => console.log(`Page confirmation: ${message}`)) + // STEP-07: Always close Chromium and let callers handle failures. + .finally(() => browser?.close()) + ); +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + // Report errors and set a nonzero exit code when this file runs directly. + main().catch((error) => { + console.error(error); + process.exitCode = 1; + }); +} diff --git a/examples/coordinates/coordinates.js b/examples/coordinates/coordinates.js index 6a8eed4..02ee08c 100644 --- a/examples/coordinates/coordinates.js +++ b/examples/coordinates/coordinates.js @@ -1,80 +1,60 @@ -/** - * Solve a click-coordinate CAPTCHA with Puppeteer. - * The example captures the source image, sends it through the official SDK, - * scales the returned coordinates to the displayed image, clicks, and submits. - */ +import { readFileSync } from 'node:fs'; import { pathToFileURL } from 'node:url'; -import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; -import puppeteer from 'puppeteer-extra'; -import StealthPlugin from 'puppeteer-extra-plugin-stealth'; - -puppeteer.use(StealthPlugin()); -const IMAGE_SELECTOR = 'img[alt="clickcaptcha example"]'; - -/** Solve the coordinate CAPTCHA on an already opened page. */ -export async function solveCaptcha(page, solver) { - if (!process.env.TARGET_URL) throw new Error('Set TARGET_URL for this example.'); - console.log('1. Opening the page'); - await page.goto(process.env.TARGET_URL, { waitUntil: 'domcontentloaded' }); - const imageElement = await page.waitForSelector(IMAGE_SELECTOR, { visible: true }); - - console.log('2. Reading the original image pixels and dimensions'); - const image = await page.$eval(IMAGE_SELECTOR, (element) => { - const canvas = document.createElement('canvas'); - canvas.width = element.naturalWidth; - canvas.height = element.naturalHeight; - canvas.getContext('2d').drawImage(element, 0, 0); - return { - body: canvas.toDataURL('image/png').split(',')[1], - width: canvas.width, - height: canvas.height, - }; - }); - const task = new Tasks.CoordinatesTask({ body: image.body }); - console.log('3. Sending Coordinates task', { - ...task.toDict(), - body: `[${image.body.length} base64 characters]`, - }); - const solution = await solver.solve(task); - console.log('4. Coordinates received', solution.coordinates); - if (!solution.coordinates?.length) throw new Error('Captcha Solver returned no coordinates.'); - - await imageElement.scrollIntoView(); - const box = await imageElement.boundingBox(); - if (!box) throw new Error('The CAPTCHA image is not visible.'); +import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; - console.log('5. Scaling and clicking the returned coordinates'); - for (const point of solution.coordinates) { - const x = box.x + point.x * box.width / image.width; - const y = box.y + point.y * box.height / image.height; - await page.mouse.click(x, y); - } +/** + * This example shows how to solve a coordinate CAPTCHA. It reads a local image, adds an + * instruction describing which objects to select, sends the task to the service, and prints the + * returned click coordinates. It uses Tasks.CoordinatesTask and CaptchaClient.solve(). + * + * How it works: + * STEP-01 - Create the SDK client. + * STEP-02 - Read the image and create the coordinate task. + * STEP-03 - Send the task and wait for the solver result. + * STEP-04 - Print the click coordinates or report an error. + */ - console.log('6. Submitting and waiting for page acceptance'); - await page.click(process.env.SUBMIT_SELECTOR || 'button[type="submit"], input[type="submit"]'); - const selector = process.env.SUCCESS_SELECTOR || 'p[class*="successMessage"]'; - await page.waitForSelector(selector, { visible: true }); - return page.$eval(selector, (element) => element.textContent.trim()); +/** Solve a task with the SDK and log the task ID returned by createTask(). */ +function solveAndLogTaskId(solver, task) { + const loggingSolver = Object.create(solver); + loggingSolver.createTask = (...args) => + solver.createTask(...args).then((taskId) => { + console.log('Task ID:', taskId); + return taskId; + }); + return loggingSolver.solve(task); } -/** Run the complete standalone coordinate example. */ -export async function main() { - const apiKey = process.env.CAPTCHA_API_KEY; - if (!apiKey || apiKey === 'your_api_key') throw new Error('Set CAPTCHA_API_KEY.'); - const solver = new CaptchaClient({ clientKey: apiKey }); - const browser = await puppeteer.launch({ - headless: process.env.HEADLESS === 'true', - executablePath: process.env.BROWSER_EXECUTABLE_PATH || undefined, - }); - try { - const page = await browser.newPage(); - console.log('Captcha solved successfully:', await solveCaptcha(page, solver)); - } finally { - await browser.close(); - } +// STEP-01: Create the SDK client with the API key from CAPTCHA_API_KEY. +const client = new CaptchaClient({ + clientKey: process.env.CAPTCHA_API_KEY || 'YOUR_API_KEY', +}); + +// STEP-02: Read the image and create the task with a base64 body and click instruction. +const task = new Tasks.CoordinatesTask({ + body: readFileSync(new URL('../../assets/coordinates-captcha.png', import.meta.url)).toString( + 'base64', + ), + comment: 'Click on all squares with street signs', +}); + +/** Create, solve, and print the coordinate task. */ +export function main() { + return ( + // STEP-03: Send the coordinate task and wait for the solver result. + solveAndLogTaskId(client, task).then((solution) => { + // STEP-04: Print coordinates in the original image's x/y coordinate system. + console.log(solution.coordinates); + // Use browser automation to click the original image at each returned x/y coordinate. + return solution; + }) + ); } if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { - main().catch((error) => { console.error('Example failed:', error.message); process.exitCode = 1; }); + main().catch((error) => { + console.error(error); + process.exitCode = 1; + }); } diff --git a/examples/geetest/geetest_v3.js b/examples/geetest/geetest_v3.js new file mode 100644 index 0000000..7bfd738 --- /dev/null +++ b/examples/geetest/geetest_v3.js @@ -0,0 +1,126 @@ +import { pathToFileURL } from 'node:url'; +import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; +import puppeteer from 'puppeteer-extra'; +import StealthPlugin from 'puppeteer-extra-plugin-stealth'; + +/** + * This example solves GeeTest v3 without a proxy. It intercepts a fresh gt/challenge pair, + * creates Tasks.GeeTestProxyless, submits the returned fields to the page verification endpoint, + * and requires an explicit successful response. It uses CaptchaClient.solve(). + * + * To adapt it, change GEETEST_V3_TARGET_URL and inspect how the target initializes GeeTest, + * consumes the solution, and reports acceptance. Solution integration is unique to every site. + * + * How it works: + * STEP-01 - Install the GeeTest initialization interceptor. + * STEP-02 - Open the target and capture gt/challenge. + * STEP-03 - Create and solve the GeeTest v3 task. + * STEP-04 - Log and submit the solution. + * STEP-05 - Verify that the page endpoint accepts it. + * STEP-06 - Handle errors and close Chromium. + */ + +puppeteer.use(StealthPlugin()); + +/** Solve a task with the SDK and log the task ID returned by createTask(). */ +function solveAndLogTaskId(solver, task) { + const loggingSolver = Object.create(solver); + loggingSolver.createTask = (...args) => + solver.createTask(...args).then((taskId) => { + console.log('Task ID:', taskId); + return taskId; + }); + return loggingSolver.solve(task); +} +const DEFAULT_URL = 'https://example.com/page_with_geetest_v3'; +const solverTimeout = 300_000; + +/** Solve GeeTest v3 on an already opened page. */ +export function solveCaptcha(page, solver) { + const websiteURL = process.env.GEETEST_V3_TARGET_URL || DEFAULT_URL; + + // STEP-01: Install the interceptor before the target initializes GeeTest. + return ( + page + .evaluateOnNewDocument(() => { + Object.defineProperty(window, 'initGeetest', { + configurable: true, + set(originalInitGeetest) { + Object.defineProperty(window, 'initGeetest', { + configurable: true, + value: (config, callback) => { + window.__geetestConfig = config; + window.__originalInitGeetest = originalInitGeetest; + window.__originalGeeTestCallback = callback; + }, + }); + }, + }); + }) + // STEP-02: Open the target and wait for the fresh initialization parameters. + .then(() => page.goto(websiteURL, { waitUntil: 'domcontentloaded' })) + .then(() => page.waitForFunction(() => window.__geetestConfig)) + .then(() => page.evaluate(() => window.__geetestConfig)) + .then((config) => { + if (!config.gt || !config.challenge) throw new Error('GeeTest v3 parameters not found.'); + // STEP-03: Create and solve the GeeTest v3 task. + const task = new Tasks.GeeTestProxyless({ + websiteURL: page.url(), + gt: config.gt, + challenge: config.challenge, + geetestApiServerSubdomain: config.api_server || 'api.geetest.com', + }); + return solveAndLogTaskId(solver, task); + }) + .then((solution) => { + // STEP-04: Log and submit all v3 solution fields to this demo endpoint. + console.log('Solution:', solution); + // Solution submission is site-specific; adapt this step to the target page. + // Inspect the target page's verification endpoint, required fields, and acceptance response before adapting it. + return page.evaluate((result) => { + return fetch('/api/v1/captcha-demo/gee-test/verify', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ + geetest_challenge: result.challenge, + geetest_validate: result.validate, + geetest_seccode: result.seccode, + }), + }).then((response) => response.json().then((body) => ({ ok: response.ok, body }))); + }, solution); + }) + .then(({ ok, body }) => { + // STEP-05: Require HTTP and application-level acceptance. + if (!ok || body.success !== true) throw new Error('Page rejected the GeeTest v3 solution.'); + return 'GeeTest v3 solution accepted.'; + }) + ); +} + +/** Launch Chromium and run the complete GeeTest v3 example. */ +export function main() { + const solver = new CaptchaClient({ + clientKey: process.env.CAPTCHA_API_KEY || 'YOUR_API_KEY', + timeout: solverTimeout, + }); + let browser; + return puppeteer + .launch({ + headless: process.env.HEADLESS === 'true', + }) + .then((instance) => { + browser = instance; + return browser.newPage(); + }) + .then((page) => solveCaptcha(page, solver)) + .then((message) => console.log('Page confirmation:', message)) + .finally(() => browser?.close()); +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + // STEP-06: Report errors; main() closes Chromium in every outcome. + main().catch((error) => { + console.error(error); + process.exitCode = 1; + }); +} diff --git a/examples/geetest/geetest_v4.js b/examples/geetest/geetest_v4.js new file mode 100644 index 0000000..3875120 --- /dev/null +++ b/examples/geetest/geetest_v4.js @@ -0,0 +1,108 @@ +import { pathToFileURL } from 'node:url'; +import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; +import puppeteer from 'puppeteer-extra'; +import StealthPlugin from 'puppeteer-extra-plugin-stealth'; + +/** + * This example solves GeeTest v4 without a proxy. It extracts captcha_id from the loader script, + * creates Tasks.GeeTestProxyless, submits the complete returned solution, and verifies acceptance. + * It uses CaptchaClient.solve(). + * + * To adapt it, change GEETEST_V4_TARGET_URL and inspect the target's initialization parameters, + * solution submission, and success response. Solution integration is unique to every site. + * + * How it works: + * STEP-01 - Open the configured target page. + * STEP-02 - Extract captcha_id from the GeeTest loader. + * STEP-03 - Create and solve the GeeTest v4 task. + * STEP-04 - Log and submit the solution. + * STEP-05 - Verify that the page endpoint accepts it. + * STEP-06 - Handle errors and close Chromium. + */ + +puppeteer.use(StealthPlugin()); + +/** Solve a task with the SDK and log the task ID returned by createTask(). */ +function solveAndLogTaskId(solver, task) { + const loggingSolver = Object.create(solver); + loggingSolver.createTask = (...args) => + solver.createTask(...args).then((taskId) => { + console.log('Task ID:', taskId); + return taskId; + }); + return loggingSolver.solve(task); +} +const DEFAULT_URL = 'https://example.com/page_with_geetest_v4'; +const solverTimeout = 300_000; + +/** Solve GeeTest v4 on an already opened page. */ +export function solveCaptcha(page, solver) { + const websiteURL = process.env.GEETEST_V4_TARGET_URL || DEFAULT_URL; + + // STEP-01: Open the configured target page. + return ( + page + .goto(websiteURL, { waitUntil: 'domcontentloaded' }) + // STEP-02: Extract captcha_id from the GeeTest loader script URL. + .then(() => page.waitForSelector('script[src*="captcha_id="]')) + .then(() => page.$eval('script[src*="captcha_id="]', (element) => element.src)) + .then((scriptURL) => { + const captchaId = new URL(scriptURL).searchParams.get('captcha_id'); + if (!captchaId) throw new Error('GeeTest v4 captcha ID not found.'); + // STEP-03: Create and solve the GeeTest v4 task. + const task = new Tasks.GeeTestProxyless({ + websiteURL: page.url(), + version: 4, + initParameters: { captcha_id: captchaId }, + }); + return solveAndLogTaskId(solver, task); + }) + .then((solution) => { + // STEP-04: Log and submit the complete v4 solution to this demo endpoint. + console.log('Solution:', solution); + // Solution submission is site-specific; adapt this step to the target page. + // Inspect the target page's verification endpoint, required fields, and acceptance response before adapting it. + return page.evaluate((result) => { + return fetch('/api/v1/captcha-demo/gee-test-v4/verify', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify(result), + }).then((response) => response.json().then((body) => ({ ok: response.ok, body }))); + }, solution); + }) + .then(({ ok, body }) => { + // STEP-05: Require HTTP and application-level acceptance. + if (!ok || body.result !== 'success') + throw new Error('Page rejected the GeeTest v4 solution.'); + return 'GeeTest v4 solution accepted.'; + }) + ); +} + +/** Launch Chromium and run the complete GeeTest v4 example. */ +export function main() { + const solver = new CaptchaClient({ + clientKey: process.env.CAPTCHA_API_KEY || 'YOUR_API_KEY', + timeout: solverTimeout, + }); + let browser; + return puppeteer + .launch({ + headless: process.env.HEADLESS === 'true', + }) + .then((instance) => { + browser = instance; + return browser.newPage(); + }) + .then((page) => solveCaptcha(page, solver)) + .then((message) => console.log('Page confirmation:', message)) + .finally(() => browser?.close()); +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + // STEP-06: Report errors; main() closes Chromium in every outcome. + main().catch((error) => { + console.error(error); + process.exitCode = 1; + }); +} diff --git a/examples/normal_captcha/image_to_text.js b/examples/normal_captcha/image_to_text.js new file mode 100644 index 0000000..5ea6fd2 --- /dev/null +++ b/examples/normal_captcha/image_to_text.js @@ -0,0 +1,60 @@ +import { readFileSync } from 'node:fs'; +import { pathToFileURL } from 'node:url'; + +import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; + +/** + * This example shows how to solve an image-to-text CAPTCHA. It reads a local CAPTCHA image, + * describes the expected answer format, sends the task to the service, and prints the recognized + * text. It uses Tasks.ImageToText and CaptchaClient.solve(). + * + * How it works: + * STEP-01 - Create the SDK client. + * STEP-02 - Read the image and create the task. + * STEP-03 - Send the task and wait for the solver result. + * STEP-04 - Print the recognized text or report an error. + */ + +/** Solve a task with the SDK and log the task ID returned by createTask(). */ +function solveAndLogTaskId(solver, task) { + const loggingSolver = Object.create(solver); + loggingSolver.createTask = (...args) => + solver.createTask(...args).then((taskId) => { + console.log('Task ID:', taskId); + return taskId; + }); + return loggingSolver.solve(task); +} + +// STEP-01: Create the SDK client with the API key from CAPTCHA_API_KEY. +const client = new CaptchaClient({ + clientKey: process.env.CAPTCHA_API_KEY || 'YOUR_API_KEY', +}); +const lettersOnly = 2; + +// STEP-02: Load the sample image and describe the expected answer format. +const task = new Tasks.ImageToText({ + body: readFileSync(new URL('../../assets/text-captcha.png', import.meta.url)).toString('base64'), + numeric: lettersOnly, + minLength: 4, + maxLength: 6, +}); + +/** Solve the image task and print its recognized text. */ +export function main() { + return ( + // STEP-03: Send the image-to-text task and wait for the solver result. + solveAndLogTaskId(client, task).then((solution) => { + // STEP-04: Print the recognized text returned in solution.text. + console.log(solution.text); + return solution; + }) + ); +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + main().catch((error) => { + console.error(error); + process.exitCode = 1; + }); +} diff --git a/examples/normal_captcha/normal_captcha_canvas.js b/examples/normal_captcha/normal_captcha_canvas.js deleted file mode 100644 index a1b9905..0000000 --- a/examples/normal_captcha/normal_captcha_canvas.js +++ /dev/null @@ -1,67 +0,0 @@ -/** - * Solve an image CAPTCHA using its original pixels. - * The image is drawn to a canvas, sent to Captcha Solver, and the recognized - * text is typed into the form. Use TARGET_URL for a page you may automate. - */ -import { pathToFileURL } from 'node:url'; -import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; -import puppeteer from 'puppeteer-extra'; -import StealthPlugin from 'puppeteer-extra-plugin-stealth'; - -puppeteer.use(StealthPlugin()); -const IMAGE_SELECTOR = 'img[alt="normal captcha example"]'; -const ANSWER_SELECTOR = '#simple-captcha-field'; - -/** Solve the image CAPTCHA on an already opened page. */ -export async function solveCaptcha(page, solver) { - if (!process.env.TARGET_URL) throw new Error('Set TARGET_URL for this example.'); - - console.log('1. Opening the page'); - await page.goto(process.env.TARGET_URL, { waitUntil: 'domcontentloaded' }); - await page.waitForSelector(IMAGE_SELECTOR, { visible: true }); - - console.log('2. Reading the original image pixels through canvas'); - const body = await page.$eval(IMAGE_SELECTOR, (image) => { - const canvas = document.createElement('canvas'); - canvas.width = image.naturalWidth; - canvas.height = image.naturalHeight; - canvas.getContext('2d').drawImage(image, 0, 0); - return canvas.toDataURL('image/png').split(',')[1]; - }); - - const task = new Tasks.ImageToText({ body }); - console.log('3. Sending ImageToText task', { ...task.toDict(), body: `[${body.length} base64 characters]` }); - const solution = await solver.solve(task); - console.log('4. Recognized text:', solution.text); - if (!solution.text) throw new Error('Captcha Solver returned empty text.'); - - console.log('5. Typing the answer and submitting the form'); - await page.locator(ANSWER_SELECTOR).fill(solution.text); - await page.click(process.env.SUBMIT_SELECTOR || 'button[type="submit"], input[type="submit"]'); - - console.log('6. Waiting for page acceptance'); - const selector = process.env.SUCCESS_SELECTOR || 'p[class*="successMessage"]'; - await page.waitForSelector(selector, { visible: true }); - return page.$eval(selector, (element) => element.textContent.trim()); -} - -/** Run the complete standalone canvas example. */ -export async function main() { - const apiKey = process.env.CAPTCHA_API_KEY; - if (!apiKey || apiKey === 'your_api_key') throw new Error('Set CAPTCHA_API_KEY.'); - const solver = new CaptchaClient({ clientKey: apiKey }); - const browser = await puppeteer.launch({ - headless: process.env.HEADLESS === 'true', - executablePath: process.env.BROWSER_EXECUTABLE_PATH || undefined, - }); - try { - const page = await browser.newPage(); - console.log('Captcha solved successfully:', await solveCaptcha(page, solver)); - } finally { - await browser.close(); - } -} - -if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { - main().catch((error) => { console.error('Example failed:', error.message); process.exitCode = 1; }); -} diff --git a/examples/normal_captcha/normal_captcha_screenshot.js b/examples/normal_captcha/normal_captcha_screenshot.js deleted file mode 100644 index d1604e9..0000000 --- a/examples/normal_captcha/normal_captcha_screenshot.js +++ /dev/null @@ -1,63 +0,0 @@ -/** - * Solve a normal image CAPTCHA with a Puppeteer screenshot. - * The example captures the displayed image, sends it through the official SDK, - * types the recognized text, submits the form, and confirms acceptance. - */ -import { pathToFileURL } from 'node:url'; -import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; -import puppeteer from 'puppeteer-extra'; -import StealthPlugin from 'puppeteer-extra-plugin-stealth'; - -puppeteer.use(StealthPlugin()); -const IMAGE_SELECTOR = 'img[alt="normal captcha example"]'; -const ANSWER_SELECTOR = '#simple-captcha-field'; - -/** Solve the image CAPTCHA on an already opened page. */ -export async function solveCaptcha(page, solver) { - if (!process.env.TARGET_URL) throw new Error('Set TARGET_URL for this example.'); - console.log('1. Opening the page'); - await page.goto(process.env.TARGET_URL, { waitUntil: 'domcontentloaded' }); - const image = await page.waitForSelector(IMAGE_SELECTOR, { visible: true }); - - console.log('2. Taking a screenshot of the CAPTCHA image'); - const body = await image.screenshot({ encoding: 'base64', type: 'png' }); - const task = new Tasks.ImageToText({ body }); - - console.log('3. Sending ImageToText task', { - ...task.toDict(), - body: `[${body.length} base64 characters]`, - }); - const solution = await solver.solve(task); - console.log('4. Recognized text:', solution.text); - if (!solution.text) throw new Error('Captcha Solver returned empty text.'); - - console.log('5. Typing the answer and submitting the form'); - await page.locator(ANSWER_SELECTOR).fill(solution.text); - await page.click(process.env.SUBMIT_SELECTOR || 'button[type="submit"], input[type="submit"]'); - - console.log('6. Waiting for page acceptance'); - const selector = process.env.SUCCESS_SELECTOR || 'p[class*="successMessage"]'; - await page.waitForSelector(selector, { visible: true }); - return page.$eval(selector, (element) => element.textContent.trim()); -} - -/** Run the complete standalone screenshot example. */ -export async function main() { - const apiKey = process.env.CAPTCHA_API_KEY; - if (!apiKey || apiKey === 'your_api_key') throw new Error('Set CAPTCHA_API_KEY.'); - const solver = new CaptchaClient({ clientKey: apiKey }); - const browser = await puppeteer.launch({ - headless: process.env.HEADLESS === 'true', - executablePath: process.env.BROWSER_EXECUTABLE_PATH || undefined, - }); - try { - const page = await browser.newPage(); - console.log('Captcha solved successfully:', await solveCaptcha(page, solver)); - } finally { - await browser.close(); - } -} - -if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { - main().catch((error) => { console.error('Example failed:', error.message); process.exitCode = 1; }); -} diff --git a/examples/normal_captcha/normal_captcha_screenshot_params.js b/examples/normal_captcha/normal_captcha_screenshot_params.js deleted file mode 100644 index 3038dc8..0000000 --- a/examples/normal_captcha/normal_captcha_screenshot_params.js +++ /dev/null @@ -1,65 +0,0 @@ -/** - * Solve an image CAPTCHA screenshot with recognition hints. - * This version tells the API which characters and answer length to expect. - */ -import { pathToFileURL } from 'node:url'; -import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; -import puppeteer from 'puppeteer-extra'; -import StealthPlugin from 'puppeteer-extra-plugin-stealth'; - -puppeteer.use(StealthPlugin()); -const IMAGE_SELECTOR = 'img[alt="normal captcha example"]'; -const ANSWER_SELECTOR = '#simple-captcha-field'; - -/** Solve the image CAPTCHA on an already opened page. */ -export async function solveCaptcha(page, solver) { - if (!process.env.TARGET_URL) throw new Error('Set TARGET_URL for this example.'); - console.log('1. Opening the page'); - await page.goto(process.env.TARGET_URL, { waitUntil: 'domcontentloaded' }); - const image = await page.waitForSelector(IMAGE_SELECTOR, { visible: true }); - - console.log('2. Taking a screenshot of the CAPTCHA image'); - const body = await image.screenshot({ encoding: 'base64', type: 'png' }); - const task = new Tasks.ImageToText({ - body, - numeric: 4, - minLength: 4, - maxLength: 10, - }); - - console.log('3. Sending ImageToText task with recognition hints', { - ...task.toDict(), - body: `[${body.length} base64 characters]`, - }); - const solution = await solver.solve(task); - console.log('4. Recognized text:', solution.text); - if (!solution.text) throw new Error('Captcha Solver returned empty text.'); - - console.log('5. Typing the answer and submitting the form'); - await page.locator(ANSWER_SELECTOR).fill(solution.text); - await page.click(process.env.SUBMIT_SELECTOR || 'button[type="submit"], input[type="submit"]'); - const selector = process.env.SUCCESS_SELECTOR || 'p[class*="successMessage"]'; - await page.waitForSelector(selector, { visible: true }); - return page.$eval(selector, (element) => element.textContent.trim()); -} - -/** Run the complete standalone screenshot-with-parameters example. */ -export async function main() { - const apiKey = process.env.CAPTCHA_API_KEY; - if (!apiKey || apiKey === 'your_api_key') throw new Error('Set CAPTCHA_API_KEY.'); - const solver = new CaptchaClient({ clientKey: apiKey }); - const browser = await puppeteer.launch({ - headless: process.env.HEADLESS === 'true', - executablePath: process.env.BROWSER_EXECUTABLE_PATH || undefined, - }); - try { - const page = await browser.newPage(); - console.log('Captcha solved successfully:', await solveCaptcha(page, solver)); - } finally { - await browser.close(); - } -} - -if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { - main().catch((error) => { console.error('Example failed:', error.message); process.exitCode = 1; }); -} diff --git a/examples/reCAPTCHA/recaptcha_v2.js b/examples/reCAPTCHA/recaptcha_v2.js index e9bc0e7..cdd05a2 100644 --- a/examples/reCAPTCHA/recaptcha_v2.js +++ b/examples/reCAPTCHA/recaptcha_v2.js @@ -1,100 +1,139 @@ -/** - * Solve reCAPTCHA v2 with Puppeteer and Captcha Solver. - * - * This example opens a page, reads the reCAPTCHA site key, sends a task through - * the official SDK, puts the returned token into the form, submits it, and - * waits for the page to confirm that the token was accepted. - */ import { pathToFileURL } from 'node:url'; import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; import puppeteer from 'puppeteer-extra'; import StealthPlugin from 'puppeteer-extra-plugin-stealth'; +/** + * This example shows how to solve Google reCAPTCHA v2 without using a proxy. It opens the demo + * page, extracts the site key and widget options, sends the task to the service, inserts the + * returned token into the form, and verifies that the page accepts it. It uses + * Tasks.RecaptchaV2Proxyless and CaptchaClient.solve(). + * + * To use this example on another page, change the target URL and update the site-key selector. + * Token injection and submission are site-specific. You must inspect the target page and + * determine the correct way to pass the token yourself. + * + * How it works: + * STEP-01 - Configure the target and create the SDK client. + * STEP-02 - Launch Chromium and open the target page. + * STEP-03 - Extract the reCAPTCHA parameters from the page. + * STEP-04 - Create the task and wait for the solver result. + * STEP-05 - Log the solution and inject its token into the form. + * STEP-06 - Submit the form and verify that the page accepts the token. + * STEP-07 - Handle errors and close Chromium. + */ + puppeteer.use(StealthPlugin()); -const DEFAULT_URL = 'https://www.google.com/recaptcha/api2/demo'; +/** Solve a task with the SDK and log the task ID returned by createTask(). */ +function solveAndLogTaskId(solver, task) { + const loggingSolver = Object.create(solver); + loggingSolver.createTask = (...args) => + solver.createTask(...args).then((taskId) => { + console.log('Task ID:', taskId); + return taskId; + }); + return loggingSolver.solve(task); +} + +// STEP-01: Read the target URL and create the SDK client. +const websiteURL = + process.env.RECAPTCHA_V2_TARGET_URL || 'https://www.google.com/recaptcha/api2/demo'; +const client = new CaptchaClient({ + clientKey: process.env.CAPTCHA_API_KEY || 'YOUR_API_KEY', +}); + +let browser; /** - * Solve and submit reCAPTCHA v2 on an already opened page. + * Solve and submit reCAPTCHA v2 on an opened Puppeteer page. * @param {import('puppeteer').Page} page Open Puppeteer page. * @param {CaptchaClient} solver Configured Captcha Solver client. - * @returns {Promise} Text displayed after successful submission. + * @returns {Promise} Page text that confirms acceptance. */ -export async function solveCaptcha(page, solver) { - console.log('1. Opening the page'); - await page.goto(process.env.TARGET_URL || DEFAULT_URL, { waitUntil: 'domcontentloaded' }); - await page.waitForSelector('[data-sitekey]'); - - console.log('2. Reading reCAPTCHA parameters from the page'); - const captcha = await page.$eval('[data-sitekey]', (element) => ({ - websiteKey: element.getAttribute('data-sitekey'), - isInvisible: element.getAttribute('data-size') === 'invisible', - recaptchaDataSValue: element.getAttribute('data-s') || undefined, - })); - - const task = new Tasks.RecaptchaV2Proxyless({ - websiteURL: page.url(), - ...captcha, - userAgent: await page.evaluate(() => navigator.userAgent), - }); - console.log('3. Sending the task to Captcha Solver', task.toDict()); - const solution = await solver.solve(task); - console.log('4. Solution received', solution); - - if (!solution.gRecaptchaResponse) { - throw new Error('Captcha Solver returned an empty reCAPTCHA token.'); - } +export function solveCaptcha(page, solver = client) { + const siteKeySelector = '[data-sitekey]'; + const submitSelector = 'button[type="submit"], input[type="submit"]'; + const successSelector = '.recaptcha-success, p[class*="successMessage"]'; - // Token injection and submission are site-specific; adapt this step to the target page. - console.log('5. Writing the token into g-recaptcha-response'); - await page.evaluate((token) => { - let response = document.querySelector('[name="g-recaptcha-response"]'); - if (!response) { - response = document.createElement('textarea'); - response.name = 'g-recaptcha-response'; - document.querySelector('form')?.append(response); - } - response.value = token; - response.dispatchEvent(new Event('input', { bubbles: true })); - response.dispatchEvent(new Event('change', { bubbles: true })); - }, solution.gRecaptchaResponse); + // STEP-02: Open the configured page containing reCAPTCHA v2. + return ( + page + .goto(process.env.RECAPTCHA_V2_TARGET_URL || websiteURL, { waitUntil: 'domcontentloaded' }) + .then(() => page.waitForSelector(siteKeySelector)) + // STEP-03: Extract widget options and the browser User-Agent from the page. + .then(() => + Promise.all([ + page.$eval(siteKeySelector, (element) => ({ + websiteKey: element.getAttribute('data-sitekey'), + isInvisible: element.getAttribute('data-size') === 'invisible', + recaptchaDataSValue: element.getAttribute('data-s') || undefined, + })), + page.evaluate(() => navigator.userAgent), + ]), + ) + // STEP-04: Build the task and wait for the solver result. + .then(([captcha, userAgent]) => { + if (!captcha.websiteKey) throw new Error('reCAPTCHA site key not found.'); + const task = new Tasks.RecaptchaV2Proxyless({ + websiteURL: page.url(), + ...captcha, + userAgent, + }); + return solveAndLogTaskId(solver, task); + }) + // STEP-05: Log the solution and inject its token into the form. + .then((solution) => { + console.log('Solution:', solution); + if (!solution.gRecaptchaResponse) { + throw new Error('Captcha Solver returned an empty reCAPTCHA token.'); + } - console.log('6. Submitting the form'); - await page.click(process.env.SUBMIT_SELECTOR || 'button[type="submit"], input[type="submit"]'); - - console.log('7. Waiting for the page to accept the solution'); - const successSelector = process.env.SUCCESS_SELECTOR || '.recaptcha-success, p[class*="successMessage"]'; - await page.waitForSelector(successSelector, { visible: true }); - return page.$eval(successSelector, (element) => element.textContent.trim()); + // Token injection and submission are site-specific; adapt this step to the target page. + // Put the token into the field that this form sends to its verification endpoint. + return page.evaluate((token) => { + let response = document.querySelector('[name="g-recaptcha-response"]'); + if (!response) { + response = document.createElement('textarea'); + response.name = 'g-recaptcha-response'; + document.querySelector('form')?.append(response); + } + response.value = token; + response.dispatchEvent(new Event('input', { bubbles: true })); + response.dispatchEvent(new Event('change', { bubbles: true })); + }, solution.gRecaptchaResponse); + }) + // STEP-06: Submit the form and require an explicit page confirmation. + .then(() => page.click(submitSelector)) + .then(() => page.waitForSelector(successSelector, { visible: true })) + .then(() => page.$eval(successSelector, (element) => element.textContent.trim())) + ); } -/** Run the complete standalone example. */ -export async function main() { - const apiKey = process.env.CAPTCHA_API_KEY; - if (!apiKey || apiKey === 'your_api_key') { - throw new Error('Set CAPTCHA_API_KEY in .env or the environment.'); - } - - console.log('Creating Captcha Solver client from CAPTCHA_API_KEY'); - const solver = new CaptchaClient({ clientKey: apiKey }); - const browser = await puppeteer.launch({ - headless: process.env.HEADLESS === 'true', - executablePath: process.env.BROWSER_EXECUTABLE_PATH || undefined, - defaultViewport: { width: 1280, height: 900 }, - }); - - try { - const page = await browser.newPage(); - const result = await solveCaptcha(page, solver); - console.log('Captcha solved successfully:', result); - } finally { - await browser.close(); - } +/** Run the complete standalone reCAPTCHA v2 example. */ +export function main() { + // Launch Chromium and create a browser page. + return ( + puppeteer + .launch({ + headless: process.env.HEADLESS === 'true', + defaultViewport: { width: 1280, height: 900 }, + }) + .then((instance) => { + browser = instance; + return browser.newPage(); + }) + .then((page) => solveCaptcha(page)) + .then((message) => console.log(`Page confirmation: ${message}`)) + // STEP-07: Always close Chromium and let callers handle failures. + .finally(() => browser?.close()) + ); } if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + // Report errors and set a nonzero exit code when this file runs directly. main().catch((error) => { - console.error('Example failed:', error.message); + console.error(error); process.exitCode = 1; }); } diff --git a/examples/reCAPTCHA/recaptcha_v2_callback.js b/examples/reCAPTCHA/recaptcha_v2_callback.js new file mode 100644 index 0000000..9829741 --- /dev/null +++ b/examples/reCAPTCHA/recaptcha_v2_callback.js @@ -0,0 +1,118 @@ +import { pathToFileURL } from 'node:url'; +import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; +import puppeteer from 'puppeteer-extra'; +import StealthPlugin from 'puppeteer-extra-plugin-stealth'; + +/** + * Solve reCAPTCHA v2 and pass the token to a callback whose name is known. This standalone + * example uses Tasks.RecaptchaV2Proxyless and CaptchaClient.solve(). Callback delivery is the + * acceptance boundary; adapt the final check when the target exposes a server-side result. + * Token injection and submission are site-specific. You must inspect the target page and + * determine the correct way to pass the token yourself. + * + * How it works: + * STEP-01 - Configure the SDK client and target. + * STEP-02 - Launch Chromium and open the target page. + * STEP-03 - Extract the reCAPTCHA parameters from the page. + * STEP-04 - Create the task and wait for the solver result. + * STEP-05 - Log the solution and invoke the configured callback. + * STEP-06 - Confirm that the callback received the token. + * STEP-07 - Handle errors and close Chromium. + */ + +puppeteer.use(StealthPlugin()); + +/** Solve a task with the SDK and log the task ID returned by createTask(). */ +function solveAndLogTaskId(solver, task) { + const loggingSolver = Object.create(solver); + loggingSolver.createTask = (...args) => + solver.createTask(...args).then((taskId) => { + console.log('Task ID:', taskId); + return taskId; + }); + return loggingSolver.solve(task); +} +const websiteURL = + process.env.RECAPTCHA_V2_TARGET_URL || 'https://www.google.com/recaptcha/api2/demo'; +const client = new CaptchaClient({ clientKey: process.env.CAPTCHA_API_KEY || 'YOUR_API_KEY' }); +let browser; + +/** Solve reCAPTCHA v2 and invoke a named page callback. */ +export function solveCaptcha(page, solver = client) { + // STEP-02: Open the target page in the launched Chromium instance. + return ( + page + .goto(process.env.RECAPTCHA_V2_TARGET_URL || websiteURL, { waitUntil: 'domcontentloaded' }) + // STEP-03: Extract the public widget parameters from the page. + .then(() => + page.$eval('[data-sitekey]', (element) => ({ + websiteKey: element.getAttribute('data-sitekey'), + isInvisible: element.getAttribute('data-size') === 'invisible', + })), + ) + .then((captcha) => + // STEP-04: Create the task and wait for the solver result. + page + .evaluate(() => navigator.userAgent) + .then((userAgent) => + solveAndLogTaskId( + solver, + new Tasks.RecaptchaV2Proxyless({ websiteURL: page.url(), ...captcha, userAgent }), + ), + ), + ) + .then((solution) => { + // STEP-05: Token injection and submission are site-specific; this page uses a callback. + console.log('Solution:', solution); + if (!solution.gRecaptchaResponse) + throw new Error('Captcha Solver returned an empty token.'); + const callbackName = process.env.RECAPTCHA_V2_CALLBACK || 'verifyDemoRecaptcha'; + return page + .evaluate( + (name, token) => { + const parts = name.split('.'); + let owner = window; + for (const part of parts.slice(0, -1)) owner = owner?.[part]; + const callback = owner?.[parts.at(-1)]; + if (typeof callback !== 'function') + throw new Error(`Callback ${name} was not found.`); + callback.call(owner, token); + window.__captchaCallbackToken = token; + }, + callbackName, + solution.gRecaptchaResponse, + ) + .then(() => solution.gRecaptchaResponse); + }) + .then((token) => + // STEP-06: Confirm callback delivery without claiming server-side acceptance. + page + .waitForFunction((expected) => window.__captchaCallbackToken === expected, {}, token) + .then(() => 'reCAPTCHA callback received the solver token.'), + ) + ); +} + +/** Run the complete standalone callback example. */ +export function main() { + // STEP-01: Configure the browser and SDK client above, then launch Chromium. + return ( + puppeteer + .launch({ headless: process.env.HEADLESS === 'true' }) + .then((instance) => { + browser = instance; + return browser.newPage(); + }) + .then((page) => solveCaptcha(page)) + .then((message) => console.log(`Page confirmation: ${message}`)) + // STEP-07: Always close Chromium. + .finally(() => browser?.close()) + ); +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + main().catch((error) => { + console.error(error); + process.exitCode = 1; + }); +} diff --git a/examples/reCAPTCHA/recaptcha_v2_callback_auto.js b/examples/reCAPTCHA/recaptcha_v2_callback_auto.js new file mode 100644 index 0000000..736553c --- /dev/null +++ b/examples/reCAPTCHA/recaptcha_v2_callback_auto.js @@ -0,0 +1,117 @@ +import { pathToFileURL } from 'node:url'; +import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; +import puppeteer from 'puppeteer-extra'; +import StealthPlugin from 'puppeteer-extra-plugin-stealth'; + +/** + * Solve reCAPTCHA v2 when the callback name is unknown. The example discovers the callback in + * the widget or reCAPTCHA client configuration, then uses Tasks.RecaptchaV2Proxyless and + * CaptchaClient.solve(). Callback delivery is verified separately from the solver result. + * Token injection and submission are site-specific. You must inspect the target page and + * determine the correct way to pass the token yourself. + * + * How it works: + * STEP-01 - Configure the SDK client and target. + * STEP-02 - Launch Chromium and open the target page. + * STEP-03 - Extract the reCAPTCHA parameters and discover the widget callback. + * STEP-04 - Create the task and wait for the solver result. + * STEP-05 - Log the solution and invoke the discovered callback. + * STEP-06 - Confirm that the callback received the token. + * STEP-07 - Handle errors and close Chromium. + */ + +puppeteer.use(StealthPlugin()); + +/** Solve a task with the SDK and log the task ID returned by createTask(). */ +function solveAndLogTaskId(solver, task) { + const loggingSolver = Object.create(solver); + loggingSolver.createTask = (...args) => + solver.createTask(...args).then((taskId) => { + console.log('Task ID:', taskId); + return taskId; + }); + return loggingSolver.solve(task); +} +const websiteURL = + process.env.RECAPTCHA_V2_TARGET_URL || 'https://www.google.com/recaptcha/api2/demo'; +const client = new CaptchaClient({ clientKey: process.env.CAPTCHA_API_KEY || 'YOUR_API_KEY' }); +let browser; + +/** Discover the active widget callback and retain it inside the page. */ +function discoverCaptcha(page) { + return page + .waitForFunction(() => { + const widget = document.querySelector('[data-sitekey][data-callback]'); + if (!widget) return false; + const parts = widget.dataset.callback.split('.'); + let callback = window; + for (const part of parts) callback = callback?.[part]; + if (typeof callback !== 'function') return false; + window.__captchaCallback = callback; + return { + websiteKey: widget.dataset.sitekey, + isInvisible: widget.dataset.size === 'invisible', + }; + }) + .then((handle) => handle.jsonValue().finally(() => handle.dispose())); +} + +/** Solve reCAPTCHA v2 and invoke its automatically discovered callback. */ +export function solveCaptcha(page, solver = client) { + // STEP-02: Open the target page in the launched Chromium instance. + return ( + page + .goto(process.env.RECAPTCHA_V2_TARGET_URL || websiteURL, { waitUntil: 'domcontentloaded' }) + // STEP-03: Extract the widget parameters and discover its callback. + .then(() => Promise.all([discoverCaptcha(page), page.evaluate(() => navigator.userAgent)])) + // STEP-04: Create the task and wait for the solver result. + .then(([captcha, userAgent]) => + solveAndLogTaskId( + solver, + new Tasks.RecaptchaV2Proxyless({ websiteURL: page.url(), ...captcha, userAgent }), + ), + ) + .then((solution) => { + // STEP-05: Token injection and submission are site-specific; this page uses a callback. + console.log('Solution:', solution); + if (!solution.gRecaptchaResponse) + throw new Error('Captcha Solver returned an empty token.'); + return page + .evaluate((token) => { + window.__captchaCallback(token); + window.__captchaCallbackToken = token; + }, solution.gRecaptchaResponse) + .then(() => solution.gRecaptchaResponse); + }) + .then((token) => + // STEP-06: Confirm callback delivery without claiming server-side acceptance. + page + .waitForFunction((expected) => window.__captchaCallbackToken === expected, {}, token) + .then(() => 'Discovered reCAPTCHA callback received the solver token.'), + ) + ); +} + +/** Run the complete standalone callback-discovery example. */ +export function main() { + // STEP-01: Configure the browser and SDK client above, then launch Chromium. + return ( + puppeteer + .launch({ headless: process.env.HEADLESS === 'true' }) + .then((instance) => { + browser = instance; + return browser.newPage(); + }) + .then((page) => solveCaptcha(page)) + .then((message) => console.log(`Page confirmation: ${message}`)) + // STEP-07: Always close Chromium. + .finally(() => browser?.close()) + ); +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + main().catch((error) => { + console.error(error); + process.exitCode = 1; + }); +} diff --git a/examples/reCAPTCHA/recaptcha_v2_callback_proxy.js b/examples/reCAPTCHA/recaptcha_v2_callback_proxy.js index cd82310..1d2b13b 100644 --- a/examples/reCAPTCHA/recaptcha_v2_callback_proxy.js +++ b/examples/reCAPTCHA/recaptcha_v2_callback_proxy.js @@ -1,82 +1,143 @@ -/** - * Solve callback-based reCAPTCHA v2 through an HTTP proxy. - * Chrome and the API task use the same proxy. The callback is discovered from - * the widget's data-callback attribute, then called with the returned token. - */ import { pathToFileURL } from 'node:url'; import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; import puppeteer from 'puppeteer-extra'; import StealthPlugin from 'puppeteer-extra-plugin-stealth'; +/** + * Solve callback-based reCAPTCHA v2 through the same proxy in Chromium and the API. It uses + * Tasks.RecaptchaV2 and CaptchaClient.solve(). Callback delivery is verified, but does not by + * itself prove server-side acceptance. + * Token injection and submission are site-specific. You must inspect the target page and + * determine the correct way to pass the token yourself. + * + * How it works: + * STEP-01 - Read proxy settings and configure the SDK client. + * STEP-02 - Launch Chromium through the proxy and open the target. + * STEP-03 - Extract the widget parameters. + * STEP-04 - Create and solve a proxy-based task. + * STEP-05 - Log the solution and invoke the configured callback. + * STEP-06 - Confirm callback delivery. + * STEP-07 - Handle errors and close Chromium. + */ + puppeteer.use(StealthPlugin()); -/** Read proxy settings from environment variables. */ +/** Solve a task with the SDK and log the task ID returned by createTask(). */ +function solveAndLogTaskId(solver, task) { + const loggingSolver = Object.create(solver); + loggingSolver.createTask = (...args) => + solver.createTask(...args).then((taskId) => { + console.log('Task ID:', taskId); + return taskId; + }); + return loggingSolver.solve(task); +} +const websiteURL = + process.env.RECAPTCHA_V2_TARGET_URL || 'https://www.google.com/recaptcha/api2/demo'; +const client = new CaptchaClient({ clientKey: process.env.CAPTCHA_API_KEY || 'YOUR_API_KEY' }); +let browser; + +/** Read and validate proxy settings from the environment. */ function getProxy() { - const proxyAddress = process.env.PROXY_ADDRESS; const proxyPort = Number(process.env.PROXY_PORT); - if (!proxyAddress || !Number.isInteger(proxyPort)) throw new Error('Set PROXY_ADDRESS and PROXY_PORT.'); + if (!process.env.PROXY_ADDRESS || !Number.isInteger(proxyPort)) { + throw new Error('Set PROXY_ADDRESS and PROXY_PORT for the proxy example.'); + } return { - proxyType: process.env.PROXY_TYPE || 'http', proxyAddress, proxyPort, + proxyType: process.env.PROXY_TYPE || 'http', + proxyAddress: process.env.PROXY_ADDRESS, + proxyPort, proxyLogin: process.env.PROXY_LOGIN || undefined, proxyPassword: process.env.PROXY_PASSWORD || undefined, }; } -/** Solve reCAPTCHA and invoke its named callback. */ -export async function solveCaptcha(page, solver, proxy) { - if (!process.env.TARGET_URL) throw new Error('Set TARGET_URL for this example.'); - console.log('1. Opening the page through the configured proxy'); - await page.goto(process.env.TARGET_URL, { waitUntil: 'domcontentloaded' }); - await page.waitForSelector('[data-sitekey][data-callback]'); - - console.log('2. Reading CAPTCHA parameters and callback name'); - const captcha = await page.$eval('[data-sitekey][data-callback]', (element) => ({ - websiteKey: element.dataset.sitekey, - callbackName: element.dataset.callback, - isInvisible: element.dataset.size === 'invisible', - })); - const task = new Tasks.RecaptchaV2({ - websiteURL: page.url(), websiteKey: captcha.websiteKey, - isInvisible: captcha.isInvisible, userAgent: await page.evaluate(() => navigator.userAgent), - ...proxy, - }); - console.log('3. Sending the task to Captcha Solver'); - const solution = await solver.solve(task); - console.log('4. Solution received', solution); - if (!solution.gRecaptchaResponse) throw new Error('Captcha Solver returned an empty token.'); - - // Token injection and submission are site-specific; adapt this step to the target page. - console.log(`5. Calling ${captcha.callbackName}`); - await page.evaluate((name, token) => { - const callback = name.split('.').reduce((value, key) => value?.[key], window); - if (typeof callback !== 'function') throw new Error(`Callback ${name} was not found.`); - callback(token); - }, captcha.callbackName, solution.gRecaptchaResponse); - const selector = process.env.SUCCESS_SELECTOR || 'p[class*="successMessage"]'; - await page.waitForSelector(selector, { visible: true }); - return page.$eval(selector, (element) => element.textContent.trim()); +/** Solve proxy-based reCAPTCHA v2 and invoke a named page callback. */ +export function solveCaptcha(page, solver = client, proxy = getProxy()) { + // STEP-02: Open the target through Chromium's configured proxy. + return ( + page + .goto(process.env.RECAPTCHA_V2_TARGET_URL || websiteURL, { waitUntil: 'domcontentloaded' }) + // STEP-03: Read widget parameters and browser identity. + .then(() => + Promise.all([ + page.$eval('[data-sitekey]', (element) => ({ + websiteKey: element.getAttribute('data-sitekey'), + isInvisible: element.getAttribute('data-size') === 'invisible', + })), + page.evaluate(() => navigator.userAgent), + ]), + ) + // STEP-04: Create the proxy task with the same network identity. + .then(([captcha, userAgent]) => + solveAndLogTaskId( + solver, + new Tasks.RecaptchaV2({ + websiteURL: page.url(), + ...captcha, + ...proxy, + userAgent, + }), + ), + ) + .then((solution) => { + // STEP-05: Token injection and submission are site-specific; this page uses a callback. + console.log('Solution:', solution); + if (!solution.gRecaptchaResponse) + throw new Error('Captcha Solver returned an empty token.'); + const callbackName = process.env.RECAPTCHA_V2_CALLBACK || 'verifyDemoRecaptcha'; + return page + .evaluate( + (name, token) => { + const parts = name.split('.'); + let owner = window; + for (const part of parts.slice(0, -1)) owner = owner?.[part]; + const callback = owner?.[parts.at(-1)]; + if (typeof callback !== 'function') + throw new Error(`Callback ${name} was not found.`); + callback.call(owner, token); + window.__captchaCallbackToken = token; + }, + callbackName, + solution.gRecaptchaResponse, + ) + .then(() => solution.gRecaptchaResponse); + }) + // STEP-06: Confirm callback delivery separately from the SDK result. + .then((token) => + page.waitForFunction((expected) => window.__captchaCallbackToken === expected, {}, token), + ) + .then(() => 'reCAPTCHA callback received the solver token through the proxy flow.') + ); } /** Run the complete standalone proxy callback example. */ -export async function main() { - const apiKey = process.env.CAPTCHA_API_KEY; - if (!apiKey || apiKey === 'your_api_key') throw new Error('Set CAPTCHA_API_KEY.'); +export function main() { + // STEP-01: Validate proxy configuration before launching Chromium. const proxy = getProxy(); - const solver = new CaptchaClient({ clientKey: apiKey }); - const browser = await puppeteer.launch({ - headless: process.env.HEADLESS === 'true', - executablePath: process.env.BROWSER_EXECUTABLE_PATH || undefined, - args: [`--proxy-server=${proxy.proxyType}://${proxy.proxyAddress}:${proxy.proxyPort}`], - }); - try { - const page = await browser.newPage(); - if (proxy.proxyLogin) await page.authenticate({ username: proxy.proxyLogin, password: proxy.proxyPassword }); - console.log('Captcha solved successfully:', await solveCaptcha(page, solver, proxy)); - } finally { - await browser.close(); - } + const endpoint = `${proxy.proxyType}://${proxy.proxyAddress}:${proxy.proxyPort}`; + return ( + puppeteer + .launch({ headless: process.env.HEADLESS === 'true', args: [`--proxy-server=${endpoint}`] }) + .then((instance) => { + browser = instance; + return browser.newPage(); + }) + .then((page) => { + const authentication = proxy.proxyLogin + ? page.authenticate({ username: proxy.proxyLogin, password: proxy.proxyPassword }) + : page.evaluate(() => true); + return authentication.then(() => solveCaptcha(page, client, proxy)); + }) + .then((message) => console.log(`Page confirmation: ${message}`)) + // STEP-07: Always close Chromium. + .finally(() => browser?.close()) + ); } if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { - main().catch((error) => { console.error('Example failed:', error.message); process.exitCode = 1; }); + main().catch((error) => { + console.error(error); + process.exitCode = 1; + }); } diff --git a/examples/reCAPTCHA/recaptcha_v2_callback_variant1.js b/examples/reCAPTCHA/recaptcha_v2_callback_variant1.js deleted file mode 100644 index cd08dfb..0000000 --- a/examples/reCAPTCHA/recaptcha_v2_callback_variant1.js +++ /dev/null @@ -1,72 +0,0 @@ -/** - * Solve reCAPTCHA v2 when the page expects a known JavaScript callback. - * Set TARGET_URL and, if necessary, CALLBACK_NAME (default: verifyDemoRecaptcha). - */ -import { pathToFileURL } from 'node:url'; -import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; -import puppeteer from 'puppeteer-extra'; -import StealthPlugin from 'puppeteer-extra-plugin-stealth'; - -puppeteer.use(StealthPlugin()); - -/** Solve reCAPTCHA and invoke the page callback with the returned token. */ -export async function solveCaptcha(page, solver) { - if (!process.env.TARGET_URL) throw new Error('Set TARGET_URL for this example.'); - console.log('1. Opening the callback-based reCAPTCHA page'); - await page.goto(process.env.TARGET_URL, { waitUntil: 'domcontentloaded' }); - await page.waitForSelector('[data-sitekey]'); - - console.log('2. Reading reCAPTCHA parameters'); - const captcha = await page.$eval('[data-sitekey]', (element) => ({ - websiteKey: element.getAttribute('data-sitekey'), - isInvisible: element.getAttribute('data-size') === 'invisible', - })); - const task = new Tasks.RecaptchaV2Proxyless({ - websiteURL: page.url(), - ...captcha, - userAgent: await page.evaluate(() => navigator.userAgent), - }); - - console.log('3. Sending the task to Captcha Solver', task.toDict()); - const solution = await solver.solve(task); - console.log('4. Solution received', solution); - if (!solution.gRecaptchaResponse) throw new Error('Captcha Solver returned an empty token.'); - - // Token injection and submission are site-specific; adapt this step to the target page. - const callbackName = process.env.CALLBACK_NAME || 'verifyDemoRecaptcha'; - console.log(`5. Calling ${callbackName} with the returned token`); - await page.evaluate((name, token) => { - const parts = name.split('.'); - let owner = window; - for (const part of parts.slice(0, -1)) owner = owner?.[part]; - const callback = owner?.[parts.at(-1)]; - if (typeof callback !== 'function') throw new Error(`Callback ${name} was not found.`); - callback.call(owner, token); - }, callbackName, solution.gRecaptchaResponse); - - console.log('6. Waiting for page acceptance'); - const selector = process.env.SUCCESS_SELECTOR || 'p[class*="successMessage"]'; - await page.waitForSelector(selector, { visible: true }); - return page.$eval(selector, (element) => element.textContent.trim()); -} - -/** Run the complete standalone callback example. */ -export async function main() { - const apiKey = process.env.CAPTCHA_API_KEY; - if (!apiKey || apiKey === 'your_api_key') throw new Error('Set CAPTCHA_API_KEY.'); - const solver = new CaptchaClient({ clientKey: apiKey }); - const browser = await puppeteer.launch({ - headless: process.env.HEADLESS === 'true', - executablePath: process.env.BROWSER_EXECUTABLE_PATH || undefined, - }); - try { - const page = await browser.newPage(); - console.log('Captcha solved successfully:', await solveCaptcha(page, solver)); - } finally { - await browser.close(); - } -} - -if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { - main().catch((error) => { console.error('Example failed:', error.message); process.exitCode = 1; }); -} diff --git a/examples/reCAPTCHA/recaptcha_v2_callback_variant2.js b/examples/reCAPTCHA/recaptcha_v2_callback_variant2.js deleted file mode 100644 index 74c96fc..0000000 --- a/examples/reCAPTCHA/recaptcha_v2_callback_variant2.js +++ /dev/null @@ -1,92 +0,0 @@ -/** - * Solve reCAPTCHA v2 when the callback name is unknown. - * The example discovers the callback in the live reCAPTCHA configuration, - * keeps the function inside the page, solves the task, and invokes it. - */ -import { pathToFileURL } from 'node:url'; -import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; -import puppeteer from 'puppeteer-extra'; -import StealthPlugin from 'puppeteer-extra-plugin-stealth'; - -puppeteer.use(StealthPlugin()); - -/** Find the active reCAPTCHA callback and return its public task parameters. */ -async function discoverCaptcha(page) { - const handle = await page.waitForFunction(() => { - const resolveName = (name) => name.split('.').reduce((value, key) => value?.[key], window); - const widget = document.querySelector('[data-sitekey][data-callback]'); - if (widget && typeof resolveName(widget.dataset.callback) === 'function') { - window.__captchaCallback = resolveName(widget.dataset.callback); - return { websiteKey: widget.dataset.sitekey, isInvisible: widget.dataset.size === 'invisible' }; - } - - const visited = new WeakSet(); - const search = (value, depth = 0) => { - if (!value || typeof value !== 'object' || depth > 6 || visited.has(value) || value instanceof Node) return null; - visited.add(value); - if (typeof value.sitekey === 'string' && value.callback) { - const callback = typeof value.callback === 'string' ? resolveName(value.callback) : value.callback; - if (typeof callback === 'function') { - window.__captchaCallback = callback.bind(value); - return { websiteKey: value.sitekey, isInvisible: value.size === 'invisible' }; - } - } - for (const child of Object.values(value)) { - const result = search(child, depth + 1); - if (result) return result; - } - return null; - }; - return search(window.___grecaptcha_cfg?.clients); - }); - const captcha = await handle.jsonValue(); - await handle.dispose(); - return captcha; -} - -/** Solve reCAPTCHA and invoke the automatically discovered callback. */ -export async function solveCaptcha(page, solver) { - if (!process.env.TARGET_URL) throw new Error('Set TARGET_URL for this example.'); - console.log('1. Opening the callback-based reCAPTCHA page'); - await page.goto(process.env.TARGET_URL, { waitUntil: 'domcontentloaded' }); - - console.log('2. Discovering the callback and CAPTCHA parameters'); - const captcha = await discoverCaptcha(page); - const task = new Tasks.RecaptchaV2Proxyless({ - websiteURL: page.url(), - ...captcha, - userAgent: await page.evaluate(() => navigator.userAgent), - }); - console.log('3. Sending the task to Captcha Solver', task.toDict()); - const solution = await solver.solve(task); - console.log('4. Solution received', solution); - if (!solution.gRecaptchaResponse) throw new Error('Captcha Solver returned an empty token.'); - - // Token injection and submission are site-specific; adapt this step to the target page. - console.log('5. Passing the token to the discovered callback'); - await page.evaluate((token) => window.__captchaCallback(token), solution.gRecaptchaResponse); - const selector = process.env.SUCCESS_SELECTOR || 'p[class*="successMessage"]'; - await page.waitForSelector(selector, { visible: true }); - return page.$eval(selector, (element) => element.textContent.trim()); -} - -/** Run the complete standalone callback-discovery example. */ -export async function main() { - const apiKey = process.env.CAPTCHA_API_KEY; - if (!apiKey || apiKey === 'your_api_key') throw new Error('Set CAPTCHA_API_KEY.'); - const solver = new CaptchaClient({ clientKey: apiKey }); - const browser = await puppeteer.launch({ - headless: process.env.HEADLESS === 'true', - executablePath: process.env.BROWSER_EXECUTABLE_PATH || undefined, - }); - try { - const page = await browser.newPage(); - console.log('Captcha solved successfully:', await solveCaptcha(page, solver)); - } finally { - await browser.close(); - } -} - -if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { - main().catch((error) => { console.error('Example failed:', error.message); process.exitCode = 1; }); -} diff --git a/examples/reCAPTCHA/recaptcha_v2_enterprise.js b/examples/reCAPTCHA/recaptcha_v2_enterprise.js new file mode 100644 index 0000000..1f11f06 --- /dev/null +++ b/examples/reCAPTCHA/recaptcha_v2_enterprise.js @@ -0,0 +1,105 @@ +import { pathToFileURL } from 'node:url'; +import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; +import puppeteer from 'puppeteer-extra'; +import StealthPlugin from 'puppeteer-extra-plugin-stealth'; + +/** + * This example solves reCAPTCHA v2 Enterprise without a proxy. It extracts the site key, creates + * Tasks.RecaptchaV2EnterpriseProxyless, logs and injects the returned token, submits the form, + * and requires an explicit page confirmation. It uses CaptchaClient.solve(). + * + * To use it on another page, change RECAPTCHA_ENTERPRISE_TARGET_URL and inspect its site key, + * enterprise payload, token field, submission flow, and success indicator before adapting them. + * Token injection and submission are site-specific. You must inspect the target page and + * determine the correct way to pass the token yourself. + * + * How it works: + * STEP-01 - Open the configured target page. + * STEP-02 - Extract the Enterprise site key. + * STEP-03 - Create and solve the Enterprise task. + * STEP-04 - Log and inject the returned token. + * STEP-05 - Submit the form and verify page acceptance. + * STEP-06 - Handle errors and close Chromium. + */ + +puppeteer.use(StealthPlugin()); + +/** Solve a task with the SDK and log the task ID returned by createTask(). */ +function solveAndLogTaskId(solver, task) { + const loggingSolver = Object.create(solver); + loggingSolver.createTask = (...args) => + solver.createTask(...args).then((taskId) => { + console.log('Task ID:', taskId); + return taskId; + }); + return loggingSolver.solve(task); +} +const DEFAULT_URL = 'https://example.com/page_with_recaptcha_v2_enterprise'; +const submitSelector = 'button[type="submit"]'; +const successSelector = 'p[class*="successMessage"]'; + +/** Solve and submit reCAPTCHA Enterprise on an already opened page. */ +export function solveCaptcha(page, solver) { + const websiteURL = process.env.RECAPTCHA_ENTERPRISE_TARGET_URL || DEFAULT_URL; + + // STEP-01: Open the configured target page. + return page + .goto(websiteURL, { waitUntil: 'domcontentloaded' }) + .then(() => page.$eval('[data-sitekey]', (element) => element.getAttribute('data-sitekey'))) + .then((websiteKey) => { + // STEP-02: Validate the extracted Enterprise site key. + if (!websiteKey) throw new Error('Enterprise site key not found.'); + // STEP-03: Create and solve the Enterprise task. + const task = new Tasks.RecaptchaV2EnterpriseProxyless({ + websiteURL: page.url(), + websiteKey, + isInvisible: false, + }); + return solveAndLogTaskId(solver, task); + }) + .then((solution) => { + // STEP-04: Log and inject the token into this page's response field. + console.log('Solution:', solution); + if (!solution.gRecaptchaResponse) throw new Error('Solver returned an empty token.'); + // Token injection and submission are site-specific; adapt this step to the target page. + // Inspect the target page's fields, enterprise payload, submission flow, and acceptance signals before adapting it. + return page.evaluate((token) => { + const response = document.querySelector('[name="g-recaptcha-response"]'); + if (!response) throw new Error('Enterprise response field not found.'); + response.value = token; + response.dispatchEvent(new Event('change', { bubbles: true })); + }, solution.gRecaptchaResponse); + }) + .then(() => page.click(submitSelector)) + .then(() => { + // STEP-05: Require a visible, page-specific success message. + return page + .waitForSelector(successSelector, { visible: true }) + .then(() => page.$eval(successSelector, (element) => element.textContent.trim())); + }); +} + +/** Launch Chromium and run the complete Enterprise example. */ +export function main() { + const solver = new CaptchaClient({ clientKey: process.env.CAPTCHA_API_KEY || 'YOUR_API_KEY' }); + let browser; + return puppeteer + .launch({ + headless: process.env.HEADLESS === 'true', + }) + .then((instance) => { + browser = instance; + return browser.newPage(); + }) + .then((page) => solveCaptcha(page, solver)) + .then((message) => console.log('Page confirmation:', message)) + .finally(() => browser?.close()); +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + // STEP-06: Report failures and always close Chromium in main(). + main().catch((error) => { + console.error(error); + process.exitCode = 1; + }); +} diff --git a/examples/reCAPTCHA/recaptcha_v2_proxy.js b/examples/reCAPTCHA/recaptcha_v2_proxy.js index b766f53..2fb16c6 100644 --- a/examples/reCAPTCHA/recaptcha_v2_proxy.js +++ b/examples/reCAPTCHA/recaptcha_v2_proxy.js @@ -1,97 +1,143 @@ -/** - * Solve reCAPTCHA v2 through the same HTTP proxy in Chrome and Captcha Solver. - * Every important step is kept in this file so it can be copied and adapted. - */ import { pathToFileURL } from 'node:url'; import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; import puppeteer from 'puppeteer-extra'; import StealthPlugin from 'puppeteer-extra-plugin-stealth'; +/** + * Solve Google reCAPTCHA v2 through the same proxy in Chromium and Captcha Solver. It uses + * Tasks.RecaptchaV2 and CaptchaClient.solve(), injects the token, submits the form, and checks + * page acceptance. + * Token injection and submission are site-specific. You must inspect the target page and + * determine the correct way to pass the token yourself. + * + * How it works: + * STEP-01 - Read proxy settings and configure the SDK client. + * STEP-02 - Launch Chromium through the proxy and open the target. + * STEP-03 - Extract the widget parameters. + * STEP-04 - Create and solve a proxy-based task. + * STEP-05 - Log and inject the solution. + * STEP-06 - Submit the form and verify acceptance. + * STEP-07 - Handle errors and close Chromium. + */ + puppeteer.use(StealthPlugin()); -const DEFAULT_URL = 'https://www.google.com/recaptcha/api2/demo'; -/** Read proxy settings from environment variables. */ +/** Solve a task with the SDK and log the task ID returned by createTask(). */ +function solveAndLogTaskId(solver, task) { + const loggingSolver = Object.create(solver); + loggingSolver.createTask = (...args) => + solver.createTask(...args).then((taskId) => { + console.log('Task ID:', taskId); + return taskId; + }); + return loggingSolver.solve(task); +} +const websiteURL = + process.env.RECAPTCHA_V2_TARGET_URL || 'https://www.google.com/recaptcha/api2/demo'; +const client = new CaptchaClient({ clientKey: process.env.CAPTCHA_API_KEY || 'YOUR_API_KEY' }); +let browser; + +/** Read and validate proxy settings from the environment. */ function getProxy() { - const proxyAddress = process.env.PROXY_ADDRESS; const proxyPort = Number(process.env.PROXY_PORT); - if (!proxyAddress || !Number.isInteger(proxyPort)) { - throw new Error('Set PROXY_ADDRESS and PROXY_PORT.'); + if (!process.env.PROXY_ADDRESS || !Number.isInteger(proxyPort)) { + throw new Error('Set PROXY_ADDRESS and PROXY_PORT for the proxy example.'); } return { proxyType: process.env.PROXY_TYPE || 'http', - proxyAddress, + proxyAddress: process.env.PROXY_ADDRESS, proxyPort, proxyLogin: process.env.PROXY_LOGIN || undefined, proxyPassword: process.env.PROXY_PASSWORD || undefined, }; } -/** Solve and submit proxy-based reCAPTCHA v2 on an opened page. */ -export async function solveCaptcha(page, solver, proxy) { - console.log('1. Opening the page through the configured proxy'); - await page.goto(process.env.TARGET_URL || DEFAULT_URL, { waitUntil: 'domcontentloaded' }); - await page.waitForSelector('[data-sitekey]'); - - console.log('2. Reading reCAPTCHA parameters'); - const captcha = await page.$eval('[data-sitekey]', (element) => ({ - websiteKey: element.getAttribute('data-sitekey'), - isInvisible: element.getAttribute('data-size') === 'invisible', - recaptchaDataSValue: element.getAttribute('data-s') || undefined, - })); - const task = new Tasks.RecaptchaV2({ - websiteURL: page.url(), - ...captcha, - ...proxy, - userAgent: await page.evaluate(() => navigator.userAgent), - }); - - console.log('3. Sending RecaptchaV2 task'); - const solution = await solver.solve(task); - console.log('4. Solution received', solution); - if (!solution.gRecaptchaResponse) throw new Error('Captcha Solver returned an empty token.'); - - // Token injection and submission are site-specific; adapt this step to the target page. - console.log('5. Writing the token and submitting the form'); - await page.evaluate((token) => { - let response = document.querySelector('[name="g-recaptcha-response"]'); - if (!response) { - response = document.createElement('textarea'); - response.name = 'g-recaptcha-response'; - document.querySelector('form')?.append(response); - } - response.value = token; - response.dispatchEvent(new Event('change', { bubbles: true })); - }, solution.gRecaptchaResponse); - await page.click(process.env.SUBMIT_SELECTOR || 'button[type="submit"], input[type="submit"]'); - - console.log('6. Waiting for page acceptance'); - const selector = process.env.SUCCESS_SELECTOR || '.recaptcha-success, p[class*="successMessage"]'; - await page.waitForSelector(selector, { visible: true }); - return page.$eval(selector, (element) => element.textContent.trim()); +/** Solve and submit reCAPTCHA v2 through the configured proxy. */ +export function solveCaptcha(page, solver = client, proxy = getProxy()) { + // STEP-02: Open the target through Chromium's configured proxy. + return ( + page + .goto(process.env.RECAPTCHA_V2_TARGET_URL || websiteURL, { waitUntil: 'domcontentloaded' }) + .then(() => page.waitForSelector('[data-sitekey]')) + // STEP-03: Read widget parameters and the browser User-Agent. + .then(() => + Promise.all([ + page.$eval('[data-sitekey]', (element) => ({ + websiteKey: element.getAttribute('data-sitekey'), + isInvisible: element.getAttribute('data-size') === 'invisible', + recaptchaDataSValue: element.getAttribute('data-s') || undefined, + })), + page.evaluate(() => navigator.userAgent), + ]), + ) + // STEP-04: Send the same proxy identity with the SDK task. + .then(([captcha, userAgent]) => + solveAndLogTaskId( + solver, + new Tasks.RecaptchaV2({ + websiteURL: page.url(), + ...captcha, + ...proxy, + userAgent, + }), + ), + ) + .then((solution) => { + // STEP-05: Token injection and submission are site-specific. + console.log('Solution:', solution); + if (!solution.gRecaptchaResponse) + throw new Error('Captcha Solver returned an empty token.'); + return page.evaluate((token) => { + let response = document.querySelector('[name="g-recaptcha-response"]'); + if (!response) { + response = document.createElement('textarea'); + response.name = 'g-recaptcha-response'; + document.querySelector('form')?.append(response); + } + response.value = token; + response.dispatchEvent(new Event('change', { bubbles: true })); + }, solution.gRecaptchaResponse); + }) + // STEP-06: Submit and require a visible acceptance signal. + .then(() => page.click('button[type="submit"], input[type="submit"]')) + .then(() => + page.waitForSelector('.recaptcha-success, p[class*="successMessage"]', { visible: true }), + ) + .then(() => + page.$eval('.recaptcha-success, p[class*="successMessage"]', (element) => + element.textContent.trim(), + ), + ) + ); } /** Run the complete standalone proxy example. */ -export async function main() { - const apiKey = process.env.CAPTCHA_API_KEY; - if (!apiKey || apiKey === 'your_api_key') throw new Error('Set CAPTCHA_API_KEY.'); +export function main() { + // STEP-01: Validate proxy configuration before launching the browser. const proxy = getProxy(); - const solver = new CaptchaClient({ clientKey: apiKey }); - const browser = await puppeteer.launch({ - headless: process.env.HEADLESS === 'true', - executablePath: process.env.BROWSER_EXECUTABLE_PATH || undefined, - args: [`--proxy-server=${proxy.proxyType}://${proxy.proxyAddress}:${proxy.proxyPort}`], - }); - try { - const page = await browser.newPage(); - if (proxy.proxyLogin) { - await page.authenticate({ username: proxy.proxyLogin, password: proxy.proxyPassword }); - } - console.log('Captcha solved successfully:', await solveCaptcha(page, solver, proxy)); - } finally { - await browser.close(); - } + const endpoint = `${proxy.proxyType}://${proxy.proxyAddress}:${proxy.proxyPort}`; + return ( + puppeteer + .launch({ headless: process.env.HEADLESS === 'true', args: [`--proxy-server=${endpoint}`] }) + .then((instance) => { + browser = instance; + return browser.newPage(); + }) + .then((page) => { + const authentication = proxy.proxyLogin + ? page.authenticate({ username: proxy.proxyLogin, password: proxy.proxyPassword }) + : page.evaluate(() => true); + return authentication.then(() => solveCaptcha(page, client, proxy)); + }) + .then((message) => console.log(`Page confirmation: ${message}`)) + // STEP-07: Always close Chromium. + .finally(() => browser?.close()) + ); } if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { - main().catch((error) => { console.error('Example failed:', error.message); process.exitCode = 1; }); + main().catch((error) => { + console.error(error); + process.exitCode = 1; + }); } diff --git a/examples/reCAPTCHA/recaptcha_v3.js b/examples/reCAPTCHA/recaptcha_v3.js index f1caaff..0f99d59 100644 --- a/examples/reCAPTCHA/recaptcha_v3.js +++ b/examples/reCAPTCHA/recaptcha_v3.js @@ -1,74 +1,139 @@ -/** - * Solve reCAPTCHA v3 with a known page callback. - * The example reads the site key and action from page scripts, solves the task, - * invokes the callback, and verifies that the page accepted the token. - */ import { pathToFileURL } from 'node:url'; import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; import puppeteer from 'puppeteer-extra'; import StealthPlugin from 'puppeteer-extra-plugin-stealth'; +/** + * This example shows how to solve score-based Google reCAPTCHA v3 without using a proxy. It opens + * the page, extracts the site key and action, sends the task to the service, passes the returned + * token to the page callback, and checks the confirmation. It uses Tasks.RecaptchaV3Proxyless and + * CaptchaClient.solve(). + * + * To use this example on another page, change the target URL and verify how the site key, action, + * minimum score, callback, and acceptance signal are configured. Callback delivery alone does not + * prove server-side acceptance. + * Token injection and submission are site-specific. You must inspect the target page and + * determine the correct way to pass the token yourself. + * + * How it works: + * STEP-01 - Configure the target, task options, and SDK client. + * STEP-02 - Launch Chromium and open the target page. + * STEP-03 - Extract the reCAPTCHA site key and action from the page. + * STEP-04 - Create the task and wait for the solver result. + * STEP-05 - Log the solution and pass its token to the page callback. + * STEP-06 - Verify that the page accepts the token. + * STEP-07 - Handle errors and close Chromium. + */ + puppeteer.use(StealthPlugin()); -/** Solve reCAPTCHA v3 on an already opened page. */ -export async function solveCaptcha(page, solver) { - if (!process.env.TARGET_URL) throw new Error('Set TARGET_URL for this example.'); - console.log('1. Opening the reCAPTCHA v3 page'); - await page.goto(process.env.TARGET_URL, { waitUntil: 'domcontentloaded' }); +/** Solve a task with the SDK and log the task ID returned by createTask(). */ +function solveAndLogTaskId(solver, task) { + const loggingSolver = Object.create(solver); + loggingSolver.createTask = (...args) => + solver.createTask(...args).then((taskId) => { + console.log('Task ID:', taskId); + return taskId; + }); + return loggingSolver.solve(task); +} - console.log('2. Reading the site key and action from page scripts'); - const captcha = await page.waitForFunction((sitekey, action) => { - if (sitekey && action) return { websiteKey: sitekey, pageAction: action }; - const source = Array.from(document.scripts, (script) => script.textContent).join('\n'); - const match = source.match(/grecaptcha\.execute\s*\(\s*['"]([^'"]+)['"]\s*,\s*\{[^}]*action\s*:\s*['"]([^'"]+)['"]/); - return match ? { websiteKey: match[1], pageAction: match[2] } : false; - }, {}, process.env.RECAPTCHA_SITEKEY || '', process.env.RECAPTCHA_ACTION || ''); - const params = await captcha.jsonValue(); - await captcha.dispose(); +// STEP-01: Read the target and task options, then create the SDK client. +const websiteURL = + process.env.RECAPTCHA_V3_TARGET_URL || 'https://example.com/page_with_recaptcha_v3'; +const minimumScore = 0.3; +const callbackName = 'verifyRecaptcha'; +const successSelector = 'p[class*="successMessage"]'; +const client = new CaptchaClient({ + clientKey: process.env.CAPTCHA_API_KEY || 'YOUR_API_KEY', +}); - const task = new Tasks.RecaptchaV3Proxyless({ - websiteURL: page.url(), - websiteKey: params.websiteKey, - pageAction: params.pageAction, - minScore: Number(process.env.RECAPTCHA_MIN_SCORE || 0.3), - }); - console.log('3. Sending the task to Captcha Solver', task.toDict()); - const solution = await solver.solve(task); - console.log('4. Solution received', solution); - if (!solution.gRecaptchaResponse) throw new Error('Captcha Solver returned an empty token.'); +let browser; - // Token injection and submission are site-specific; adapt this step to the target page. - const callbackName = process.env.CALLBACK_NAME || 'verifyRecaptcha'; - console.log(`5. Passing the token to ${callbackName}`); - await page.evaluate((name, token) => { - const callback = name.split('.').reduce((value, key) => value?.[key], window); - if (typeof callback !== 'function') throw new Error(`Callback ${name} was not found.`); - callback(token); - }, callbackName, solution.gRecaptchaResponse); +/** + * Solve reCAPTCHA v3 on an opened Puppeteer page. + * @param {import('puppeteer').Page} page Open Puppeteer page. + * @param {CaptchaClient} solver Configured Captcha Solver client. + * @returns {Promise} Page text that confirms acceptance. + */ +export function solveCaptcha(page, solver = client) { + // STEP-02: Open the configured page containing reCAPTCHA v3. + return ( + page + .goto(process.env.RECAPTCHA_V3_TARGET_URL || websiteURL, { waitUntil: 'domcontentloaded' }) + // STEP-03: Extract the site key and action from grecaptcha.execute(); v3 has no widget. + .then(() => + page.waitForFunction(() => { + const source = Array.from(document.scripts, (script) => script.textContent).join('\n'); + const match = source.match( + /grecaptcha\.execute\s*\(\s*['"](?[^'"]+)['"]\s*,\s*\{[^}]*action\s*:\s*['"](?[^'"]+)['"]/, + ); + return match?.groups || false; + }), + ) + .then((handle) => + handle.jsonValue().finally(() => { + return handle.dispose(); + }), + ) + // STEP-04: Build the task and wait for the solver result. + .then(({ websiteKey, pageAction }) => { + const task = new Tasks.RecaptchaV3Proxyless({ + websiteURL: page.url(), + websiteKey, + pageAction, + minScore: minimumScore, + }); + return solveAndLogTaskId(solver, task); + }) + // STEP-05: Log the solution and pass its token to the configured callback. + .then((solution) => { + console.log('Solution:', solution); + if (!solution.gRecaptchaResponse) { + throw new Error('Captcha Solver returned an empty reCAPTCHA token.'); + } - console.log('6. Waiting for page acceptance'); - const selector = process.env.SUCCESS_SELECTOR || 'p[class*="successMessage"]'; - await page.waitForSelector(selector, { visible: true }); - return page.$eval(selector, (element) => element.textContent.trim()); + // Token injection and submission are site-specific; adapt this step to the target page. + // The configured callback submits the token through this page's verification flow. + return page.evaluate( + (name, token) => { + const callback = name.split('.').reduce((value, key) => value?.[key], window); + if (typeof callback !== 'function') throw new Error(`Callback ${name} was not found.`); + callback(token); + }, + callbackName, + solution.gRecaptchaResponse, + ); + }) + // STEP-06: Require a visible, page-specific success message. + .then(() => page.waitForSelector(successSelector, { visible: true })) + .then(() => page.$eval(successSelector, (element) => element.textContent.trim())) + ); } /** Run the complete standalone reCAPTCHA v3 example. */ -export async function main() { - const apiKey = process.env.CAPTCHA_API_KEY; - if (!apiKey || apiKey === 'your_api_key') throw new Error('Set CAPTCHA_API_KEY.'); - const solver = new CaptchaClient({ clientKey: apiKey }); - const browser = await puppeteer.launch({ - headless: process.env.HEADLESS === 'true', - executablePath: process.env.BROWSER_EXECUTABLE_PATH || undefined, - }); - try { - const page = await browser.newPage(); - console.log('Captcha solved successfully:', await solveCaptcha(page, solver)); - } finally { - await browser.close(); - } +export function main() { + // Launch Chromium and create a browser page. + return ( + puppeteer + .launch({ + headless: process.env.HEADLESS === 'true', + }) + .then((instance) => { + browser = instance; + return browser.newPage(); + }) + .then((page) => solveCaptcha(page)) + .then((message) => console.log(`Page confirmation: ${message}`)) + // STEP-07: Always close Chromium and let callers handle failures. + .finally(() => browser?.close()) + ); } if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { - main().catch((error) => { console.error('Example failed:', error.message); process.exitCode = 1; }); + // Report errors and set a nonzero exit code when this file runs directly. + main().catch((error) => { + console.error(error); + process.exitCode = 1; + }); } diff --git a/examples/reCAPTCHA/recaptcha_v3_extended_js_script.js b/examples/reCAPTCHA/recaptcha_v3_extended_js_script.js deleted file mode 100644 index 5d5f04d..0000000 --- a/examples/reCAPTCHA/recaptcha_v3_extended_js_script.js +++ /dev/null @@ -1,89 +0,0 @@ -/** - * Solve reCAPTCHA v3 when execute() is called from an external script. - * An interceptor records the site key and action before navigation, then this - * example solves the task and resolves the intercepted execute() promise. - */ -import { pathToFileURL } from 'node:url'; -import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; -import puppeteer from 'puppeteer-extra'; -import StealthPlugin from 'puppeteer-extra-plugin-stealth'; - -puppeteer.use(StealthPlugin()); - -/** Install a small execute() interceptor before page scripts run. */ -async function installInterceptor(page) { - await page.evaluateOnNewDocument(() => { - const patch = (api) => { - if (!api || api.__captchaPatched) return api; - Object.defineProperty(api, '__captchaPatched', { value: true }); - Object.defineProperty(api, 'execute', { - configurable: true, - get: () => (websiteKey, options = {}) => { - window.__recaptchaV3 = { websiteKey, pageAction: options.action }; - return new Promise((resolve) => { window.__resolveRecaptchaV3 = resolve; }); - }, - }); - return api; - }; - let api = patch(window.grecaptcha); - Object.defineProperty(window, 'grecaptcha', { - configurable: true, - get: () => api, - set: (value) => { api = patch(value); }, - }); - }); -} - -/** Solve intercepted reCAPTCHA v3 on an already opened page. */ -export async function solveCaptcha(page, solver) { - if (!process.env.TARGET_URL) throw new Error('Set TARGET_URL for this example.'); - console.log('1. Installing the execute() interceptor'); - await installInterceptor(page); - console.log('2. Opening the reCAPTCHA v3 page'); - await page.goto(process.env.TARGET_URL, { waitUntil: 'domcontentloaded' }); - - if (!await page.evaluate(() => Boolean(window.__recaptchaV3))) { - await page.click(process.env.SUBMIT_SELECTOR || 'button[type="submit"], input[type="submit"]'); - } - const handle = await page.waitForFunction(() => window.__recaptchaV3 || false); - const params = await handle.jsonValue(); - await handle.dispose(); - console.log('3. Captured reCAPTCHA parameters', params); - - const task = new Tasks.RecaptchaV3Proxyless({ - websiteURL: page.url(), ...params, - minScore: Number(process.env.RECAPTCHA_MIN_SCORE || 0.3), - }); - console.log('4. Sending the task to Captcha Solver'); - const solution = await solver.solve(task); - console.log('5. Solution received', solution); - if (!solution.gRecaptchaResponse) throw new Error('Captcha Solver returned an empty token.'); - - // Token injection and submission are site-specific; adapt this step to the target page. - console.log('6. Resolving the intercepted execute() promise'); - await page.evaluate((token) => window.__resolveRecaptchaV3(token), solution.gRecaptchaResponse); - const selector = process.env.SUCCESS_SELECTOR || 'p[class*="successMessage"]'; - await page.waitForSelector(selector, { visible: true }); - return page.$eval(selector, (element) => element.textContent.trim()); -} - -/** Run the complete standalone intercepted reCAPTCHA v3 example. */ -export async function main() { - const apiKey = process.env.CAPTCHA_API_KEY; - if (!apiKey || apiKey === 'your_api_key') throw new Error('Set CAPTCHA_API_KEY.'); - const solver = new CaptchaClient({ clientKey: apiKey }); - const browser = await puppeteer.launch({ - headless: process.env.HEADLESS === 'true', - executablePath: process.env.BROWSER_EXECUTABLE_PATH || undefined, - }); - try { - const page = await browser.newPage(); - console.log('Captcha solved successfully:', await solveCaptcha(page, solver)); - } finally { - await browser.close(); - } -} - -if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { - main().catch((error) => { console.error('Example failed:', error.message); process.exitCode = 1; }); -} diff --git a/examples/tencent/tencent.js b/examples/tencent/tencent.js index c610dc0..171718d 100644 --- a/examples/tencent/tencent.js +++ b/examples/tencent/tencent.js @@ -1,32 +1,77 @@ -/** - * Solve Tencent CAPTCHA with Puppeteer and Captcha Solver. - * The TencentCaptcha constructor is intercepted so the task parameters and - * original callback can be used without hardcoded values. - */ import { pathToFileURL } from 'node:url'; import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; import puppeteer from 'puppeteer-extra'; import StealthPlugin from 'puppeteer-extra-plugin-stealth'; +/** + * This example shows how to solve Tencent CAPTCHA without using a proxy. It intercepts the + * TencentCaptcha constructor, captures the app ID, script URL, and callback, sends the task to the + * service, passes the returned solution to the original callback, and confirms callback delivery. + * It uses Tasks.TencentTaskProxyless and CaptchaClient.solve(). + * + * To use this example on another page, change the target URL and optional script URL, then verify + * its constructor signature and callback. Callback delivery is site-specific and does not prove + * server-side acceptance, so add a separate page-specific acceptance check when one is available. + * + * How it works: + * STEP-01 - Configure the target and create the SDK client. + * STEP-02 - Launch Chromium and install the constructor interceptor. + * STEP-03 - Open the target and wait for the CAPTCHA widget. + * STEP-04 - Capture the Tencent task parameters. + * STEP-05 - Create the task and wait for the solver result. + * STEP-06 - Log the solution and pass it to the original callback. + * STEP-07 - Confirm that the callback receives the solution. + * STEP-08 - Handle errors and close Chromium. + */ + puppeteer.use(StealthPlugin()); +/** Solve a task with the SDK and log the task ID returned by createTask(). */ +function solveAndLogTaskId(solver, task) { + const loggingSolver = Object.create(solver); + loggingSolver.createTask = (...args) => + solver.createTask(...args).then((taskId) => { + console.log('Task ID:', taskId); + return taskId; + }); + return loggingSolver.solve(task); +} + +// STEP-01: Read the target settings and create the SDK client. +const websiteURL = + process.env.TENCENT_TARGET_URL || 'https://example.com/page_with_tencent_captcha'; +const client = new CaptchaClient({ + clientKey: process.env.CAPTCHA_API_KEY || 'YOUR_API_KEY', +}); + +let browser; + /** Install the TencentCaptcha constructor interceptor before navigation. */ -async function installInterceptor(page) { - await page.evaluateOnNewDocument(() => { +function installInterceptor(page) { + return page.evaluateOnNewDocument(() => { const records = new Map(); let originalConstructor; - let nextId = 0; + let nextRecordId = 0; Object.defineProperty(window, '__captchaSolverTencent', { value: { - pending: () => [...records.values()] - .filter((record) => !record.submitted) - .map((record) => record.params), - submit(id, solution) { - const record = records.get(id); + pending: () => + [...records.values()] + .filter((record) => !record.submitted) + .map((record) => record.params), + submit(recordId, solution) { + const record = records.get(recordId); if (!record || record.submitted) throw new Error('Tencent callback was not found.'); record.submitted = true; record.callback(solution); + record.receivedSolution = solution; + }, + received(recordId, solution) { + const receivedSolution = records.get(recordId)?.receivedSolution; + return ( + receivedSolution?.ticket === solution.ticket && + receivedSolution?.randstr === solution.randstr + ); }, }, }); @@ -36,24 +81,34 @@ async function installInterceptor(page) { get: () => originalConstructor, set: (Constructor) => { originalConstructor = new Proxy(Constructor, { - construct(Target, args, newTarget) { - const offset = typeof args[1] === 'function' ? 0 : 1; - const appId = args[offset]; - const callback = args[offset + 1]; - const id = `tencent-${++nextId}`; + construct(Target, constructorArguments, newTarget) { + const [firstArgument, secondArgument, thirdArgument] = constructorArguments; + const hasContainerArgument = typeof secondArgument !== 'function'; + const appId = hasContainerArgument ? secondArgument : firstArgument; + const callback = hasContainerArgument ? thirdArgument : secondArgument; + const callbackArgumentIndex = hasContainerArgument ? 2 : 1; + const recordId = `tencent-${++nextRecordId}`; const params = { - id, + recordId, websiteURL: location.href, appId: String(appId), - captchaScript: document.currentScript?.src || [...document.scripts] - .map((script) => script.src) - .find((src) => /\/TCaptcha-global\.js(?:\?|$)/i.test(src)), + captchaScript: + document.currentScript?.src || + [...document.scripts] + .map((script) => script.src) + .find((source) => /\/TCaptcha-global\.js(?:\?|$)/i.test(source)), }; - const nativeArgs = [...args]; - nativeArgs[offset + 1] = () => {}; - const instance = Reflect.construct(Target, nativeArgs, newTarget); + + const nativeArguments = [...constructorArguments]; + nativeArguments[callbackArgumentIndex] = () => {}; + const instance = Reflect.construct(Target, nativeArguments, newTarget); instance.show = () => {}; - records.set(id, { params, callback, submitted: false }); + records.set(recordId, { + params, + callback, + submitted: false, + receivedSolution: null, + }); return instance; }, }); @@ -62,56 +117,94 @@ async function installInterceptor(page) { }); } -/** Solve Tencent CAPTCHA on an already opened page. */ -export async function solveCaptcha(page, solver) { - if (!process.env.TARGET_URL) throw new Error('Set TARGET_URL for this example.'); - if (!process.env.TENCENT_SUCCESS_SELECTOR) throw new Error('Set TENCENT_SUCCESS_SELECTOR.'); - console.log('1. Installing the TencentCaptcha interceptor'); - await installInterceptor(page); - console.log('2. Opening the Tencent CAPTCHA page'); - await page.goto(process.env.TARGET_URL, { waitUntil: 'domcontentloaded' }); - - if (process.env.TENCENT_TRIGGER_SELECTOR) { - console.log('3. Opening the CAPTCHA widget'); - await page.click(process.env.TENCENT_TRIGGER_SELECTOR); - } - const handle = await page.waitForFunction(() => window.__captchaSolverTencent.pending()[0] || false); - const captured = await handle.jsonValue(); - await handle.dispose(); - const { id, ...taskParameters } = captured; - console.log('4. Captured Tencent parameters', taskParameters); +/** + * Solve Tencent CAPTCHA on an opened Puppeteer page. + * @param {import('puppeteer').Page} page Open Puppeteer page. + * @param {CaptchaClient} solver Configured Captcha Solver client. + * @returns {Promise} Message confirming delivery to the page callback. + */ +export function solveCaptcha(page, solver = client) { + // STEP-02: Install the interceptor before the target defines TencentCaptcha. + return ( + installInterceptor(page) + // STEP-03: Open the target; this flow expects the page to create its CAPTCHA widget. + .then(() => + page.goto(process.env.TENCENT_TARGET_URL || websiteURL, { waitUntil: 'domcontentloaded' }), + ) + // STEP-04: Wait for the constructor parameters captured from a fresh widget instance. + .then(() => + page.waitForFunction(() => window.__captchaSolverTencent.pending().at(0) || false), + ) + .then((handle) => + handle.jsonValue().finally(() => { + return handle.dispose(); + }), + ) + // STEP-05: Build the task and wait for the solver result. + .then(({ recordId, ...taskParameters }) => { + if (process.env.TENCENT_SCRIPT_URL) { + taskParameters.captchaScript = process.env.TENCENT_SCRIPT_URL; + } + if (!taskParameters.appId) throw new Error('Tencent app ID was not captured.'); + if (!taskParameters.captchaScript) throw new Error('Tencent script URL was not captured.'); - const task = new Tasks.TencentTaskProxyless(taskParameters); - console.log('5. Sending the task to Captcha Solver'); - const solution = await solver.solve(task); - console.log('6. Solution received', solution); + return solveAndLogTaskId(solver, new Tasks.TencentTaskProxyless(taskParameters)).then( + (solution) => ({ recordId, solution }), + ); + }) + // STEP-06: Log the solution and pass it to the exact callback registered by the page. + .then(({ recordId, solution }) => { + console.log('Solution:', solution); - // Token injection and submission are site-specific; adapt this step to the target page. - console.log('7. Passing the solution to the original Tencent callback'); - await page.evaluate((recordId, answer) => { - window.__captchaSolverTencent.submit(recordId, answer); - }, id, solution); - await page.waitForSelector(process.env.TENCENT_SUCCESS_SELECTOR, { visible: true }); - return page.$eval(process.env.TENCENT_SUCCESS_SELECTOR, (element) => element.textContent.trim()); + // Solution submission is site-specific; adapt this step to the target page. + // Pass every returned Tencent field through the original page callback. + return page + .evaluate( + (capturedRecordId, answer) => { + window.__captchaSolverTencent.submit(capturedRecordId, answer); + }, + recordId, + solution, + ) + .then(() => ({ recordId, solution })); + }) + // STEP-07: Confirm delivery of the same ticket and random string to the page callback. + .then(({ recordId, solution }) => + page.waitForFunction( + (capturedRecordId, answer) => + window.__captchaSolverTencent.received(capturedRecordId, answer), + {}, + recordId, + solution, + ), + ) + .then(() => 'Tencent callback received the solution.') + ); } /** Run the complete standalone Tencent CAPTCHA example. */ -export async function main() { - const apiKey = process.env.CAPTCHA_API_KEY; - if (!apiKey || apiKey === 'your_api_key') throw new Error('Set CAPTCHA_API_KEY.'); - const solver = new CaptchaClient({ clientKey: apiKey }); - const browser = await puppeteer.launch({ - headless: process.env.HEADLESS === 'true', - executablePath: process.env.BROWSER_EXECUTABLE_PATH || undefined, - }); - try { - const page = await browser.newPage(); - console.log('Captcha solved successfully:', await solveCaptcha(page, solver)); - } finally { - await browser.close(); - } +export function main() { + // Launch Chromium and create a browser page. + return ( + puppeteer + .launch({ + headless: process.env.HEADLESS === 'true', + }) + .then((instance) => { + browser = instance; + return browser.newPage(); + }) + .then((page) => solveCaptcha(page)) + .then((message) => console.log(`Page confirmation: ${message}`)) + // STEP-08: Always close Chromium and let callers handle failures. + .finally(() => browser?.close()) + ); } if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { - main().catch((error) => { console.error('Example failed:', error.message); process.exitCode = 1; }); + // Report errors and set a nonzero exit code when this file runs directly. + main().catch((error) => { + console.error(error); + process.exitCode = 1; + }); } diff --git a/examples/yandex/yandex_smartcaptcha.js b/examples/yandex/yandex_smartcaptcha.js index cc0a355..81e10ad 100644 --- a/examples/yandex/yandex_smartcaptcha.js +++ b/examples/yandex/yandex_smartcaptcha.js @@ -1,92 +1,142 @@ -/** - * Solve Yandex SmartCaptcha with Puppeteer and Captcha Solver. - * - * This example opens the official demo, reads the public widget key, sends a - * task through the official SDK, writes the returned token into the hidden - * form field, submits the form, and confirms that the page accepted it. - */ import { pathToFileURL } from 'node:url'; import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; import puppeteer from 'puppeteer-extra'; import StealthPlugin from 'puppeteer-extra-plugin-stealth'; -import { demos } from '../../config/demos.js'; + +/** + * This example shows how to solve Yandex SmartCaptcha without a proxy. It opens the official + * demo, extracts the public site key and browser User-Agent, creates a + * Tasks.YandexSmartCaptchaTaskProxyless task, and uses CaptchaClient.solve(). It logs the returned + * token, writes it to the demo form, submits the form, and requires the demo's success text as + * proof that the page accepted the solution. + * + * To use this example on another page, change the target URL and verify the site key. Token fields, + * callbacks, submission, and success indicators are site-specific. You must inspect the target + * page and determine the correct way to pass the token yourself. + * + * How it works: + * STEP-01 - Configure the target and create the SDK client. + * STEP-02 - Launch Chromium and open the target page. + * STEP-03 - Extract the SmartCaptcha parameters from the page. + * STEP-04 - Create the task and wait for the solver result. + * STEP-05 - Log and apply the returned token. + * STEP-06 - Submit the form and verify that the page accepts the token. + * STEP-07 - Handle errors and close Chromium. + */ puppeteer.use(StealthPlugin()); -const SITEKEY_SELECTOR = '.smart-captcha[data-sitekey]'; -const TOKEN_SELECTOR = 'input[name="smart-token"]'; -const SUBMIT_SELECTOR = '#smartcaptcha-demo-submit'; -const SUCCESS_TEXT = 'Hello, user!'; +/** Solve a task with the SDK and log the task ID returned by createTask(). */ +function solveAndLogTaskId(solver, task) { + const loggingSolver = Object.create(solver); + loggingSolver.createTask = (...args) => + solver.createTask(...args).then((taskId) => { + console.log('Task ID:', taskId); + return taskId; + }); + return loggingSolver.solve(task); +} + +const websiteURL = process.env.YANDEX_TARGET_URL || 'https://captcha-api.yandex.ru/demo'; +const siteKeySelector = '.smart-captcha[data-sitekey]'; +const tokenSelector = 'input[name="smart-token"]'; +const submitSelector = '#smartcaptcha-demo-submit'; +const expectedSuccessText = 'Hello, user!'; +const client = new CaptchaClient({ + clientKey: process.env.CAPTCHA_API_KEY || 'YOUR_API_KEY', +}); +let browser; /** - * Solve and submit Yandex SmartCaptcha on an already opened page. + * Solve and submit Yandex SmartCaptcha on an opened Puppeteer page. * @param {import('puppeteer').Page} page Open Puppeteer page. * @param {CaptchaClient} solver Configured Captcha Solver client. - * @returns {Promise} Text displayed after successful submission. + * @returns {Promise} Page text that confirms acceptance. */ -export async function solveCaptcha(page, solver) { - console.log('1. Opening the Yandex SmartCaptcha page'); - await page.goto(process.env.TARGET_URL || demos.yandexSmartCaptcha, { waitUntil: 'domcontentloaded' }); - await page.waitForSelector(SITEKEY_SELECTOR); - - console.log('2. Reading the SmartCaptcha site key'); - const websiteKey = await page.$eval(SITEKEY_SELECTOR, (element) => element.getAttribute('data-sitekey')); - if (!websiteKey) throw new Error('No Yandex SmartCaptcha sitekey found.'); - - const task = new Tasks.YandexSmartCaptchaTaskProxyless({ - websiteURL: page.url(), - websiteKey, - userAgent: await page.evaluate(() => navigator.userAgent), - }); - console.log('3. Sending the task to Captcha Solver', task.toDict()); - const solution = await solver.solve(task); - console.log('4. Solution received', solution); - if (typeof solution.token !== 'string' || !solution.token.trim()) { - throw new Error('Captcha Solver returned an empty SmartCaptcha token.'); - } +export function solveCaptcha(page, solver = client) { + let solution; - // Token injection and submission are site-specific; adapt this step to the target page. - console.log('5. Writing the token into smart-token'); - await page.waitForSelector(TOKEN_SELECTOR); - await page.$eval(TOKEN_SELECTOR, (input, token) => { - input.value = token; - input.dispatchEvent(new Event('input', { bubbles: true })); - input.dispatchEvent(new Event('change', { bubbles: true })); - }, solution.token); - - console.log('6. Submitting the form'); - await page.click(process.env.SUBMIT_SELECTOR || SUBMIT_SELECTOR); - - console.log('7. Waiting for the page to accept the solution'); - if (process.env.SUCCESS_SELECTOR) { - await page.waitForSelector(process.env.SUCCESS_SELECTOR, { visible: true }); - return page.$eval(process.env.SUCCESS_SELECTOR, (element) => element.textContent.trim()); - } - const successText = process.env.YANDEX_SUCCESS_TEXT || SUCCESS_TEXT; - await page.waitForFunction((text) => document.body.innerText.includes(text), {}, successText); - return successText; + // Open the configured target page after main() launches Chromium. + return ( + page + .goto(process.env.YANDEX_TARGET_URL || websiteURL, { + waitUntil: 'domcontentloaded', + }) + .then(() => page.waitForSelector(siteKeySelector)) + // STEP-03: Extract the SmartCaptcha parameters from the page. + .then(() => + Promise.all([ + page.$eval(siteKeySelector, (element) => element.getAttribute('data-sitekey')), + page.evaluate(() => navigator.userAgent), + ]), + ) + // STEP-04: Create the task and wait for the solver result. + .then(([websiteKey, userAgent]) => { + const task = new Tasks.YandexSmartCaptchaTaskProxyless({ + websiteURL: page.url(), + websiteKey, + userAgent, + }); + return solveAndLogTaskId(solver, task); + }) + // STEP-05: Log and apply the returned token. + .then((result) => { + solution = result; + console.log('Solution:', solution); + // Token injection and submission are site-specific; adapt this step to the target page. + // Inspect the target page's fields, submission flow, and acceptance signals before adapting it. + return page.$eval( + tokenSelector, + (input, token) => { + input.value = token; + input.dispatchEvent(new Event('input', { bubbles: true })); + input.dispatchEvent(new Event('change', { bubbles: true })); + }, + solution.token, + ); + }) + // STEP-06: Submit the form and verify that the page accepts the token. + .then(() => page.click(submitSelector)) + .then(() => + page + .waitForFunction( + (text) => document.body.innerText.includes(text), + {}, + expectedSuccessText, + ) + .then(() => expectedSuccessText), + ) + .then((message) => { + console.log(`Page confirmation: ${message}`); + return message; + }) + ); } /** Run the complete standalone Yandex SmartCaptcha example. */ -export async function main() { - const apiKey = process.env.CAPTCHA_API_KEY; - if (!apiKey || apiKey === 'your_api_key') throw new Error('Set CAPTCHA_API_KEY.'); - const solver = new CaptchaClient({ clientKey: apiKey }); - const browser = await puppeteer.launch({ - headless: process.env.HEADLESS === 'true', - executablePath: process.env.BROWSER_EXECUTABLE_PATH || undefined, - defaultViewport: { width: 1280, height: 900 }, - }); - try { - const page = await browser.newPage(); - const result = await solveCaptcha(page, solver); - console.log('Captcha solved successfully:', result); - return result; - } finally { - await browser.close(); - } +export function main() { + // STEP-01: Configure the target and create the SDK client. + // STEP-02: Launch Chromium and open the target page. + return ( + puppeteer + .launch({ + headless: process.env.HEADLESS === 'true', + defaultViewport: { width: 1280, height: 900 }, + }) + .then((launchedBrowser) => { + browser = launchedBrowser; + return browser.newPage(); + }) + .then((page) => solveCaptcha(page)) + // STEP-07: Always close Chromium and let callers handle failures. + .finally(() => browser?.close()) + ); } if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { - main().catch((error) => { console.error('Example failed:', error.message); process.exitCode = 1; }); + // Report errors and set a nonzero exit code when this file runs directly. + main().catch((error) => { + console.error(error); + process.exitCode = 1; + }); } diff --git a/examples/yandex/yandex_smartcaptcha_image.js b/examples/yandex/yandex_smartcaptcha_image.js new file mode 100644 index 0000000..1782326 --- /dev/null +++ b/examples/yandex/yandex_smartcaptcha_image.js @@ -0,0 +1,70 @@ +import { readFile } from 'node:fs/promises'; +import { pathToFileURL } from 'node:url'; +import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; + +/** + * This example solves the image-selection stage of Yandex SmartCaptcha. It reads the challenge + * and instruction images, creates Tasks.YandexSmartCaptchaImageTask, sends it through + * CaptchaClient.solve(), and prints the returned click coordinates. + * + * To adapt this example, replace both sample images with images from the same challenge. Applying + * returned coordinates is site-specific: inspect the target widget, its scaling, and click flow. + * + * How it works: + * STEP-01 - Create the SDK client. + * STEP-02 - Read the challenge and instruction images. + * STEP-03 - Create and send the Yandex SmartCaptcha image task. + * STEP-04 - Print the returned coordinates or report an error. + */ + +/** Solve a task with the SDK and log the task ID returned by createTask(). */ +function solveAndLogTaskId(solver, task) { + const loggingSolver = Object.create(solver); + loggingSolver.createTask = (...args) => + solver.createTask(...args).then((taskId) => { + console.log('Task ID:', taskId); + return taskId; + }); + return loggingSolver.solve(task); +} + +/** + * Read both sample images, solve the Yandex image task, and print its result. + * @param {CaptchaClient} [solver] Configured client, primarily for local testing. + * @returns {Promise} Solution. + */ +export function main(solver) { + // STEP-01: Create the SDK client with the API key from CAPTCHA_API_KEY. + const client = + solver || + new CaptchaClient({ + clientKey: process.env.CAPTCHA_API_KEY || 'YOUR_API_KEY', + }); + + // STEP-02: Read both images without printing their base64 contents. + return Promise.all([ + readFile(new URL('../../assets/yandex-smartcaptcha-main.png', import.meta.url)), + readFile(new URL('../../assets/yandex-smartcaptcha-task.png', import.meta.url)), + ]) + .then(([body, instructions]) => { + // STEP-03: Create and send the dedicated Yandex SmartCaptcha image task. + const task = new Tasks.YandexSmartCaptchaImageTask({ + image: body.toString('base64'), + imgInstructions: instructions.toString('base64'), + comment: 'Select objects in the order shown in the instruction image', + }); + return solveAndLogTaskId(client, task); + }) + .then((solution) => { + // STEP-04: Print coordinates; applying them in a widget is unique to each target site. + console.log(solution.coordinates); + return solution; + }); +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + main().catch((error) => { + console.error(error); + process.exitCode = 1; + }); +} diff --git a/index.js b/index.js new file mode 100644 index 0000000..6299c89 --- /dev/null +++ b/index.js @@ -0,0 +1,3 @@ +import { main } from './examples/cloudflare/turnstile_challenge.js'; + +main(); diff --git a/package-lock.json b/package-lock.json index faebc48..eb60f4e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,15 +1,15 @@ { "name": "captcha-solver-puppeteer-javascript-examples", - "version": "0.1.0", + "version": "1.0.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "captcha-solver-puppeteer-javascript-examples", - "version": "0.1.0", + "version": "1.0.0", "license": "MIT", "dependencies": { - "@captcha-solver-api/javascript-sdk": "^1.0.1", + "@captcha-solver-api/javascript-sdk": "^1.1.0", "puppeteer": "^25.13.0", "puppeteer-extra": "^3.3.6", "puppeteer-extra-plugin-stealth": "^2.11.2" @@ -17,16 +17,17 @@ "devDependencies": { "@eslint/js": "^9.39.5", "eslint": "^9.39.5", - "eslint-plugin-jsdoc": "^61.4.1" + "eslint-plugin-jsdoc": "^61.4.1", + "prettier": "^3.6.2" }, "engines": { "node": ">=22.12.0" } }, "node_modules/@captcha-solver-api/javascript-sdk": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/@captcha-solver-api/javascript-sdk/-/javascript-sdk-1.0.1.tgz", - "integrity": "sha512-CPXmV0GuL5Ty8F63/v9rtH1r4jM3versg4lCzhxAIwoIdwWqAhUPY8meQPosrRTCYj0n+QPJb/tgoQmqf2PKcg==", + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@captcha-solver-api/javascript-sdk/-/javascript-sdk-1.1.0.tgz", + "integrity": "sha512-Xc6jK1ek97i9amHkvbWG60gALdXIAulDLNtMfuHA3yw1LIh+dgEd6Gpi+ZmEnCLJK/hfo+suAUdgcjJ4XRM+oQ==", "license": "MIT", "engines": { "node": ">=18" @@ -300,6 +301,12 @@ "url": "https://github.com/sponsors/nzakas" } }, + "node_modules/@isaacs/nonrecursive-glob-match": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@isaacs/nonrecursive-glob-match/-/nonrecursive-glob-match-1.1.0.tgz", + "integrity": "sha512-GPm/Dbvk5RLmhRnxXIa7nTpK0xtl4E0wj0MslsuNiJ1FIROU+2+9lgUC/dgF7Ey4QCWhfEsgxilMRMCdHPfDfw==", + "license": "BlueOak-1.0.0" + }, "node_modules/@puppeteer/browsers": { "version": "3.2.4", "resolved": "https://registry.npmjs.org/@puppeteer/browsers/-/browsers-3.2.4.tgz", @@ -475,19 +482,24 @@ } }, "node_modules/balanced-match": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", - "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", - "license": "MIT" + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", + "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", + "license": "MIT", + "engines": { + "node": "18 || 20 || >=22" + } }, "node_modules/brace-expansion": { - "version": "1.1.21", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.21.tgz", - "integrity": "sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw==", + "version": "5.0.13", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.13.tgz", + "integrity": "sha512-Vh3dmFbc4wZeox7M9I/0L9GfFd83Su4+yCck/OF9Gi/P/dAHn0RT7X4K9R7gMNMhDck3DvhR6QXsnQdjjgwNvQ==", "license": "MIT", "dependencies": { - "balanced-match": "^1.0.0", - "concat-map": "0.0.1" + "balanced-match": "^4.0.2" + }, + "engines": { + "node": "20 || >=22" } }, "node_modules/callsites": { @@ -635,12 +647,6 @@ "node": ">= 12.0.0" } }, - "node_modules/concat-map": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", - "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", - "license": "MIT" - }, "node_modules/cross-spawn": { "version": "7.0.6", "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", @@ -1433,15 +1439,19 @@ } }, "node_modules/minimatch": { - "version": "3.1.5", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", - "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", - "license": "ISC", + "version": "11.0.8", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.8.tgz", + "integrity": "sha512-nFQuYSTVrGvysVBps5Ih+0BdnYFN/Cj3C816r6+p7yK+FHrVLGE4O4N9AFwykrlNlvM2HYt+Rad1Uiro6h88Ig==", + "license": "BlueOak-1.0.0", "dependencies": { - "brace-expansion": "^1.1.7" + "@isaacs/nonrecursive-glob-match": "^1.1.0", + "brace-expansion": "^5.0.12" }, "engines": { - "node": "*" + "node": "20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" } }, "node_modules/mitt": { @@ -1629,6 +1639,22 @@ "node": ">= 0.8.0" } }, + "node_modules/prettier": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.6.2.tgz", + "integrity": "sha512-I7AIg5boAr5R0FFtJ6rCfD+LFsWHp81dolrFD8S79U9tb8Az2nGrJncnMSnys+bpQJfRUzqs9hnA81OAA3hCuQ==", + "dev": true, + "license": "MIT", + "bin": { + "prettier": "bin/prettier.cjs" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/prettier/prettier?sponsor=1" + } + }, "node_modules/punycode": { "version": "2.3.1", "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", diff --git a/package.json b/package.json index d6a995f..26f201f 100644 --- a/package.json +++ b/package.json @@ -1,36 +1,55 @@ { "name": "captcha-solver-puppeteer-javascript-examples", - "version": "0.1.0", + "version": "1.0.0", "private": true, "type": "module", "description": "Captcha Solver browser automation examples using JavaScript and Puppeteer", + "keywords": [ + "captcha", + "captcha-solver", + "puppeteer", + "browser-automation", + "recaptcha", + "turnstile", + "geetest", + "yandex-smartcaptcha", + "tencent-captcha", + "image-to-text", + "javascript", + "examples" + ], "license": "MIT", "engines": { "node": ">=22.12.0" }, "scripts": { - "example:recaptcha-v2": "node --env-file-if-exists=.env examples/reCAPTCHA/recaptcha_v2.js", - "example:recaptcha-v2-proxy": "node --env-file-if-exists=.env examples/reCAPTCHA/recaptcha_v2_proxy.js", - "example:callback": "node --env-file-if-exists=.env examples/reCAPTCHA/recaptcha_v2_callback_variant1.js", - "example:callback-auto": "node --env-file-if-exists=.env examples/reCAPTCHA/recaptcha_v2_callback_variant2.js", - "example:callback-proxy": "node --env-file-if-exists=.env examples/reCAPTCHA/recaptcha_v2_callback_proxy.js", - "example:recaptcha-v3": "node --env-file-if-exists=.env examples/reCAPTCHA/recaptcha_v3.js", - "example:recaptcha-v3-extended": "node --env-file-if-exists=.env examples/reCAPTCHA/recaptcha_v3_extended_js_script.js", - "example:turnstile": "node --env-file-if-exists=.env examples/cloudflare/cloudflare_turnstile.js", - "example:challenge": "node --env-file-if-exists=.env examples/cloudflare/cloudflare_challenge_page.js", - "example:tencent": "node --env-file-if-exists=.env examples/tencent/tencent.js", - "example:yandex-smartcaptcha": "node --env-file-if-exists=.env examples/yandex/yandex_smartcaptcha.js", - "example:image": "node --env-file-if-exists=.env examples/normal_captcha/normal_captcha_screenshot.js", - "example:image-canvas": "node --env-file-if-exists=.env examples/normal_captcha/normal_captcha_canvas.js", - "example:image-params": "node --env-file-if-exists=.env examples/normal_captcha/normal_captcha_screenshot_params.js", - "example:coordinates": "node --env-file-if-exists=.env examples/coordinates/coordinates.js", + "start": "node --env-file-if-exists=.env index.js", + "recaptcha-v2": "node --env-file-if-exists=.env examples/reCAPTCHA/recaptcha_v2.js", + "recaptcha-v2-callback": "node --env-file-if-exists=.env examples/reCAPTCHA/recaptcha_v2_callback.js", + "recaptcha-v2-callback-auto": "node --env-file-if-exists=.env examples/reCAPTCHA/recaptcha_v2_callback_auto.js", + "recaptcha-v2-proxy": "node --env-file-if-exists=.env examples/reCAPTCHA/recaptcha_v2_proxy.js", + "recaptcha-v2-callback-proxy": "node --env-file-if-exists=.env examples/reCAPTCHA/recaptcha_v2_callback_proxy.js", + "recaptcha-v2-enterprise": "node --env-file-if-exists=.env examples/reCAPTCHA/recaptcha_v2_enterprise.js", + "recaptcha-v3": "node --env-file-if-exists=.env examples/reCAPTCHA/recaptcha_v3.js", + "turnstile": "node --env-file-if-exists=.env examples/cloudflare/turnstile.js", + "turnstile-challenge": "node --env-file-if-exists=.env examples/cloudflare/turnstile_challenge.js", + "tencent": "node --env-file-if-exists=.env examples/tencent/tencent.js", + "yandex": "node --env-file-if-exists=.env examples/yandex/yandex_smartcaptcha.js", + "yandex-image": "node --env-file-if-exists=.env examples/yandex/yandex_smartcaptcha_image.js", + "image-to-text": "node --env-file-if-exists=.env examples/normal_captcha/image_to_text.js", + "coordinates": "node --env-file-if-exists=.env examples/coordinates/coordinates.js", + "geetest-v3": "node --env-file-if-exists=.env examples/geetest/geetest_v3.js", + "geetest-v4": "node --env-file-if-exists=.env examples/geetest/geetest_v4.js", + "balance": "node --env-file-if-exists=.env examples/balance.js", "lint": "eslint .", - "check": "npm run lint && node scripts/check.js", + "format": "prettier --write .", + "format:check": "prettier --check .", + "check": "npm run lint && npm run format:check && node scripts/check.js && npm test", "test": "node --test tests/*.test.js", "test:live": "node --env-file-if-exists=.env scripts/live.js" }, "dependencies": { - "@captcha-solver-api/javascript-sdk": "^1.0.1", + "@captcha-solver-api/javascript-sdk": "^1.1.0", "puppeteer": "^25.13.0", "puppeteer-extra": "^3.3.6", "puppeteer-extra-plugin-stealth": "^2.11.2" @@ -42,9 +61,11 @@ "devDependencies": { "@eslint/js": "^9.39.5", "eslint": "^9.39.5", - "eslint-plugin-jsdoc": "^61.4.1" + "eslint-plugin-jsdoc": "^61.4.1", + "prettier": "^3.6.2" }, "overrides": { + "minimatch": "^11.0.1", "zod": "4.6.6" } } diff --git a/scripts/check.js b/scripts/check.js index 8dd711b..7d39266 100644 --- a/scripts/check.js +++ b/scripts/check.js @@ -1,4 +1,4 @@ -import { readdir } from 'node:fs/promises'; +import { readFile, readdir } from 'node:fs/promises'; import { spawnSync } from 'node:child_process'; /** Recursively yield JavaScript source files from a directory. */ @@ -10,10 +10,138 @@ async function* javascriptFiles(directory) { } } -for (const directory of ['config', 'examples', 'scripts', 'tests']) { +for (const directory of ['examples', 'scripts', 'tests']) { for await (const path of javascriptFiles(directory)) { - const result = spawnSync(process.execPath, ['--check', path], { stdio: 'inherit' }); + const result = spawnSync(process.execPath, ['--check', path], { + stdio: 'inherit', + }); if (result.status !== 0) process.exit(result.status || 1); } } + +const examplePaths = []; +const tokenApplicationNotice = + 'You must inspect the target page and determine the correct way to pass the token yourself.'; +for await (const path of javascriptFiles('examples')) { + examplePaths.push(path); + const source = await readFile(path, 'utf8'); + const forbiddenPatterns = [ + [/\basync\b|\bawait\b/, 'must use a Promise chain instead of async/await'], + [/_finallyRethrows|Promise\.resolve\(/, 'contains generated Promise wrapper code'], + [/(?:match|args)\[\d+\]/, 'contains a magic positional index'], + [/timeout:\s*\d/, 'contains an unnamed numeric timeout'], + [ + /from\s+['"]\.\.?\/[^'"]+\.js['"]/, + 'must be standalone and cannot import a local JavaScript module', + ], + ]; + for (const [pattern, message] of forbiddenPatterns) { + if (pattern.test(source)) throw new Error(`${path} ${message}.`); + } + + const allowedConsoleOutput = [ + /console\.log\('Task ID:', taskId\);/, + /console\.log\('Solution:', solution\);/, + /console\.log\('Page confirmation:', message\)/, + /console\.log\(`Page confirmation: \$\{message\}`\)/, + /console\.log\(solution\.(?:coordinates|text)\);/, + /console\.log\(balance\);/, + ]; + for (const line of source.split('\n').filter((value) => value.includes('console.log('))) { + if (!allowedConsoleOutput.some((pattern) => pattern.test(line))) { + throw new Error(`${path} contains unsupported console output: ${line.trim()}`); + } + } + + const guideCount = source.match(/How it works:/g)?.length || 0; + if (guideCount !== 1) { + throw new Error(`${path} must contain exactly one How it works guide.`); + } + const described = [...source.matchAll(/STEP-(?\d{2}) -/g)].map( + (match) => match.groups.number, + ); + const implementedList = [...source.matchAll(/\/\/ STEP-(?\d{2}):/g)].map( + (match) => match.groups.number, + ); + const implemented = new Set(implementedList); + const duplicateSteps = implementedList.filter( + (number, index) => implementedList.indexOf(number) !== index, + ); + if (duplicateSteps.some((number) => number !== described.at(-1))) { + throw new Error(`${path} implements a non-final STEP more than once.`); + } + described.forEach((number, index) => { + const expected = String(index + 1).padStart(2, '0'); + if (number !== expected || !implemented.has(number)) { + throw new Error(`${path} has an incomplete or non-sequential STEP-${number} guide.`); + } + }); + const describedSteps = new Set(described); + for (const number of implemented) { + if (!describedSteps.has(number)) { + throw new Error(`${path} implements undocumented STEP-${number}.`); + } + } + + if (source.includes("from 'puppeteer-extra'")) { + if (!source.includes('.catch(') || !source.includes('.finally(')) { + throw new Error(`${path} must handle errors and close Chromium in its Promise chain.`); + } + if ( + !/Token injection and submission are site-specific|Solution submission is site-specific/.test( + source, + ) + ) { + throw new Error(`${path} must explain its site-specific solution application.`); + } + if (!source.includes('Page confirmation:')) { + throw new Error( + `${path} must log its acceptance boundary separately from the solver result.`, + ); + } + const directExecutionIndex = source.indexOf('if (process.argv[1]'); + const errorHandlerIndex = source.indexOf('.catch((error)'); + if (errorHandlerIndex < directExecutionIndex) { + throw new Error(`${path} main() must reject so the live runner can report failures.`); + } + } + + const intro = source.match(/\/\*\*[\s\S]*?How it works:[\s\S]*?\*\//)?.[0] || ''; + const normalizedIntro = intro.replace(/\s+/g, ' ').replace(/\* /g, ''); + if (source.includes('.solve(') && !intro.includes('CaptchaClient.solve()')) { + throw new Error(`${path} intro must name CaptchaClient.solve().`); + } + if (source.includes('.getBalance(') && !intro.includes('CaptchaClient.getBalance()')) { + throw new Error(`${path} intro must name CaptchaClient.getBalance().`); + } + if ( + (source.includes('solution.gRecaptchaResponse') || source.includes('solution.token')) && + !normalizedIntro.includes(tokenApplicationNotice) + ) { + throw new Error(`${path} must tell users to determine the site-specific token flow.`); + } +} + +const packageJSON = JSON.parse(await readFile('package.json', 'utf8')); +const readme = await readFile('README.md', 'utf8'); +for (const path of examplePaths) { + const hasScript = Object.values(packageJSON.scripts).some((command) => command.endsWith(path)); + if (!hasScript) throw new Error(`${path} has no npm run command.`); + if (!readme.includes(`(${path})`)) { + throw new Error(`${path} is missing from the README example table.`); + } +} + +const envTemplate = await readFile('.env.example', 'utf8'); +const configuredEnvironmentNames = new Set( + [...envTemplate.matchAll(/^(?[A-Z][A-Z0-9_]*)=/gm)].map((match) => match.groups.name), +); +for (const path of examplePaths) { + const source = await readFile(path, 'utf8'); + for (const match of source.matchAll(/process\.env\.(?[A-Z][A-Z0-9_]*)/g)) { + if (!configuredEnvironmentNames.has(match.groups.name)) { + throw new Error(`${match.groups.name}, used by ${path}, is missing from .env.example.`); + } + } +} console.log('JavaScript syntax checks passed.'); diff --git a/scripts/live.js b/scripts/live.js index 9d46b06..af7323e 100644 --- a/scripts/live.js +++ b/scripts/live.js @@ -1,24 +1,25 @@ import { mkdir, readFile, writeFile } from 'node:fs/promises'; -import { basename } from 'node:path'; /** Remove locally configured credentials from live-test output. */ function redact(value) { let text = String(value); - for (const name of ['CAPTCHA_API_KEY', 'PROXY_LOGIN', 'PROXY_PASSWORD']) { + for (const name of ['CAPTCHA_API_KEY']) { if (process.env[name]) text = text.split(process.env[name]).join('[REDACTED]'); } return text; } const { scripts } = JSON.parse(await readFile(new URL('../package.json', import.meta.url), 'utf8')); -const paths = Object.fromEntries(Object.entries(scripts) - .filter(([name]) => name.startsWith('example:')) - .map(([, command]) => { - const path = command.split(' ').at(-1); - return [basename(path, '.js'), path]; - })); +const paths = Object.fromEntries( + Object.entries(scripts) + .filter(([, command]) => command.includes(' examples/')) + .map(([name, command]) => { + const path = command.split(' ').at(-1); + return [name, path]; + }), +); const allowed = Object.keys(paths); -const examples = allowed.filter((name) => !name.endsWith('_proxy') && name !== 'tencent'); +const examples = allowed.filter((name) => name !== 'tencent'); const selected = process.argv.slice(2).length ? process.argv.slice(2) : examples; if (selected.some((name) => !allowed.includes(name))) throw new Error('Unknown example name.'); await mkdir('artifacts', { recursive: true }); @@ -29,10 +30,19 @@ for (const name of selected) { try { const { main } = await import(new URL(`../${paths[name]}`, import.meta.url)); await main(); - report.results.push({ name, status: 'passed', seconds: (Date.now() - started) / 1000 }); + report.results.push({ + name, + status: 'passed', + seconds: (Date.now() - started) / 1000, + }); } catch (error) { console.error(`FAIL: ${name}: ${redact(error.message)}`); - report.results.push({ name, status: 'failed', seconds: (Date.now() - started) / 1000, error: redact(error.message) }); + report.results.push({ + name, + status: 'failed', + seconds: (Date.now() - started) / 1000, + error: redact(error.message), + }); process.exitCode = 1; } await writeFile(reportPath, JSON.stringify(report, null, 2)); diff --git a/tests/browser.test.js b/tests/browser.test.js index a058405..c01ac6a 100644 --- a/tests/browser.test.js +++ b/tests/browser.test.js @@ -6,19 +6,18 @@ import puppeteer from 'puppeteer-extra'; import StealthPlugin from 'puppeteer-extra-plugin-stealth'; import { CaptchaClient } from '@captcha-solver-api/javascript-sdk'; import { solveCaptcha as v2 } from '../examples/reCAPTCHA/recaptcha_v2.js'; +import { solveCaptcha as v2Callback } from '../examples/reCAPTCHA/recaptcha_v2_callback.js'; +import { solveCaptcha as v2CallbackAuto } from '../examples/reCAPTCHA/recaptcha_v2_callback_auto.js'; import { solveCaptcha as v2Proxy } from '../examples/reCAPTCHA/recaptcha_v2_proxy.js'; -import { solveCaptcha as callback } from '../examples/reCAPTCHA/recaptcha_v2_callback_variant1.js'; -import { solveCaptcha as callbackAuto } from '../examples/reCAPTCHA/recaptcha_v2_callback_variant2.js'; +import { solveCaptcha as v2CallbackProxy } from '../examples/reCAPTCHA/recaptcha_v2_callback_proxy.js'; +import { solveCaptcha as enterprise } from '../examples/reCAPTCHA/recaptcha_v2_enterprise.js'; import { solveCaptcha as v3 } from '../examples/reCAPTCHA/recaptcha_v3.js'; -import { solveCaptcha as v3Extended } from '../examples/reCAPTCHA/recaptcha_v3_extended_js_script.js'; -import { solveCaptcha as turnstile } from '../examples/cloudflare/cloudflare_turnstile.js'; -import { solveCaptcha as challenge } from '../examples/cloudflare/cloudflare_challenge_page.js'; +import { solveCaptcha as turnstile } from '../examples/cloudflare/turnstile.js'; +import { solveCaptcha as challenge } from '../examples/cloudflare/turnstile_challenge.js'; import { solveCaptcha as tencent } from '../examples/tencent/tencent.js'; import { solveCaptcha as yandex } from '../examples/yandex/yandex_smartcaptcha.js'; -import { solveCaptcha as imageScreenshot } from '../examples/normal_captcha/normal_captcha_screenshot.js'; -import { solveCaptcha as imageCanvas } from '../examples/normal_captcha/normal_captcha_canvas.js'; -import { solveCaptcha as imageParams } from '../examples/normal_captcha/normal_captcha_screenshot_params.js'; -import { solveCaptcha as coordinates } from '../examples/coordinates/coordinates.js'; +import { solveCaptcha as geetestV3 } from '../examples/geetest/geetest_v3.js'; +import { solveCaptcha as geetestV4 } from '../examples/geetest/geetest_v4.js'; puppeteer.use(StealthPlugin()); @@ -37,10 +36,8 @@ const fixtures = { `, - '/callback': `
`, '/v3': `${button}`, + '/challenge-passed': ``, + '/challenge-http-error': ``, '/already': ``, @@ -74,28 +86,34 @@ const fixtures = { document.querySelector('button').onclick = () => { if (Math.abs(window.clicked?.[0] - 50) < 2 && Math.abs(window.clicked?.[1] - 25) < 2) accept(); };`, - '/tencent': ``, '/yandex': `
`, + '/geetest-v3': ``, + '/geetest-v4': ``, }; before(async () => { - delete process.env.SUCCESS_SELECTOR; - delete process.env.SUBMIT_SELECTOR; - delete process.env.CALLBACK_NAME; - delete process.env.RECAPTCHA_SITEKEY; - delete process.env.RECAPTCHA_ACTION; - delete process.env.TENCENT_TRIGGER_SELECTOR; - delete process.env.TENCENT_SUCCESS_SELECTOR; - process.env.RECAPTCHA_MIN_SCORE = '0.3'; server = createServer(async (req, res) => { if (req.method === 'GET' && req.url === '/TCaptcha-global.js') { res.setHeader('Content-Type', 'text/javascript'); @@ -106,6 +124,18 @@ before(async () => { let body = ''; for await (const chunk of req) body += chunk; const data = JSON.parse(body); + if (req.url === '/api/v1/captcha-demo/gee-test/verify') { + assert.equal(data.geetest_validate, 'fixture-validate'); + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify({ success: true })); + return; + } + if (req.url === '/api/v1/captcha-demo/gee-test-v4/verify') { + assert.equal(data.captcha_id, 'fixture-captcha-id'); + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify({ result: 'success' })); + return; + } assert.equal(data.clientKey, 'fixture-key'); res.setHeader('Content-Type', 'application/json'); if (req.url === '/createTask') { @@ -113,16 +143,36 @@ before(async () => { receivedHeader = req.headers['x-sdk']; res.end(JSON.stringify({ errorId: 0, taskId: 1 })); } else if (req.url === '/getTaskResult') { - const solution = submitted.type === 'ImageToTextTask' ? { text: 'test' } - : submitted.type === 'CoordinatesTask' ? { coordinates: [{ x: 100, y: 50 }] } - : submitted.type === 'TurnstileTaskProxyless' ? { token: 'fixture-token', userAgent: 'FixtureBrowser/1.0' } - : submitted.type === 'TencentTaskProxyless' ? { appid: 'fixture-app-id', ret: 0, ticket: 'fixture-ticket', randstr: 'fixture-randstr' } - : submitted.type === 'YandexSmartCaptchaTaskProxyless' ? { token: 'fixture-token' } - : { gRecaptchaResponse: 'fixture-token' }; + const solution = + submitted.type === 'ImageToTextTask' + ? { text: 'test' } + : submitted.type === 'CoordinatesTask' + ? { coordinates: [{ x: 100, y: 50 }] } + : submitted.type === 'TurnstileTaskProxyless' + ? { token: 'fixture-token', userAgent: 'FixtureBrowser/1.0' } + : submitted.type === 'TencentTaskProxyless' + ? { + appid: 'fixture-app-id', + ret: 0, + ticket: 'fixture-ticket', + randstr: 'fixture-randstr', + } + : submitted.type === 'YandexSmartCaptchaTaskProxyless' + ? { token: 'fixture-token' } + : submitted.type === 'GeeTestTaskProxyless' && submitted.version === 4 + ? { captcha_id: 'fixture-captcha-id', lot_number: 'fixture-lot' } + : submitted.type === 'GeeTestTaskProxyless' + ? { + challenge: 'fixture-challenge', + validate: 'fixture-validate', + seccode: 'fixture-seccode', + } + : { gRecaptchaResponse: 'fixture-token' }; res.end(JSON.stringify({ errorId: 0, status: 'ready', solution })); } } else { res.setHeader('Content-Type', 'text/html'); + if (req.url === '/challenge-rejected') res.statusCode = 403; res.end(success + (fixtures[req.url] || '')); } }).listen(0, '127.0.0.1'); @@ -130,7 +180,6 @@ before(async () => { baseUrl = `http://127.0.0.1:${server.address().port}`; browser = await puppeteer.launch({ headless: true, - executablePath: process.env.BROWSER_EXECUTABLE_PATH || undefined, // GitHub's hosted runner requires Chrome's sandbox to be disabled. Local // examples keep the browser sandbox enabled. args: process.env.CI ? ['--no-sandbox', '--disable-setuid-sandbox'] : [], @@ -139,24 +188,43 @@ before(async () => { after(async () => { await browser?.close(); - if (server) await new Promise(resolve => server.close(resolve)); + if (server) await new Promise((resolve) => server.close(resolve)); process.env = originalEnv; }); /** Run an example flow against the local page and API fixtures. */ async function run(path, solveCaptcha, ...options) { - process.env.TARGET_URL = baseUrl + path; + const targetURL = baseUrl + path; + process.env.RECAPTCHA_V2_TARGET_URL = targetURL; + process.env.RECAPTCHA_V3_TARGET_URL = targetURL; + process.env.TURNSTILE_TARGET_URL = targetURL; + process.env.TURNSTILE_CHALLENGE_TARGET_URL = targetURL; + process.env.TENCENT_TARGET_URL = targetURL; submitted = null; const page = await browser.newPage(); page.setDefaultTimeout(3000); await page.setViewport({ width: 1000, height: 700, deviceScaleFactor: 1 }); - const solver = new CaptchaClient({ clientKey: 'fixture-key', baseUrl, timeout: 3000, pollingInterval: 1 }); + const solver = new CaptchaClient({ + clientKey: 'fixture-key', + baseUrl, + timeout: 3000, + pollingInterval: 1, + }); try { const message = await solveCaptcha(page, solver, ...options); - assert.match(message, /Demo accepted/); + assert.match( + message, + /Demo accepted|callback received|Hello, user!|Tencent callback received|challenge cleared and target page loaded/, + ); if (submitted) assert.match(receivedHeader, /^javascript-sdk\//); - return { task: submitted, userAgent: await page.evaluate(() => navigator.userAgent) }; - } finally { await page.close(); } + return { + message, + task: submitted, + userAgent: await page.evaluate(() => navigator.userAgent), + }; + } finally { + await page.close(); + } } test('v2 sends a real SDK request and submits the returned token', async () => { @@ -164,22 +232,45 @@ test('v2 sends a real SDK request and submits the returned token', async () => { assert.equal(task.type, 'RecaptchaV2TaskProxyless'); assert.equal(task.websiteKey, 'fixture-key'); }); -test('proxy variant passes the configured proxy into its task', async () => { - const { task } = await run('/v2', v2Proxy, { proxyType: 'http', proxyAddress: 'proxy.example.com', proxyPort: 8080 }); +test('v2 known-callback example delivers the returned token', async () => { + const { task } = await run('/v2-callback', v2Callback); + assert.equal(task.type, 'RecaptchaV2TaskProxyless'); +}); +test('v2 callback-discovery example finds and invokes the widget callback', async () => { + const { task } = await run('/v2-callback', v2CallbackAuto); + assert.equal(task.type, 'RecaptchaV2TaskProxyless'); +}); +test('v2 proxy example creates a proxy task and submits the token', async () => { + const proxy = { proxyType: 'http', proxyAddress: '127.0.0.1', proxyPort: 8080 }; + const { task } = await run('/v2', v2Proxy, proxy); + assert.equal(task.type, 'RecaptchaV2Task'); + assert.equal(task.proxyAddress, '127.0.0.1'); +}); +test('v2 callback proxy example creates a proxy task and invokes the callback', async () => { + const proxy = { proxyType: 'http', proxyAddress: '127.0.0.1', proxyPort: 8080 }; + const { task } = await run('/v2-callback', v2CallbackProxy, proxy); assert.equal(task.type, 'RecaptchaV2Task'); - assert.equal(task.proxyPort, 8080); }); -test('known callback receives the API token', async () => { await run('/callback', callback); }); -test('automatic discovery handles cyclic callback configuration', async () => { await run('/callback', callbackAuto); }); +test('Enterprise v2 creates the Enterprise task and verifies acceptance', async () => { + process.env.RECAPTCHA_ENTERPRISE_TARGET_URL = `${baseUrl}/v2`; + try { + const { task } = await run('/v2', enterprise); + assert.equal(task.type, 'RecaptchaV2EnterpriseTaskProxyless'); + } finally { + delete process.env.RECAPTCHA_ENTERPRISE_TARGET_URL; + } +}); test('v3 preserves the action extracted from the page script', async () => { const { task } = await run('/v3', v3); assert.equal(task.pageAction, 'fixture_action'); assert.equal(task.minScore, 0.3); }); -test('extended v3 resolves the intercepted promise with the API answer', async () => { await run('/v3', v3Extended); }); -test('embedded Turnstile submits its response field', async () => { await run('/turnstile', turnstile); }); +test('embedded Turnstile submits its response field', async () => { + await run('/turnstile', turnstile); +}); test('Challenge interception preserves session fields and the browser User-Agent', async () => { - const { task, userAgent } = await run('/challenge', challenge); + const { message, task, userAgent } = await run('/challenge', challenge); + assert.equal(message, 'challenge cleared and target page loaded.'); assert.equal(task.data, 'session-data'); assert.equal(task.pagedata, 'page-data'); assert.equal(task.action, 'managed'); @@ -189,39 +280,64 @@ test('Challenge interception preserves session fields and the browser User-Agent test('an already passed Challenge makes no paid request', async () => { assert.equal((await run('/already', challenge)).task, null); }); +test('Challenge rejects a failed navigation response', async () => { + await assert.rejects(run('/challenge-http-error', challenge), /HTTP 403/); +}); test('Tencent interception sends captured fields and invokes the original callback', async () => { - process.env.TENCENT_TRIGGER_SELECTOR = '#open-tencent'; - process.env.TENCENT_SUCCESS_SELECTOR = 'p[class*="successMessage"]'; const { task } = await run('/tencent', tencent); assert.equal(task.type, 'TencentTaskProxyless'); assert.equal(task.appId, 'fixture-app-id'); assert.match(task.captchaScript, /\/TCaptcha-global\.js$/); }); test('Yandex SmartCaptcha sends the site key and submits the returned token', async () => { - process.env.SUCCESS_SELECTOR = 'p[class*="successMessage"]'; + process.env.YANDEX_TARGET_URL = `${baseUrl}/yandex`; try { const { task, userAgent } = await run('/yandex', yandex); assert.equal(task.type, 'YandexSmartCaptchaTaskProxyless'); assert.equal(task.websiteKey, 'fixture-key'); assert.equal(task.userAgent, userAgent); } finally { - delete process.env.SUCCESS_SELECTOR; + delete process.env.YANDEX_TARGET_URL; } }); test('a Cloudflare block page fails before creating a paid task', async () => { await assert.rejects(run('/blocked', challenge), /blocked the browser/); assert.equal(submitted, null); }); -for (const [name, solveImage, hasHints] of [ - ['screenshot', imageScreenshot, false], - ['canvas', imageCanvas, false], - ['hints', imageParams, true], -]) { - test(`image ${name} sends image data and verifies recognized text`, async () => { - const { task } = await run('/image', solveImage); - assert.equal(task.type, 'ImageToTextTask'); - assert.ok(Buffer.from(task.body, 'base64').length > 100); - if (hasHints) assert.equal(task.numeric, 4); - }); -} -test('coordinate clicks account for image scaling and scroll position', async () => { await run('/coordinates', coordinates); }); +test('GeeTest v3 submits all returned verification fields', async () => { + process.env.GEETEST_V3_TARGET_URL = `${baseUrl}/geetest-v3`; + const page = await browser.newPage(); + try { + const solver = new CaptchaClient({ + clientKey: 'fixture-key', + baseUrl, + timeout: 3000, + pollingInterval: 1, + }); + assert.match(await geetestV3(page, solver), /accepted/); + assert.equal(submitted.type, 'GeeTestTaskProxyless'); + assert.equal(submitted.gt, 'fixture-gt'); + } finally { + delete process.env.GEETEST_V3_TARGET_URL; + await page.close(); + } +}); + +test('GeeTest v4 submits the complete solver response', async () => { + process.env.GEETEST_V4_TARGET_URL = `${baseUrl}/geetest-v4`; + const page = await browser.newPage(); + try { + const solver = new CaptchaClient({ + clientKey: 'fixture-key', + baseUrl, + timeout: 3000, + pollingInterval: 1, + }); + assert.match(await geetestV4(page, solver), /accepted/); + assert.equal(submitted.version, 4); + assert.equal(submitted.initParameters.captcha_id, 'fixture-captcha-id'); + } finally { + delete process.env.GEETEST_V4_TARGET_URL; + await page.close(); + } +}); diff --git a/tests/yandex-smartcaptcha-image.test.js b/tests/yandex-smartcaptcha-image.test.js new file mode 100644 index 0000000..e8ee0d4 --- /dev/null +++ b/tests/yandex-smartcaptcha-image.test.js @@ -0,0 +1,50 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { CaptchaClient } from '@captcha-solver-api/javascript-sdk'; +import { main } from '../examples/yandex/yandex_smartcaptcha_image.js'; + +test('Yandex image example sends the dedicated SmartCaptchaTask', async (context) => { + const originalFetch = globalThis.fetch; + const originalApiKey = process.env.CAPTCHA_API_KEY; + let submittedTask; + + context.after(() => { + globalThis.fetch = originalFetch; + if (originalApiKey === undefined) delete process.env.CAPTCHA_API_KEY; + else process.env.CAPTCHA_API_KEY = originalApiKey; + }); + + process.env.CAPTCHA_API_KEY = 'fixture-key'; + globalThis.fetch = (url, options) => { + const request = JSON.parse(options.body); + assert.equal(request.clientKey, 'fixture-key'); + + if (String(url).endsWith('/createTask')) { + submittedTask = request.task; + return Promise.resolve(globalThis.Response.json({ errorId: 0, taskId: 1 })); + } + + assert.match(String(url), /\/getTaskResult$/); + return Promise.resolve( + globalThis.Response.json({ + errorId: 0, + status: 'ready', + solution: { coordinates: [{ x: 57, y: 82 }] }, + }), + ); + }; + + const solution = await main( + new CaptchaClient({ + clientKey: 'fixture-key', + baseUrl: 'https://fixture.invalid', + pollingInterval: 1, + }), + ); + + assert.equal(submittedTask.type, 'SmartCaptchaTask'); + assert.ok(submittedTask.image); + assert.ok(submittedTask.imgInstructions); + assert.equal(submittedTask.body, undefined); + assert.deepEqual(solution.coordinates, [{ x: 57, y: 82 }]); +});