diff --git a/README.md b/README.md index cbeed12..8d9a3dc 100644 --- a/README.md +++ b/README.md @@ -35,11 +35,13 @@ Full API reference (all endpoints, error codes, captcha-type details): **https:/ - [Image to Text](#image-to-text) - [GeeTest (v3 & v4)](#geetest-v3--v4) - [Yandex SmartCaptcha](#yandex-smartcaptcha) + - [Kaleidoscope puzzle](#kaleidoscope-puzzle) - [Coordinates (click captcha)](#coordinates-click-captcha) - [Tencent](#tencent) - [Advanced Usage](#advanced-usage) - [Check balance](#check-balance) - [Custom timeout and polling](#custom-timeout-and-polling) + - [Debug mode](#debug-mode) - [Worker language pool](#worker-language-pool) - [Solving multiple captchas in parallel](#solving-multiple-captchas-in-parallel) - [Error handling](#error-handling) @@ -162,8 +164,9 @@ Constructor. Takes a single options object. |---|---|---|---| | `clientKey` | `string` | required | Your Captcha Solver API key. Throws `ValidationError` if empty. | | `baseUrl` | `string` | `https://api.captcha-solver.com` | API base URL. Override only for self-hosted/staging deployments. | -| `timeout` | `number` | `120000` | Default max milliseconds `solve()` waits for a solution before throwing `TimeoutError`. | +| `timeout` | `number` | `120000` | Per-request HTTP timeout and polling time budget used by `solve()`. | | `pollingInterval` | `number` | `5000` | Milliseconds between `getTaskResult` polls inside `solve()`. | +| `debug` | `boolean` | `false` | Print timestamped, sanitized request and `solve()` diagnostics with `console.debug`. See [Debug mode](#debug-mode). | There's no manual connection pool to open or close -- `fetch` (via Node's built-in `undici`) already reuses keep-alive connections per host automatically, unlike Python's @@ -179,8 +182,9 @@ solution -- wraps `createTask()` + `getTaskResult()` so you don't poll by hand. | `task` | task object | One of the classes from `Tasks` (see [Captcha Types](#captcha-types)). | | `languagePool` | `string \| null` | Optional worker pool selector, `'en'` or `'ru'`. Defaults to `null` (account default pool). | -Returns a `Promise` resolving to the `solution` object once `status` is `'ready'` -- -its shape depends on the task type (see [Captcha Types](#captcha-types)). +Returns a `Promise` resolving to the task-specific `solution` value once `status` is +`'ready'`. Most tasks return an object; Yandex SmartCaptcha Kaleidoscope returns a +string. See [Captcha Types](#captcha-types) for each result format. Rejects with `ApiError`, `TimeoutError`, or `NetworkError`. ### `createTask(task, languagePool)` @@ -188,19 +192,20 @@ Rejects with `ApiError`, `TimeoutError`, or `NetworkError`. Submits `task` and returns a `Promise` resolving to its numeric task ID, without waiting for a solution. Same parameters as `solve()`. Use this instead of `solve()` only if you need to manage polling yourself (e.g. checking on many tasks from a -different process). Rejects with `ApiError`, `NetworkError`. +different process). Rejects with `ApiError`, `TimeoutError`, or `NetworkError`. ### `getTaskResult(taskId)` -Fetches the current status of a task created with `createTask()`. Resolves to an -object with a `status` key (`'processing'` or `'ready'`); when `'ready'`, also has a -`solution` object. This is a single poll, not a wait -- call it repeatedly (as -`solve()` does) until `status` is `'ready'`. Rejects with `ApiError`, `NetworkError`. +Fetches the current status of a task created with `createTask()`. Resolves to the API +response with a `status` key (`'processing'` or `'ready'`); when `'ready'`, it also +has a task-specific `solution` value. This is a single poll, not a wait -- call it +repeatedly (as `solve()` does) until `status` is `'ready'`. Rejects with `ApiError`, +`TimeoutError`, or `NetworkError`. ### `getBalance()` Returns a `Promise` resolving to the account's current balance (`number`) in the -account's currency. Rejects with `ApiError`, `NetworkError`. +account's currency. Rejects with `ApiError`, `TimeoutError`, or `NetworkError`. ## Captcha Types @@ -677,6 +682,26 @@ const captchaSolver = new CaptchaClient({ }); ``` +### Debug mode + +Enable `debug` to inspect how the SDK communicates with the API. It logs timestamped +requests, server responses, errors, request duration, task status, and a final +`solve()` summary with the task ID, elapsed time, and poll count. + +```javascript +// Create a client with sanitized debug logging enabled. +const captchaSolver = new CaptchaClient({ + clientKey: 'your_api_key', + debug: true +}); +``` + +Credentials and cookies are masked, base64 images are replaced with their length, +and long strings are shortened. Review logs before sharing them because URLs and +custom task fields may still contain application-specific data. + +See [examples/debug_mode.js](examples/debug_mode.js) for a runnable example. + ### Worker language pool Pass `languagePool` as the second argument to `solve()` (or `createTask()`) to pick a @@ -756,9 +781,12 @@ matches this README. ## Running the examples -- **Image/click captchas** (`image_to_text.js`, `coordinates.js`) run end-to-end +- **Image/click captchas** (`image_to_text.js`, `image_to_text_math.js`, + `image_to_text_language_pool.js`, `coordinates.js`, `coordinates_traffic_lights.js`, + `yandex_smartcaptcha_image.js`, `yandex_smartcaptcha_kaleidoscope.js`, `debug_mode.js`) run end-to-end with nothing but a valid `CAPTCHA_API_KEY` -- they read sample images bundled in [examples/assets](examples/assets), no target page needed. +- **Token captchas** (`recaptcha_v2.js`, `recaptcha_v2_enterprise.js`, `recaptcha_v3.js`, `turnstile.js`, `yandex_smartcaptcha.js`, `geetest_v4.js`, `tencent.js`) use placeholder values (`https://example.com/...`, `YOUR_WEBSITE_KEY`, `YOUR_APP_ID`, `YOUR_CAPTCHA_ID`) -- replace these with the real values from your own target @@ -779,6 +807,7 @@ export CAPTCHA_API_KEY=your_api_key node examples/balance.js node examples/image_to_text.js node examples/coordinates.js +node examples/debug_mode.js ``` Full details, an example index, and a per-type breakdown of what each script @@ -786,7 +815,7 @@ covers live in [examples/README.md](examples/README.md). ## Requirements -- Node.js 18 or newer. Modern browser with fetch support. +- Node.js 18 or newer. The repository examples also rely on Node.js APIs and `dotenv`. - Captcha Solver account with a valid API key. ## API Documentation diff --git a/examples/README.md b/examples/README.md index 21d5b14..34f9cea 100644 --- a/examples/README.md +++ b/examples/README.md @@ -47,6 +47,7 @@ Additional one-scenario examples: - [`image_to_text_math.js`](image_to_text_math.js) — math CAPTCHA with an instruction image. - [`image_to_text_language_pool.js`](image_to_text_language_pool.js) — select the English worker pool. - [`coordinates_traffic_lights.js`](coordinates_traffic_lights.js) — click coordinates with an instruction image. +- [`debug_mode.js`](debug_mode.js) — enable `debug: true` and watch the SDK's request, response and solve summary log. > **Important:** `geetest_v3.js` and `geetest_v3_proxy.js` contain a placeholder > initialization endpoint. Replace it with the target website's endpoint and diff --git a/examples/balance.js b/examples/balance.js index 5afc88e..cded72e 100644 --- a/examples/balance.js +++ b/examples/balance.js @@ -1,24 +1,27 @@ +import 'dotenv/config'; +import { CaptchaClient } from '@captcha-solver-api/javascript-sdk'; + /** - * Example: Get account balance. + * Check the current Captcha Solver account balance without creating a CAPTCHA task. + * Set the CAPTCHA_API_KEY environment variable before running this example. * - * Prerequisites: - * Set the CAPTCHA_API_KEY environment variable. - * Returns the current available balance of your account. + * How it works: + * STEP-01 - Read the API key and configure the SDK client. + * STEP-02 - Request the account balance with CaptchaClient.getBalance(). + * STEP-03 - Print the returned amount or report an error. */ -import 'dotenv/config'; -import { CaptchaClient } from '@captcha-solver-api/javascript-sdk'; - +// STEP-01: Read the API key and configure the SDK client. const apiKey = process.env.CAPTCHA_API_KEY || 'YOUR_API_KEY'; - const captchaSolver = new CaptchaClient({ clientKey: apiKey }); -// Get the current account balance. -// Returns a float with the available amount in your account currency. +// STEP-02: Request the balance; this method does not create a CAPTCHA task. captchaSolver.getBalance() .then((balance) => { + // STEP-03: Print the available amount in the account currency. console.log('Balance:', balance); }) .catch((error) => { + // Report SDK or transport failures without hiding the rejected Promise. console.error(error); }); diff --git a/examples/coordinates.js b/examples/coordinates.js index fb6c748..f4178d0 100644 --- a/examples/coordinates.js +++ b/examples/coordinates.js @@ -2,12 +2,37 @@ import 'dotenv/config'; import fs from 'fs'; import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; +/** + * Solve a coordinate CAPTCHA from a local image without a proxy. + * It creates Tasks.CoordinatesTask from the shown parameters, submits it with + * CaptchaClient.solve(), and prints the relevant returned value. Applying that value to a + * target page is site-specific. Replace all target-specific placeholders before running. + * + * How it works: + * STEP-01 - Configure the SDK client. + * STEP-02 - Create the CAPTCHA task from the required parameters or local assets. + * STEP-03 - Submit the task and wait for CaptchaClient.solve() to return the solution. + * STEP-04 - Print the relevant solution value or report an error. + */ + + +// STEP-01: Configure the SDK client with the API key. const client = new CaptchaClient({ clientKey: process.env.CAPTCHA_API_KEY || 'YOUR_API_KEY' }); + +// STEP-02: Create the CAPTCHA task with the values required by this challenge. const task = new Tasks.CoordinatesTask({ body: fs.readFileSync(new URL('./assets/coordinates-captcha.png', import.meta.url)).toString('base64'), comment: 'Click on the green apple' }); + +// STEP-03: Submit the task; solve() handles task creation and polling. client.solve(task) - .then((solution) => console.log(solution.coordinates)) - .catch(console.error); + .then((solution) => { + // STEP-04: Print only the useful field returned for this CAPTCHA type. + console.log(solution.coordinates); + }) + .catch((error) => { + // Report SDK or transport failures without hiding the rejected Promise. + console.error(error); + }); diff --git a/examples/coordinates_traffic_lights.js b/examples/coordinates_traffic_lights.js index 00ee1ab..998d637 100644 --- a/examples/coordinates_traffic_lights.js +++ b/examples/coordinates_traffic_lights.js @@ -2,7 +2,24 @@ import 'dotenv/config'; import fs from 'fs'; import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; +/** + * Solve an instruction-image coordinate CAPTCHA without a proxy. + * It creates Tasks.CoordinatesTask from the shown parameters, submits it with + * CaptchaClient.solve(), and prints the relevant returned value. Applying that value to a + * target page is site-specific. Replace all target-specific placeholders before running. + * + * How it works: + * STEP-01 - Configure the SDK client. + * STEP-02 - Create the CAPTCHA task from the required parameters or local assets. + * STEP-03 - Submit the task and wait for CaptchaClient.solve() to return the solution. + * STEP-04 - Print the relevant solution value or report an error. + */ + + +// STEP-01: Configure the SDK client with the API key. const client = new CaptchaClient({ clientKey: process.env.CAPTCHA_API_KEY || 'YOUR_API_KEY' }); + +// STEP-02: Create the CAPTCHA task with the values required by this challenge. const task = new Tasks.CoordinatesTask({ body: fs.readFileSync(new URL('./assets/traffic-lights.png', import.meta.url)).toString('base64'), imgInstructions: fs.readFileSync(new URL('./assets/traffic-lights-instructions.png', import.meta.url)).toString('base64'), @@ -10,6 +27,14 @@ const task = new Tasks.CoordinatesTask({ maxClicks: 5 }); + +// STEP-03: Submit the task; solve() handles task creation and polling. client.solve(task) - .then((solution) => console.log(solution.coordinates)) - .catch(console.error); + .then((solution) => { + // STEP-04: Print only the useful field returned for this CAPTCHA type. + console.log(solution.coordinates); + }) + .catch((error) => { + // Report SDK or transport failures without hiding the rejected Promise. + console.error(error); + }); diff --git a/examples/debug_mode.js b/examples/debug_mode.js new file mode 100644 index 0000000..eff0297 --- /dev/null +++ b/examples/debug_mode.js @@ -0,0 +1,46 @@ +import 'dotenv/config'; +import fs from 'fs'; +import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; + +/** + * Debug mode: watch every API request, server response and the final solve summary. + * It enables `debug: true`, solves a text CAPTCHA from a bundled image with + * CaptchaClient.solve(), and prints the recognized text. The `[CaptchaClient] ...` + * lines are the SDK's debug log; the last line is printed by this example. + * Credentials in the log are shown as [MASKED], so the output is safe to share. + * + * How it works: + * STEP-01 - Configure the SDK client with debug logging enabled. + * STEP-02 - Create the CAPTCHA task from a local image. + * STEP-03 - Submit the task; the SDK logs each request and a SOLVE SUMMARY. + * STEP-04 - Print the solution or report an error. + */ + +if (!process.env.CAPTCHA_API_KEY) { + throw new Error('Set CAPTCHA_API_KEY in .env or in the current shell before running this example.'); +} + +// STEP-01: Configure the SDK client; debug: true turns on the debug log. +const client = new CaptchaClient({ + clientKey: process.env.CAPTCHA_API_KEY, + debug: true +}); + +// STEP-02: Create the CAPTCHA task from the bundled sample image. +const task = new Tasks.ImageToText({ + body: fs.readFileSync(new URL('./assets/text-captcha.png', import.meta.url)).toString('base64'), + numeric: 2, + minLength: 4, + maxLength: 6 +}); + +// STEP-03: Submit the task; solve() handles task creation and polling and logs each step. +client.solve(task) + .then((solution) => { + // STEP-04: Print the result returned by solve(), after the SDK's SOLVE SUMMARY. + console.log('Result:', solution.text); + }) + .catch((error) => { + // Report SDK or transport failures without hiding the rejected Promise. + console.error(error); + }); diff --git a/examples/geetest_v3.js b/examples/geetest_v3.js index 12223f2..d4125d5 100644 --- a/examples/geetest_v3.js +++ b/examples/geetest_v3.js @@ -1,14 +1,39 @@ import 'dotenv/config'; import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; +/** + * Solve GeeTest v3 with a challenge fetched from the target site and without a proxy. + * It creates Tasks.GeeTestProxyless from the shown parameters, submits it with + * CaptchaClient.solve(), and prints the relevant returned value. Applying that value to a + * target page is site-specific. Replace all target-specific placeholders before running. + * + * How it works: + * STEP-01 - Configure the SDK client. + * STEP-02 - Fetch the current challenge from the target site's GeeTest endpoint. + * STEP-03 - Create and submit the task, then wait for CaptchaClient.solve(). + * STEP-04 - Print the relevant solution value or report an error. + */ + + +// STEP-01: Configure the SDK client with the API key. const client = new CaptchaClient({ clientKey: process.env.CAPTCHA_API_KEY || 'YOUR_API_KEY', timeout: 300000 }); +// STEP-02: Fetch the dynamic challenge immediately before creating the task. fetch('https://target-site.com/path/to/geetest/init') .then((response) => response.json()) - .then(({ challenge }) => client.solve(new Tasks.GeeTestProxyless({ - websiteURL: 'https://example.com/login', - gt: 'YOUR_GT_KEY', - challenge - }))) - .then((solution) => console.log(solution)) - .catch(console.error); + .then(({ challenge }) => { + // STEP-03: Submit a task that uses the fresh challenge returned by the target site. + return client.solve(new Tasks.GeeTestProxyless({ + websiteURL: 'https://example.com/login', + gt: 'YOUR_GT_KEY', + challenge + })); + }) + .then((solution) => { + // STEP-04: Print only the useful field returned for this CAPTCHA type. + console.log(solution); + }) + .catch((error) => { + // Report SDK or transport failures without hiding the rejected Promise. + console.error(error); + }); diff --git a/examples/geetest_v3_proxy.js b/examples/geetest_v3_proxy.js index 21b4bbc..3511ad7 100644 --- a/examples/geetest_v3_proxy.js +++ b/examples/geetest_v3_proxy.js @@ -1,17 +1,42 @@ import 'dotenv/config'; import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; +/** + * Solve GeeTest v3 with a challenge fetched from the target site and a customer proxy. + * It creates Tasks.GeeTest from the shown parameters, submits it with + * CaptchaClient.solve(), and prints the relevant returned value. Applying that value to a + * target page is site-specific. Replace all target-specific placeholders before running. + * + * How it works: + * STEP-01 - Configure the SDK client. + * STEP-02 - Fetch the current challenge from the target site's GeeTest endpoint. + * STEP-03 - Create and submit the proxied task, then wait for CaptchaClient.solve(). + * STEP-04 - Print the relevant solution value or report an error. + */ + + +// STEP-01: Configure the SDK client with the API key. const client = new CaptchaClient({ clientKey: process.env.CAPTCHA_API_KEY || 'YOUR_API_KEY', timeout: 300000 }); +// STEP-02: Fetch the dynamic challenge immediately before creating the task. fetch('https://target-site.com/path/to/geetest/init') .then((response) => response.json()) - .then(({ challenge }) => client.solve(new Tasks.GeeTest({ - websiteURL: 'https://example.com/login', - gt: 'YOUR_GT_KEY', - challenge, - proxyType: 'http', - proxyAddress: '1.2.3.4', - proxyPort: 8080 - }))) - .then((solution) => console.log(solution)) - .catch(console.error); + .then(({ challenge }) => { + // STEP-03: Submit a proxied task with the fresh challenge returned by the target site. + return client.solve(new Tasks.GeeTest({ + websiteURL: 'https://example.com/login', + gt: 'YOUR_GT_KEY', + challenge, + proxyType: 'http', + proxyAddress: '1.2.3.4', + proxyPort: 8080 + })); + }) + .then((solution) => { + // STEP-04: Print only the useful field returned for this CAPTCHA type. + console.log(solution); + }) + .catch((error) => { + // Report SDK or transport failures without hiding the rejected Promise. + console.error(error); + }); diff --git a/examples/geetest_v4.js b/examples/geetest_v4.js index 8c1084c..3e3123a 100644 --- a/examples/geetest_v4.js +++ b/examples/geetest_v4.js @@ -1,13 +1,38 @@ import 'dotenv/config'; import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; +/** + * Solve GeeTest v4 without a proxy. + * It creates Tasks.GeeTestProxyless from the shown parameters, submits it with + * CaptchaClient.solve(), and prints the relevant returned value. Applying that value to a + * target page is site-specific. Replace all target-specific placeholders before running. + * + * How it works: + * STEP-01 - Configure the SDK client. + * STEP-02 - Create the CAPTCHA task from the required parameters or local assets. + * STEP-03 - Submit the task and wait for CaptchaClient.solve() to return the solution. + * STEP-04 - Print the relevant solution value or report an error. + */ + + +// STEP-01: Configure the SDK client with the API key. const client = new CaptchaClient({ clientKey: process.env.CAPTCHA_API_KEY || 'YOUR_API_KEY', timeout: 300000 }); + +// STEP-02: Create the CAPTCHA task with the values required by this challenge. const task = new Tasks.GeeTestProxyless({ websiteURL: 'https://example.com/login', version: 4, initParameters: { captcha_id: 'YOUR_CAPTCHA_ID' } }); + +// STEP-03: Submit the task; solve() handles task creation and polling. client.solve(task) - .then((solution) => console.log(solution)) - .catch(console.error); + .then((solution) => { + // STEP-04: Print only the useful field returned for this CAPTCHA type. + console.log(solution); + }) + .catch((error) => { + // Report SDK or transport failures without hiding the rejected Promise. + console.error(error); + }); diff --git a/examples/geetest_v4_proxy.js b/examples/geetest_v4_proxy.js index 1ff188e..66c4f31 100644 --- a/examples/geetest_v4_proxy.js +++ b/examples/geetest_v4_proxy.js @@ -1,7 +1,24 @@ import 'dotenv/config'; import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; +/** + * Solve GeeTest v4 through a customer proxy. + * It creates Tasks.GeeTest from the shown parameters, submits it with + * CaptchaClient.solve(), and prints the relevant returned value. Applying that value to a + * target page is site-specific. Replace all target-specific placeholders before running. + * + * How it works: + * STEP-01 - Configure the SDK client. + * STEP-02 - Create the CAPTCHA task from the required parameters or local assets. + * STEP-03 - Submit the task and wait for CaptchaClient.solve() to return the solution. + * STEP-04 - Print the relevant solution value or report an error. + */ + + +// STEP-01: Configure the SDK client with the API key. const client = new CaptchaClient({ clientKey: process.env.CAPTCHA_API_KEY || 'YOUR_API_KEY', timeout: 300000 }); + +// STEP-02: Create the CAPTCHA task with the values required by this challenge. const task = new Tasks.GeeTest({ websiteURL: 'https://example.com/login', version: 4, @@ -11,6 +28,14 @@ const task = new Tasks.GeeTest({ proxyPort: 8080 }); + +// STEP-03: Submit the task; solve() handles task creation and polling. client.solve(task) - .then((solution) => console.log(solution)) - .catch(console.error); + .then((solution) => { + // STEP-04: Print only the useful field returned for this CAPTCHA type. + console.log(solution); + }) + .catch((error) => { + // Report SDK or transport failures without hiding the rejected Promise. + console.error(error); + }); diff --git a/examples/image_to_text.js b/examples/image_to_text.js index ca2bd02..556b33b 100644 --- a/examples/image_to_text.js +++ b/examples/image_to_text.js @@ -2,7 +2,24 @@ import 'dotenv/config'; import fs from 'fs'; import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; +/** + * Recognize a constrained text CAPTCHA from a local image. + * It creates Tasks.ImageToText from the shown parameters, submits it with + * CaptchaClient.solve(), and prints the relevant returned value. Applying that value to a + * target page is site-specific. Replace all target-specific placeholders before running. + * + * How it works: + * STEP-01 - Configure the SDK client. + * STEP-02 - Create the CAPTCHA task from the required parameters or local assets. + * STEP-03 - Submit the task and wait for CaptchaClient.solve() to return the solution. + * STEP-04 - Print the relevant solution value or report an error. + */ + + +// STEP-01: Configure the SDK client with the API key. const client = new CaptchaClient({ clientKey: process.env.CAPTCHA_API_KEY || 'YOUR_API_KEY' }); + +// STEP-02: Create the CAPTCHA task with the values required by this challenge. const task = new Tasks.ImageToText({ body: fs.readFileSync(new URL('./assets/text-captcha.png', import.meta.url)).toString('base64'), numeric: 2, @@ -10,6 +27,14 @@ const task = new Tasks.ImageToText({ maxLength: 6 }); + +// STEP-03: Submit the task; solve() handles task creation and polling. client.solve(task) - .then((solution) => console.log(solution.text)) - .catch(console.error); + .then((solution) => { + // STEP-04: Print only the useful field returned for this CAPTCHA type. + console.log(solution.text); + }) + .catch((error) => { + // Report SDK or transport failures without hiding the rejected Promise. + console.error(error); + }); diff --git a/examples/image_to_text_language_pool.js b/examples/image_to_text_language_pool.js index db08a44..10eb972 100644 --- a/examples/image_to_text_language_pool.js +++ b/examples/image_to_text_language_pool.js @@ -2,11 +2,36 @@ import 'dotenv/config'; import fs from 'fs'; import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; +/** + * Recognize a text CAPTCHA with the English worker pool. + * It creates Tasks.ImageToText from the shown parameters, submits it with + * CaptchaClient.solve(), and prints the relevant returned value. Applying that value to a + * target page is site-specific. Replace all target-specific placeholders before running. + * + * How it works: + * STEP-01 - Configure the SDK client. + * STEP-02 - Create the CAPTCHA task from the required parameters or local assets. + * STEP-03 - Submit the task and wait for CaptchaClient.solve() to return the solution. + * STEP-04 - Print the relevant solution value or report an error. + */ + + +// STEP-01: Configure the SDK client with the API key. const client = new CaptchaClient({ clientKey: process.env.CAPTCHA_API_KEY || 'YOUR_API_KEY' }); + +// STEP-02: Create the CAPTCHA task with the values required by this challenge. const task = new Tasks.ImageToText({ body: fs.readFileSync(new URL('./assets/text-captcha.png', import.meta.url)).toString('base64') }); + +// STEP-03: Submit the task; solve() handles task creation and polling. client.solve(task, 'en') - .then((solution) => console.log(solution.text)) - .catch(console.error); + .then((solution) => { + // STEP-04: Print only the useful field returned for this CAPTCHA type. + console.log(solution.text); + }) + .catch((error) => { + // Report SDK or transport failures without hiding the rejected Promise. + console.error(error); + }); diff --git a/examples/image_to_text_math.js b/examples/image_to_text_math.js index 8c7dcaa..f27bdec 100644 --- a/examples/image_to_text_math.js +++ b/examples/image_to_text_math.js @@ -2,7 +2,24 @@ import 'dotenv/config'; import fs from 'fs'; import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; +/** + * Solve a mathematical image-to-text CAPTCHA with image instructions. + * It creates Tasks.ImageToText from the shown parameters, submits it with + * CaptchaClient.solve(), and prints the relevant returned value. Applying that value to a + * target page is site-specific. Replace all target-specific placeholders before running. + * + * How it works: + * STEP-01 - Configure the SDK client. + * STEP-02 - Create the CAPTCHA task from the required parameters or local assets. + * STEP-03 - Submit the task and wait for CaptchaClient.solve() to return the solution. + * STEP-04 - Print the relevant solution value or report an error. + */ + + +// STEP-01: Configure the SDK client with the API key. const client = new CaptchaClient({ clientKey: process.env.CAPTCHA_API_KEY || 'YOUR_API_KEY' }); + +// STEP-02: Create the CAPTCHA task with the values required by this challenge. const task = new Tasks.ImageToText({ body: fs.readFileSync(new URL('./assets/captcha-math.png', import.meta.url)).toString('base64'), math: true, @@ -10,6 +27,14 @@ const task = new Tasks.ImageToText({ imgInstructions: fs.readFileSync(new URL('./assets/captcha-math-instructions.png', import.meta.url)).toString('base64') }); + +// STEP-03: Submit the task; solve() handles task creation and polling. client.solve(task) - .then((solution) => console.log(solution.text)) - .catch(console.error); + .then((solution) => { + // STEP-04: Print only the useful field returned for this CAPTCHA type. + console.log(solution.text); + }) + .catch((error) => { + // Report SDK or transport failures without hiding the rejected Promise. + console.error(error); + }); diff --git a/examples/recaptcha_v2.js b/examples/recaptcha_v2.js index 2e7b01f..5566c28 100644 --- a/examples/recaptcha_v2.js +++ b/examples/recaptcha_v2.js @@ -1,12 +1,37 @@ import 'dotenv/config'; import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; +/** + * Solve reCAPTCHA v2 without a proxy. + * It creates Tasks.RecaptchaV2Proxyless from the shown parameters, submits it with + * CaptchaClient.solve(), and prints the relevant returned value. Applying that value to a + * target page is site-specific. Replace all target-specific placeholders before running. + * + * How it works: + * STEP-01 - Configure the SDK client. + * STEP-02 - Create the CAPTCHA task from the required parameters or local assets. + * STEP-03 - Submit the task and wait for CaptchaClient.solve() to return the solution. + * STEP-04 - Print the relevant solution value or report an error. + */ + + +// STEP-01: Configure the SDK client with the API key. const client = new CaptchaClient({ clientKey: process.env.CAPTCHA_API_KEY || 'YOUR_API_KEY' }); + +// STEP-02: Create the CAPTCHA task with the values required by this challenge. const task = new Tasks.RecaptchaV2Proxyless({ websiteURL: 'https://example.com/login', websiteKey: 'YOUR_WEBSITE_KEY' }); + +// STEP-03: Submit the task; solve() handles task creation and polling. client.solve(task) - .then((solution) => console.log(solution.gRecaptchaResponse)) - .catch(console.error); + .then((solution) => { + // STEP-04: Print only the useful field returned for this CAPTCHA type. + console.log(solution.gRecaptchaResponse); + }) + .catch((error) => { + // Report SDK or transport failures without hiding the rejected Promise. + console.error(error); + }); diff --git a/examples/recaptcha_v2_enterprise.js b/examples/recaptcha_v2_enterprise.js index dd7c6e3..7737f14 100644 --- a/examples/recaptcha_v2_enterprise.js +++ b/examples/recaptcha_v2_enterprise.js @@ -1,12 +1,37 @@ import 'dotenv/config'; import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; +/** + * Solve reCAPTCHA v2 Enterprise without a proxy. + * It creates Tasks.RecaptchaV2EnterpriseProxyless from the shown parameters, submits it with + * CaptchaClient.solve(), and prints the relevant returned value. Applying that value to a + * target page is site-specific. Replace all target-specific placeholders before running. + * + * How it works: + * STEP-01 - Configure the SDK client. + * STEP-02 - Create the CAPTCHA task from the required parameters or local assets. + * STEP-03 - Submit the task and wait for CaptchaClient.solve() to return the solution. + * STEP-04 - Print the relevant solution value or report an error. + */ + + +// STEP-01: Configure the SDK client with the API key. const client = new CaptchaClient({ clientKey: process.env.CAPTCHA_API_KEY || 'YOUR_API_KEY' }); + +// STEP-02: Create the CAPTCHA task with the values required by this challenge. const task = new Tasks.RecaptchaV2EnterpriseProxyless({ websiteURL: 'https://example.com/login', websiteKey: 'YOUR_WEBSITE_KEY' }); + +// STEP-03: Submit the task; solve() handles task creation and polling. client.solve(task) - .then((solution) => console.log(solution.gRecaptchaResponse)) - .catch(console.error); + .then((solution) => { + // STEP-04: Print only the useful field returned for this CAPTCHA type. + console.log(solution.gRecaptchaResponse); + }) + .catch((error) => { + // Report SDK or transport failures without hiding the rejected Promise. + console.error(error); + }); diff --git a/examples/recaptcha_v2_enterprise_proxy.js b/examples/recaptcha_v2_enterprise_proxy.js index 6817580..3add9b2 100644 --- a/examples/recaptcha_v2_enterprise_proxy.js +++ b/examples/recaptcha_v2_enterprise_proxy.js @@ -1,7 +1,24 @@ import 'dotenv/config'; import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; +/** + * Solve reCAPTCHA v2 Enterprise through a customer proxy. + * It creates Tasks.RecaptchaV2Enterprise from the shown parameters, submits it with + * CaptchaClient.solve(), and prints the relevant returned value. Applying that value to a + * target page is site-specific. Replace all target-specific placeholders before running. + * + * How it works: + * STEP-01 - Configure the SDK client. + * STEP-02 - Create the CAPTCHA task from the required parameters or local assets. + * STEP-03 - Submit the task and wait for CaptchaClient.solve() to return the solution. + * STEP-04 - Print the relevant solution value or report an error. + */ + + +// STEP-01: Configure the SDK client with the API key. const client = new CaptchaClient({ clientKey: process.env.CAPTCHA_API_KEY || 'YOUR_API_KEY' }); + +// STEP-02: Create the CAPTCHA task with the values required by this challenge. const task = new Tasks.RecaptchaV2Enterprise({ websiteURL: 'https://example.com/login', websiteKey: 'YOUR_WEBSITE_KEY', @@ -10,6 +27,14 @@ const task = new Tasks.RecaptchaV2Enterprise({ proxyPort: 8080 }); + +// STEP-03: Submit the task; solve() handles task creation and polling. client.solve(task) - .then((solution) => console.log(solution.gRecaptchaResponse)) - .catch(console.error); + .then((solution) => { + // STEP-04: Print only the useful field returned for this CAPTCHA type. + console.log(solution.gRecaptchaResponse); + }) + .catch((error) => { + // Report SDK or transport failures without hiding the rejected Promise. + console.error(error); + }); diff --git a/examples/recaptcha_v2_proxy.js b/examples/recaptcha_v2_proxy.js index 2dc1745..ab7c1c6 100644 --- a/examples/recaptcha_v2_proxy.js +++ b/examples/recaptcha_v2_proxy.js @@ -1,7 +1,24 @@ import 'dotenv/config'; import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; +/** + * Solve reCAPTCHA v2 through a customer proxy. + * It creates Tasks.RecaptchaV2 from the shown parameters, submits it with + * CaptchaClient.solve(), and prints the relevant returned value. Applying that value to a + * target page is site-specific. Replace all target-specific placeholders before running. + * + * How it works: + * STEP-01 - Configure the SDK client. + * STEP-02 - Create the CAPTCHA task from the required parameters or local assets. + * STEP-03 - Submit the task and wait for CaptchaClient.solve() to return the solution. + * STEP-04 - Print the relevant solution value or report an error. + */ + + +// STEP-01: Configure the SDK client with the API key. const client = new CaptchaClient({ clientKey: process.env.CAPTCHA_API_KEY || 'YOUR_API_KEY' }); + +// STEP-02: Create the CAPTCHA task with the values required by this challenge. const task = new Tasks.RecaptchaV2({ websiteURL: 'https://example.com/login', websiteKey: 'YOUR_WEBSITE_KEY', @@ -12,6 +29,14 @@ const task = new Tasks.RecaptchaV2({ proxyPassword: 'password' }); + +// STEP-03: Submit the task; solve() handles task creation and polling. client.solve(task) - .then((solution) => console.log(solution.gRecaptchaResponse)) - .catch(console.error); + .then((solution) => { + // STEP-04: Print only the useful field returned for this CAPTCHA type. + console.log(solution.gRecaptchaResponse); + }) + .catch((error) => { + // Report SDK or transport failures without hiding the rejected Promise. + console.error(error); + }); diff --git a/examples/recaptcha_v3.js b/examples/recaptcha_v3.js index b3ffc63..c237b85 100644 --- a/examples/recaptcha_v3.js +++ b/examples/recaptcha_v3.js @@ -1,15 +1,27 @@ +import 'dotenv/config'; +import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; + /** - * Promise-chain example: Solve reCAPTCHA v3 without a customer proxy. - * Set CAPTCHA_API_KEY and replace the page-specific values before running. + * Solve reCAPTCHA v3 without a proxy. + * It creates Tasks.RecaptchaV3Proxyless from the shown parameters, submits it with + * CaptchaClient.solve(), and prints the relevant returned value. Applying that value to a + * target page is site-specific. Replace all target-specific placeholders before running. + * + * How it works: + * STEP-01 - Configure the SDK client. + * STEP-02 - Create the CAPTCHA task from the required parameters or local assets. + * STEP-03 - Submit the task and wait for CaptchaClient.solve() to return the solution. + * STEP-04 - Print the relevant solution value or report an error. */ -import 'dotenv/config'; -import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; +// STEP-01: Configure the SDK client with the API key. const captchaSolver = new CaptchaClient({ clientKey: process.env.CAPTCHA_API_KEY || 'YOUR_API_KEY' }); + +// STEP-02: Create the CAPTCHA task with the values required by this challenge. const task = new Tasks.RecaptchaV3Proxyless({ websiteURL: 'https://example.com/login', websiteKey: 'YOUR_WEBSITE_KEY', @@ -17,6 +29,14 @@ const task = new Tasks.RecaptchaV3Proxyless({ pageAction: 'homepage' }); + +// STEP-03: Submit the task; solve() handles task creation and polling. captchaSolver.solve(task) - .then((result) => console.log('result:', result)) - .catch((error) => console.error(error)); + .then((result) => { + // STEP-04: Print the solution returned for this CAPTCHA type. + console.log('Solution:', result); + }) + .catch((error) => { + // Report SDK or transport failures without hiding the rejected Promise. + console.error(error); + }); diff --git a/examples/tencent.js b/examples/tencent.js index e827ff4..8ce1b0d 100644 --- a/examples/tencent.js +++ b/examples/tencent.js @@ -1,12 +1,37 @@ import 'dotenv/config'; import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; +/** + * Solve Tencent CAPTCHA without a proxy. + * It creates Tasks.TencentTaskProxyless from the shown parameters, submits it with + * CaptchaClient.solve(), and prints the relevant returned value. Applying that value to a + * target page is site-specific. Replace all target-specific placeholders before running. + * + * How it works: + * STEP-01 - Configure the SDK client. + * STEP-02 - Create the CAPTCHA task from the required parameters or local assets. + * STEP-03 - Submit the task and wait for CaptchaClient.solve() to return the solution. + * STEP-04 - Print the relevant solution value or report an error. + */ + + +// STEP-01: Configure the SDK client with the API key. const client = new CaptchaClient({ clientKey: process.env.CAPTCHA_API_KEY || 'YOUR_API_KEY' }); + +// STEP-02: Create the CAPTCHA task with the values required by this challenge. const task = new Tasks.TencentTaskProxyless({ websiteURL: 'https://example.com/register', appId: 'YOUR_APP_ID' }); + +// STEP-03: Submit the task; solve() handles task creation and polling. client.solve(task) - .then((solution) => console.log(solution)) - .catch(console.error); + .then((solution) => { + // STEP-04: Print only the useful field returned for this CAPTCHA type. + console.log(solution); + }) + .catch((error) => { + // Report SDK or transport failures without hiding the rejected Promise. + console.error(error); + }); diff --git a/examples/tencent_proxy.js b/examples/tencent_proxy.js index b92f239..8f6e721 100644 --- a/examples/tencent_proxy.js +++ b/examples/tencent_proxy.js @@ -1,7 +1,24 @@ import 'dotenv/config'; import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; +/** + * Solve Tencent CAPTCHA through a customer proxy. + * It creates Tasks.TencentTask from the shown parameters, submits it with + * CaptchaClient.solve(), and prints the relevant returned value. Applying that value to a + * target page is site-specific. Replace all target-specific placeholders before running. + * + * How it works: + * STEP-01 - Configure the SDK client. + * STEP-02 - Create the CAPTCHA task from the required parameters or local assets. + * STEP-03 - Submit the task and wait for CaptchaClient.solve() to return the solution. + * STEP-04 - Print the relevant solution value or report an error. + */ + + +// STEP-01: Configure the SDK client with the API key. const client = new CaptchaClient({ clientKey: process.env.CAPTCHA_API_KEY || 'YOUR_API_KEY' }); + +// STEP-02: Create the CAPTCHA task with the values required by this challenge. const task = new Tasks.TencentTask({ websiteURL: 'https://example.com/register', appId: 'YOUR_APP_ID', @@ -10,6 +27,14 @@ const task = new Tasks.TencentTask({ proxyPort: 8080 }); + +// STEP-03: Submit the task; solve() handles task creation and polling. client.solve(task) - .then((solution) => console.log(solution)) - .catch(console.error); + .then((solution) => { + // STEP-04: Print only the useful field returned for this CAPTCHA type. + console.log(solution); + }) + .catch((error) => { + // Report SDK or transport failures without hiding the rejected Promise. + console.error(error); + }); diff --git a/examples/turnstile.js b/examples/turnstile.js index ad66730..484b8c6 100644 --- a/examples/turnstile.js +++ b/examples/turnstile.js @@ -1,12 +1,37 @@ import 'dotenv/config'; import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; +/** + * Solve Cloudflare Turnstile without a proxy. + * It creates Tasks.TurnstileProxyless from the shown parameters, submits it with + * CaptchaClient.solve(), and prints the relevant returned value. Applying that value to a + * target page is site-specific. Replace all target-specific placeholders before running. + * + * How it works: + * STEP-01 - Configure the SDK client. + * STEP-02 - Create the CAPTCHA task from the required parameters or local assets. + * STEP-03 - Submit the task and wait for CaptchaClient.solve() to return the solution. + * STEP-04 - Print the relevant solution value or report an error. + */ + + +// STEP-01: Configure the SDK client with the API key. const client = new CaptchaClient({ clientKey: process.env.CAPTCHA_API_KEY || 'YOUR_API_KEY' }); + +// STEP-02: Create the CAPTCHA task with the values required by this challenge. const task = new Tasks.TurnstileProxyless({ websiteURL: 'https://example.com/login', websiteKey: 'YOUR_WEBSITE_KEY' }); + +// STEP-03: Submit the task; solve() handles task creation and polling. client.solve(task) - .then((solution) => console.log(solution.token)) - .catch(console.error); + .then((solution) => { + // STEP-04: Print only the useful field returned for this CAPTCHA type. + console.log(solution.token); + }) + .catch((error) => { + // Report SDK or transport failures without hiding the rejected Promise. + console.error(error); + }); diff --git a/examples/turnstile_proxy.js b/examples/turnstile_proxy.js index 31fb852..f590312 100644 --- a/examples/turnstile_proxy.js +++ b/examples/turnstile_proxy.js @@ -1,7 +1,24 @@ import 'dotenv/config'; import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; +/** + * Solve Cloudflare Turnstile through a customer proxy. + * It creates Tasks.Turnstile from the shown parameters, submits it with + * CaptchaClient.solve(), and prints the relevant returned value. Applying that value to a + * target page is site-specific. Replace all target-specific placeholders before running. + * + * How it works: + * STEP-01 - Configure the SDK client. + * STEP-02 - Create the CAPTCHA task from the required parameters or local assets. + * STEP-03 - Submit the task and wait for CaptchaClient.solve() to return the solution. + * STEP-04 - Print the relevant solution value or report an error. + */ + + +// STEP-01: Configure the SDK client with the API key. const client = new CaptchaClient({ clientKey: process.env.CAPTCHA_API_KEY || 'YOUR_API_KEY' }); + +// STEP-02: Create the CAPTCHA task with the values required by this challenge. const task = new Tasks.Turnstile({ websiteURL: 'https://example.com/login', websiteKey: 'YOUR_WEBSITE_KEY', @@ -10,6 +27,14 @@ const task = new Tasks.Turnstile({ proxyPort: 8080 }); + +// STEP-03: Submit the task; solve() handles task creation and polling. client.solve(task) - .then((solution) => console.log(solution.token)) - .catch(console.error); + .then((solution) => { + // STEP-04: Print only the useful field returned for this CAPTCHA type. + console.log(solution.token); + }) + .catch((error) => { + // Report SDK or transport failures without hiding the rejected Promise. + console.error(error); + }); diff --git a/examples/yandex_smartcaptcha.js b/examples/yandex_smartcaptcha.js index 3397175..84b509e 100644 --- a/examples/yandex_smartcaptcha.js +++ b/examples/yandex_smartcaptcha.js @@ -1,12 +1,37 @@ import 'dotenv/config'; import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; +/** + * Solve Yandex SmartCaptcha without a proxy. + * It creates Tasks.YandexSmartCaptchaTaskProxyless from the shown parameters, submits it with + * CaptchaClient.solve(), and prints the relevant returned value. Applying that value to a + * target page is site-specific. Replace all target-specific placeholders before running. + * + * How it works: + * STEP-01 - Configure the SDK client. + * STEP-02 - Create the CAPTCHA task from the required parameters or local assets. + * STEP-03 - Submit the task and wait for CaptchaClient.solve() to return the solution. + * STEP-04 - Print the relevant solution value or report an error. + */ + + +// STEP-01: Configure the SDK client with the API key. const client = new CaptchaClient({ clientKey: process.env.CAPTCHA_API_KEY || 'YOUR_API_KEY' }); + +// STEP-02: Create the CAPTCHA task with the values required by this challenge. const task = new Tasks.YandexSmartCaptchaTaskProxyless({ websiteURL: 'https://example.com/login', websiteKey: 'YOUR_WEBSITE_KEY' }); + +// STEP-03: Submit the task; solve() handles task creation and polling. client.solve(task) - .then((solution) => console.log(solution.token)) - .catch(console.error); + .then((solution) => { + // STEP-04: Print only the useful field returned for this CAPTCHA type. + console.log(solution.token); + }) + .catch((error) => { + // Report SDK or transport failures without hiding the rejected Promise. + console.error(error); + }); diff --git a/examples/yandex_smartcaptcha_image.js b/examples/yandex_smartcaptcha_image.js index 714063a..bc318c8 100644 --- a/examples/yandex_smartcaptcha_image.js +++ b/examples/yandex_smartcaptcha_image.js @@ -2,12 +2,37 @@ import 'dotenv/config'; import fs from 'fs'; import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; +/** + * Solve a Yandex SmartCaptcha image challenge from local assets. + * It creates Tasks.YandexSmartCaptchaImageTask from the shown parameters, submits it with + * CaptchaClient.solve(), and prints the relevant returned value. Applying that value to a + * target page is site-specific. Replace all target-specific placeholders before running. + * + * How it works: + * STEP-01 - Configure the SDK client. + * STEP-02 - Create the CAPTCHA task from the required parameters or local assets. + * STEP-03 - Submit the task and wait for CaptchaClient.solve() to return the solution. + * STEP-04 - Print the relevant solution value or report an error. + */ + + +// STEP-01: Configure the SDK client with the API key. const client = new CaptchaClient({ clientKey: process.env.CAPTCHA_API_KEY || 'YOUR_API_KEY' }); + +// STEP-02: Create the CAPTCHA task with the values required by this challenge. const task = new Tasks.YandexSmartCaptchaImageTask({ image: fs.readFileSync(new URL('./assets/yandex-smartcaptcha-image.png', import.meta.url)).toString('base64'), imgInstructions: fs.readFileSync(new URL('./assets/yandex-smartcaptcha-instructions.png', import.meta.url)).toString('base64') }); + +// STEP-03: Submit the task; solve() handles task creation and polling. client.solve(task) - .then((solution) => console.log(solution.coordinates)) - .catch(console.error); + .then((solution) => { + // STEP-04: Print only the useful field returned for this CAPTCHA type. + console.log(solution.coordinates); + }) + .catch((error) => { + // Report SDK or transport failures without hiding the rejected Promise. + console.error(error); + }); diff --git a/examples/yandex_smartcaptcha_kaleidoscope.js b/examples/yandex_smartcaptcha_kaleidoscope.js index 41ef64d..2d0a282 100644 --- a/examples/yandex_smartcaptcha_kaleidoscope.js +++ b/examples/yandex_smartcaptcha_kaleidoscope.js @@ -2,10 +2,24 @@ import 'dotenv/config'; import fs from 'node:fs'; import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; +/** + * Solve a Yandex SmartCaptcha Kaleidoscope puzzle from a local image. + * It creates Tasks.YandexSmartCaptchaKaleidoscopeTask from the shown parameters, submits it with + * CaptchaClient.solve(), and prints the relevant returned value. Applying that value to a + * target page is site-specific. Replace all target-specific placeholders before running. + * + * How it works: + * STEP-01 - Configure the SDK client. + * STEP-02 - Create the CAPTCHA task from the required parameters or local assets. + * STEP-03 - Submit the task and wait for CaptchaClient.solve() to return the solution. + * STEP-04 - Print the solution as formatted JSON or report an error. + */ + if (!process.env.CAPTCHA_API_KEY) { throw new Error('Set CAPTCHA_API_KEY in .env or in the current shell before running this example.'); } +// STEP-01: Configure the SDK client with the API key. const captchaSolver = new CaptchaClient({ clientKey: process.env.CAPTCHA_API_KEY }); @@ -13,13 +27,19 @@ const image = fs.readFileSync( new URL('./assets/yandex-smartcaptcha-kaleidoscope.jpg', import.meta.url) ).toString('base64'); +// STEP-02: Create the CAPTCHA task with the values required by this challenge. const task = new Tasks.YandexSmartCaptchaKaleidoscopeTask({ image, task: '[7,15,14,0,11,6,6,0,11,15,6,10,1,14,3,12,9,0,15,1,5,1,8,11,12,11,0,12,1,10,1,4,14,6,10,6,10,8,3,0,5,9,7,8,0,3,8,0,9,12,12,11,3,0,8,10]' }); +// STEP-03: Submit the task; solve() handles task creation and polling. captchaSolver.solve(task) .then((clicks) => { - console.log('Captcha solved. Slider arrow clicks:', clicks); + // STEP-04: Print a structured response that can be copied or parsed as JSON. + console.log(JSON.stringify({ clicks }, null, 2)); }) - .catch(console.error); + .catch((error) => { + // Report SDK or transport failures without hiding the rejected Promise. + console.error(error); + }); diff --git a/examples/yandex_smartcaptcha_proxy.js b/examples/yandex_smartcaptcha_proxy.js index c3250d6..fc12f99 100644 --- a/examples/yandex_smartcaptcha_proxy.js +++ b/examples/yandex_smartcaptcha_proxy.js @@ -1,7 +1,24 @@ import 'dotenv/config'; import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk'; +/** + * Solve Yandex SmartCaptcha through a customer proxy. + * It creates Tasks.YandexSmartCaptchaTask from the shown parameters, submits it with + * CaptchaClient.solve(), and prints the relevant returned value. Applying that value to a + * target page is site-specific. Replace all target-specific placeholders before running. + * + * How it works: + * STEP-01 - Configure the SDK client. + * STEP-02 - Create the CAPTCHA task from the required parameters or local assets. + * STEP-03 - Submit the task and wait for CaptchaClient.solve() to return the solution. + * STEP-04 - Print the relevant solution value or report an error. + */ + + +// STEP-01: Configure the SDK client with the API key. const client = new CaptchaClient({ clientKey: process.env.CAPTCHA_API_KEY || 'YOUR_API_KEY' }); + +// STEP-02: Create the CAPTCHA task with the values required by this challenge. const task = new Tasks.YandexSmartCaptchaTask({ websiteURL: 'https://example.com/login', websiteKey: 'YOUR_WEBSITE_KEY', @@ -10,6 +27,14 @@ const task = new Tasks.YandexSmartCaptchaTask({ proxyPort: 8080 }); + +// STEP-03: Submit the task; solve() handles task creation and polling. client.solve(task) - .then((solution) => console.log(solution.token)) - .catch(console.error); + .then((solution) => { + // STEP-04: Print only the useful field returned for this CAPTCHA type. + console.log(solution.token); + }) + .catch((error) => { + // Report SDK or transport failures without hiding the rejected Promise. + console.error(error); + }); diff --git a/src/client.ts b/src/client.ts index 3039fe1..09c9e05 100644 --- a/src/client.ts +++ b/src/client.ts @@ -2,6 +2,56 @@ import { ApiError, NetworkError, TimeoutError, ValidationError } from './excepti import { __version__ } from './version.js'; import type { BaseTask } from './tasks.js'; +const MAX_DEBUG_STRING_LENGTH = 200; +const DEBUG_STRING_EDGE_LENGTH = 40; +const MASKED_DEBUG_FIELDS = /^(authorization|clientKey|cookie|cookies|password|proxyAddress|proxyLogin|proxyPassword)$/i; +/** Task fields that carry base64 images; their content is never useful in a log. */ +const BASE64_DEBUG_FIELDS = /^(body|image|imgInstructions)$/; + +/** Format a moment as local time with milliseconds and UTC offset: `2026-11-12 14:03:21.512 +03:00`. */ +function formatDebugTimestamp(date: Date): string { + const pad = (value: number, length = 2) => String(value).padStart(length, '0'); + const offsetMinutes = -date.getTimezoneOffset(); + const sign = offsetMinutes >= 0 ? '+' : '-'; + const absOffset = Math.abs(offsetMinutes); + return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ` + + `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}.${pad(date.getMilliseconds(), 3)} ` + + `${sign}${pad(Math.floor(absOffset / 60))}:${pad(absOffset % 60)}`; +} + +/** Describe a single error: name, `code` when present (e.g. undici `UND_ERR_CONNECT_TIMEOUT`) and message. */ +function describeSingleDebugError(error: unknown): string { + if (error instanceof ApiError) return `${error.name} ${error.errorCode}: ${error.errorDescription}`; + if (error instanceof Error) { + const code = 'code' in error && typeof error.code === 'string' ? ` ${error.code}` : ''; + return `${error.name}${code}: ${error.message}`; + } + return String(error); +} + +/** + * Describe an error in one line, following `originalError` / `cause` links. + * `fetch` reports every transport failure as a bare `TypeError: fetch failed`; + * the actual reason (DNS, connect timeout, TLS) is only in its `cause`. + */ +function describeDebugError(error: unknown): string { + const parts: string[] = []; + let current: unknown = error; + for (let depth = 0; current !== undefined && current !== null && depth < 4; depth += 1) { + const description = describeSingleDebugError(current); + // NetworkError copies the message of the error it wraps; skip the duplicate link. + if (!(depth === 1 && error instanceof NetworkError && current instanceof Error && current.message === error.message)) parts.push(description); + current = current instanceof NetworkError ? current.originalError : (current as { cause?: unknown }).cause; + } + return parts.join(' <- '); +} + +/** One part of a debug event below its line: an optional title and a JSON value. */ +interface DebugSection { + title?: string; + value?: unknown; +} + /** Options accepted by the {@link CaptchaClient} constructor. */ export interface CaptchaClientOptions { /** Your Captcha Solver API key. Required. */ @@ -24,6 +74,15 @@ export interface CaptchaClientOptions { * @defaultValue `5000` */ pollingInterval?: number; + /** + * Print one timestamped `console.debug` line per API request plus a final + * {@link CaptchaClient.solve} summary. Request and response bodies are added + * for task creation, errors and solved tasks; routine `processing` polls stay + * on one line. Credentials are masked, base64 images are replaced by their + * length and other long strings such as solution tokens are shortened. + * @defaultValue `false` + */ + debug?: boolean; } /** Raw response of `/getTaskResult` (and, structurally, of every other API endpoint). */ @@ -72,14 +131,64 @@ export class CaptchaClient { timeout: number; /** Delay between polls inside {@link solve}, in milliseconds. */ pollingInterval: number; + /** Whether lifecycle debug logging is enabled. */ + debug: boolean; /** * @param options - Client options; only `clientKey` is required. * @throws {ValidationError} If `clientKey` is empty. */ - constructor({ clientKey, baseUrl = 'https://api.captcha-solver.com', timeout = 120000, pollingInterval = 5000 }: CaptchaClientOptions = {} as CaptchaClientOptions) { + constructor({ clientKey, baseUrl = 'https://api.captcha-solver.com', timeout = 120000, pollingInterval = 5000, debug = false }: CaptchaClientOptions = {} as CaptchaClientOptions) { if (!clientKey) throw new ValidationError('clientKey is required'); - this.clientKey = clientKey; this.baseUrl = baseUrl; this.timeout = timeout; this.pollingInterval = pollingInterval; + this.clientKey = clientKey; this.baseUrl = baseUrl; this.timeout = timeout; this.pollingInterval = pollingInterval; this.debug = debug; + this._debug(`client initialized sdk=javascript-sdk/${__version__} baseUrl=${baseUrl} timeout=${timeout}ms pollingInterval=${pollingInterval}ms`); + } + + /** + * Copy a value for debug output while keeping logs readable and safe to share. + * Credential fields are masked, base64 image fields are reduced to their + * length, and other long strings keep their edges so tokens stay comparable. + */ + private _sanitizeForDebug(value: unknown, fieldName?: string): unknown { + if (fieldName && MASKED_DEBUG_FIELDS.test(fieldName)) return '[MASKED]'; + if (typeof value === 'string' && fieldName && BASE64_DEBUG_FIELDS.test(fieldName)) return `[base64, ${value.length} chars]`; + if (typeof value === 'string' && value.length > MAX_DEBUG_STRING_LENGTH) { + return `${value.slice(0, DEBUG_STRING_EDGE_LENGTH)}...[${value.length} chars]...${value.slice(-DEBUG_STRING_EDGE_LENGTH)}`; + } + if (Array.isArray(value)) return value.map((item) => this._sanitizeForDebug(item)); + if (value && typeof value === 'object') { + return Object.fromEntries( + Object.entries(value).map(([key, item]) => [key, this._sanitizeForDebug(item, key)]) + ); + } + return value; + } + + /** + * Write one debug event: a timestamped line, optionally followed by titled + * sections such as `REQUEST (POST ):` and `RESPONSE (HTTP 200 OK):`, each with a + * sanitized JSON value. Everything goes through a single `console.debug` + * call so the sections cannot be separated from their line. + */ + private _debug(message: string, sections: DebugSection[] = []): void { + if (!this.debug) return; + this._ignoreDebugFailure(() => { + const lines = [`[${formatDebugTimestamp(new Date())}] [CaptchaClient] ${message}`]; + for (const { title, value } of sections) { + if (title) lines.push(value === undefined ? title : `${title}:`); + if (value !== undefined) lines.push(JSON.stringify(this._sanitizeForDebug(value), null, 2)); + } + console.debug(lines.join('\n')); + }); + } + + /** + * Run debug-only code so that it can never change what the caller gets: + * a failure while building or printing a debug event (e.g. a replaced + * `console.debug` that throws) is swallowed instead of failing the request. + */ + private _ignoreDebugFailure(write: () => void): void { + try { write(); } catch { /* debug output must not affect the request */ } } /** @@ -97,19 +206,81 @@ export class CaptchaClient { */ protected async _request(endpoint: string, payload: Record): Promise { const controller = new AbortController(); const timer = setTimeout(() => controller.abort(), this.timeout); + const startedAt = Date.now(); + const headers = { 'Content-Type': 'application/json', Accept: 'application/json', 'X-SDK': `javascript-sdk/${__version__}` }; + let httpStatus: string | undefined; + let bodyNotJson = false; + let data: (TaskResult & { errorCode?: string; errorDescription?: string; error?: string }) | undefined; try { - const response = await fetch(`${this.baseUrl}${endpoint}`, { method: 'POST', headers: { 'Content-Type': 'application/json', Accept: 'application/json', 'X-SDK': `javascript-sdk/${__version__}` }, body: JSON.stringify(payload), signal: controller.signal }); + const response = await fetch(`${this.baseUrl}${endpoint}`, { method: 'POST', headers, body: JSON.stringify(payload), signal: controller.signal }); + httpStatus = `${response.status} ${response.statusText ?? ''}`.trim(); + try { + data = await response.json() as typeof data; + } catch (parseError) { + // A SyntaxError means the body arrived but is not JSON; anything else (e.g. AbortError + // on timeout) means the body never fully arrived. + bodyNotJson = parseError instanceof SyntaxError; + if (!response.ok) throw new NetworkError(`HTTP error: ${response.status} ${response.statusText}`); + throw parseError; + } if (!response.ok) throw new NetworkError(`HTTP error: ${response.status} ${response.statusText}`); - const data = await response.json() as TaskResult & { errorCode?: string; errorDescription?: string; error?: string }; - if (data.errorId !== 0) throw new ApiError(data.errorCode || 'UNKNOWN_ERROR', data.errorDescription || data.error || 'Unknown API error'); - return data; + if (data!.errorId !== 0) throw new ApiError(data!.errorCode || 'UNKNOWN_ERROR', data!.errorDescription || data!.error || 'Unknown API error'); + this._ignoreDebugFailure(() => this._debugExchange(endpoint, payload, startedAt, { httpStatus, response: data })); + return data!; } catch (error) { - if (error instanceof ApiError || error instanceof NetworkError) throw error; - if (error && typeof error === 'object' && 'name' in error && error.name === 'AbortError') throw new TimeoutError(`Request timed out after ${this.timeout}ms`); - throw new NetworkError(error instanceof Error ? error.message : String(error), error); + let failure: unknown = error; + if (!(error instanceof ApiError || error instanceof NetworkError)) { + failure = error && typeof error === 'object' && 'name' in error && error.name === 'AbortError' + ? new TimeoutError(`Request timed out after ${this.timeout}ms`) + : new NetworkError(error instanceof Error ? error.message : String(error), error); + } + this._ignoreDebugFailure(() => this._debugExchange(endpoint, payload, startedAt, { error: failure, httpStatus, response: data, bodyNotJson })); + throw failure; } finally { clearTimeout(timer); } } + /** + * Log one API exchange. The line names the endpoint, task type or task ID, + * outcome and duration. Below it come `REQUEST (POST ):` (the body sent, + * credentials masked) and `RESPONSE (HTTP ...):` (the server body as + * received); both are skipped for routine `processing` polls so long waits + * stay readable. + */ + private _debugExchange(endpoint: string, payload: Record, startedAt: number, outcome: { response?: TaskResult; error?: unknown; httpStatus?: string; bodyNotJson?: boolean }): void { + if (!this.debug) return; + const task = payload.task as Record | undefined; + const label = [ + endpoint.replace(/^\//, ''), + typeof task?.type === 'string' ? task.type : null, + payload.taskId !== undefined ? `taskId=${payload.taskId}` : null + ].filter(Boolean).join(' '); + const durationMs = Date.now() - startedAt; + const { response, error, httpStatus, bodyNotJson } = outcome; + const errorName = error instanceof Error ? error.name : 'Error'; + + const sections: DebugSection[] = [{ title: `REQUEST (POST ${this.baseUrl}${endpoint})`, value: payload }]; + // httpStatus is set only once the server answered; without it the request failed in transit, + // and an explicit "none" line keeps every REQUEST paired with a RESPONSE. + if (!httpStatus) { + sections.push({ title: `RESPONSE: none - no response from the server (${errorName}, ${durationMs}ms)` }); + } else if (response !== undefined) { + sections.push({ title: `RESPONSE (HTTP ${httpStatus}, ${durationMs}ms)`, value: response }); + } else if (bodyNotJson) { + sections.push({ title: `RESPONSE (HTTP ${httpStatus}, ${durationMs}ms): body is not valid JSON` }); + } else { + sections.push({ title: `RESPONSE (HTTP ${httpStatus}, ${durationMs}ms): body was not received (${errorName})` }); + } + + if (error === undefined) { + const result = response?.status + ?? (response?.taskId !== undefined ? `taskId=${response.taskId}` : undefined) + ?? (response?.balance !== undefined ? `balance=${response.balance}` : 'ok'); + this._debug(`${label} -> ${result} (${durationMs}ms)`, response?.status === 'processing' ? [] : sections); + return; + } + this._debug(`${label} -> failed: ${describeDebugError(error)} (${durationMs}ms)`, sections); + } + /** * Submit a task and return its ID without waiting for the solution. * @@ -190,12 +361,52 @@ export class CaptchaClient { * ``` */ async solve>(task: T, languagePool: string | null = null): Promise> { - const taskId = await this.createTask(task, languagePool); const startedAt = Date.now(); - while (true) { - const remaining = this.timeout - (Date.now() - startedAt); if (remaining <= 0) throw new TimeoutError(`Task ${taskId} timed out after ${this.timeout}ms`); - await new Promise(resolve => setTimeout(resolve, Math.min(this.pollingInterval, remaining))); - if (Date.now() - startedAt >= this.timeout) throw new TimeoutError(`Task ${taskId} timed out after ${this.timeout}ms`); - const result = await this.getTaskResult(taskId); if (result.status === 'ready') return (result.solution ?? {}) as SolutionOf; + const startedAt = Date.now(); + let taskId: number | null = null; + let polls = 0; + try { + taskId = await this.createTask(task, languagePool); + while (true) { + const remaining = this.timeout - (Date.now() - startedAt); if (remaining <= 0) throw new TimeoutError(`Task ${taskId} timed out after ${this.timeout}ms`); + await new Promise(resolve => setTimeout(resolve, Math.min(this.pollingInterval, remaining))); + if (Date.now() - startedAt >= this.timeout) throw new TimeoutError(`Task ${taskId} timed out after ${this.timeout}ms`); + polls += 1; + const result = await this.getTaskResult(taskId); + if (result.status === 'ready') { + this._ignoreDebugFailure(() => this._debugSolveSummary(task, startedAt, { status: 'solved', taskId, polls, result })); + return (result.solution ?? {}) as SolutionOf; + } + } + } catch (error) { + this._ignoreDebugFailure(() => this._debugSolveSummary(task, startedAt, { status: 'not solved', taskId, polls, error })); + throw error; } } + + /** + * Log the final {@link solve} outcome. `serverSolveTime` comes from the API's + * `createTime` / `endTime` and shows how much of the total wait was spent + * solving versus creating the task and waiting between polls. + */ + private _debugSolveSummary(task: BaseTask, startedAt: number, outcome: { status: 'solved' | 'not solved'; taskId: number | null; polls: number; result?: TaskResult; error?: unknown }): void { + if (!this.debug) return; + const { status, taskId, polls, result, error } = outcome; + let taskType: unknown; + try { taskType = task.toDict().type; } catch { taskType = undefined; } + const createTime = result?.createTime; const endTime = result?.endTime; + const fields: Array<[string, string] | null> = [ + ['status', status], + ['taskId', taskId === null ? '- (task was not created)' : String(taskId)], + typeof taskType === 'string' ? ['taskType', taskType] : null, + ['elapsed', `${((Date.now() - startedAt) / 1000).toFixed(3)}s`], + typeof createTime === 'number' && typeof endTime === 'number' ? ['serverSolveTime', `${endTime - createTime}s`] : null, + ['polls', String(polls)], + error !== undefined ? ['error', describeDebugError(error)] : null + ]; + const present = fields.filter((field): field is [string, string] => field !== null); + const width = Math.max(...present.map(([name]) => name.length)) + 1; + // One aligned "name: value" line per field; line breaks inside a value are flattened. + const lines = present.map(([name, value]) => ` ${`${name}:`.padEnd(width)} ${value.replace(/\s*\n\s*/g, ' ')}`); + this._debug(`SOLVE SUMMARY:\n${lines.join('\n')}`); + } } diff --git a/tests/unit/async/client.test.js b/tests/unit/async/client.test.js index a612f53..4445415 100644 --- a/tests/unit/async/client.test.js +++ b/tests/unit/async/client.test.js @@ -39,6 +39,278 @@ describe('CaptchaClient (async)', () => { expect(requestOptions.headers['X-SDK']).toBe('javascript-sdk/1.1.0'); }); + describe('debug mode', () => { + const TIMESTAMP = /^\[\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3} [+-]\d{2}:\d{2}\] \[CaptchaClient\] /; + let debug; + const okResponse = (body) => Promise.resolve({ ok: true, status: 200, statusText: 'OK', json: () => Promise.resolve(body) }); + const logs = () => debug.mock.calls.map(([message]) => message); + const messageOf = (text) => logs().find((message) => message.split('\n')[0].includes(text)); + const lineOf = (text) => messageOf(text)?.split('\n')[0]; + // Split the lines below an event into titled sections ("REQUEST (POST )", "RESPONSE (HTTP 200 OK)"); + // the variable ", ms" duration is dropped from titles so tests can use fixed keys. + const sectionsOf = (text) => { + const sections = {}; + let title = ''; + for (const line of messageOf(text).split('\n').slice(1)) { + if (/^[A-Z]/.test(line)) { title = line.replace(/:$/, '').replace(/, \d+ms\)/, ')'); sections[title] = ''; } + else sections[title] = (sections[title] ?? '') + line + '\n'; + } + return Object.fromEntries(Object.entries(sections).map(([key, json]) => [key, json ? JSON.parse(json) : undefined])); + }; + // Parse the " name: value" lines below SOLVE SUMMARY into an object. + const summaryOf = () => Object.fromEntries(messageOf('SOLVE SUMMARY:').split('\n').slice(1).map((line) => { + const [, name, value] = line.match(/^ {2}(\w+): +(.*)$/); + return [name, value]; + })); + const recaptchaTask = () => new Tasks.RecaptchaV2Proxyless({ websiteURL: 'https://example.com', websiteKey: 'website_key' }); + + beforeEach(() => { + debug = jest.spyOn(console, 'debug').mockImplementation(() => {}); + }); + + afterEach(() => { + debug.mockRestore(); + }); + + test('is silent by default', async () => { + global.fetch = jest.fn(() => okResponse({ errorId: 0, balance: '1.00' })); + + await client.getBalance(); + + expect(debug).not.toHaveBeenCalled(); + }); + + test('prefixes every event with a local timestamp and UTC offset, in one console call each', async () => { + client = new CaptchaClient({ clientKey: 'secret_key', debug: true }); + global.fetch = jest.fn(() => okResponse({ errorId: 0, balance: '1.00' })); + + await client.getBalance(); + + expect(logs().length).toBeGreaterThan(0); + for (const message of logs()) expect(message).toMatch(TIMESTAMP); + for (const call of debug.mock.calls) expect(call).toHaveLength(1); + expect(lineOf('client initialized')).toContain('sdk=javascript-sdk/1.1.0 baseUrl=https://api.captcha-solver.com timeout=120000ms pollingInterval=5000ms'); + expect(lineOf('getBalance')).toMatch(/getBalance -> balance=1\.00 \(\d+ms\)$/); + expect(sectionsOf('getBalance')).toEqual({ + 'REQUEST (POST https://api.captcha-solver.com/getBalance)': { clientKey: '[MASKED]' }, + 'RESPONSE (HTTP 200 OK)': { errorId: 0, balance: '1.00' } + }); + expect(JSON.stringify(debug.mock.calls)).not.toContain('secret_key'); + }); + + test('keeps processing polls on one line and logs bodies for creation and the ready result', async () => { + client = new CaptchaClient({ clientKey: 'secret_key', debug: true, pollingInterval: 1 }); + global.fetch = jest.fn() + .mockImplementationOnce(() => okResponse({ errorId: 0, taskId: 12345 })) + .mockImplementationOnce(() => okResponse({ errorId: 0, status: 'processing' })) + .mockImplementationOnce(() => okResponse({ + errorId: 0, status: 'ready', solution: { token: `start-${'x'.repeat(300)}-end` }, createTime: 100, endTime: 108 + })); + + await client.solve(recaptchaTask()); + + expect(lineOf('createTask')).toMatch(/createTask RecaptchaV2TaskProxyless -> taskId=12345 \(\d+ms\)$/); + expect(sectionsOf('createTask')).toEqual({ + 'REQUEST (POST https://api.captcha-solver.com/createTask)': { clientKey: '[MASKED]', task: { type: 'RecaptchaV2TaskProxyless', websiteURL: 'https://example.com', websiteKey: 'website_key' } }, + 'RESPONSE (HTTP 200 OK)': { errorId: 0, taskId: 12345 } + }); + const processing = messageOf('-> processing'); + expect(processing).toMatch(/getTaskResult taskId=12345 -> processing \(\d+ms\)$/); + expect(processing).not.toContain('\n'); + expect(lineOf('-> ready')).toMatch(/getTaskResult taskId=12345 -> ready \(\d+ms\)$/); + expect(sectionsOf('-> ready')['REQUEST (POST https://api.captcha-solver.com/getTaskResult)']).toEqual({ clientKey: '[MASKED]', taskId: 12345 }); + expect(sectionsOf('-> ready')['RESPONSE (HTTP 200 OK)'].solution.token).toMatch(/^start-x+\.\.\.\[310 chars\]\.\.\.x+-end$/); + expect(summaryOf()).toEqual({ + status: 'solved', + taskId: '12345', + taskType: 'RecaptchaV2TaskProxyless', + elapsed: expect.stringMatching(/^\d+\.\d{3}s$/), + serverSolveTime: '8s', + polls: '2' + }); + expect(JSON.stringify(debug.mock.calls)).not.toContain('secret_key'); + }); + + test('replaces base64 image fields with their length', async () => { + client = new CaptchaClient({ clientKey: 'secret_key', debug: true }); + global.fetch = jest.fn(() => okResponse({ errorId: 0, taskId: 1 })); + + await client.createTask(new Tasks.ImageToText({ body: 'A'.repeat(1000) })); + + expect(sectionsOf('createTask')['REQUEST (POST https://api.captcha-solver.com/createTask)'].task.body).toBe('[base64, 1000 chars]'); + }); + + test('masks proxy address and credentials', async () => { + client = new CaptchaClient({ clientKey: 'secret_key', debug: true }); + global.fetch = jest.fn(() => okResponse({ errorId: 0, taskId: 1 })); + + await client.createTask(new Tasks.Turnstile({ + websiteURL: 'https://example.com', + websiteKey: 'website_key', + proxyType: 'http', + proxyAddress: '203.0.113.7', + proxyPort: 8080, + proxyLogin: 'proxy_user', + proxyPassword: 'proxy_pass' + })); + + const { task } = sectionsOf('createTask')['REQUEST (POST https://api.captcha-solver.com/createTask)']; + expect(task).toMatchObject({ proxyAddress: '[MASKED]', proxyPort: 8080, proxyLogin: '[MASKED]', proxyPassword: '[MASKED]' }); + const logged = JSON.stringify(debug.mock.calls); + for (const secret of ['203.0.113.7', 'proxy_user', 'proxy_pass', 'secret_key']) expect(logged).not.toContain(secret); + }); + + test('logs the API error response and adds the error to a not-solved summary', async () => { + client = new CaptchaClient({ clientKey: 'secret_key', debug: true, pollingInterval: 1 }); + global.fetch = jest.fn() + .mockImplementationOnce(() => okResponse({ errorId: 0, taskId: 12345 })) + .mockImplementationOnce(() => okResponse({ errorId: 1, errorCode: 'ERROR_TASK_FAILED', errorDescription: 'Task failed' })); + + await expect(client.solve(recaptchaTask())).rejects.toThrow(ApiError); + + expect(lineOf('getTaskResult')).toMatch(/getTaskResult taskId=12345 -> failed: ApiError ERROR_TASK_FAILED: Task failed \(\d+ms\)$/); + expect(sectionsOf('getTaskResult')).toEqual({ + 'REQUEST (POST https://api.captcha-solver.com/getTaskResult)': { clientKey: '[MASKED]', taskId: 12345 }, + 'RESPONSE (HTTP 200 OK)': { errorId: 1, errorCode: 'ERROR_TASK_FAILED', errorDescription: 'Task failed' } + }); + expect(summaryOf()).toEqual({ + status: 'not solved', + taskId: '12345', + taskType: 'RecaptchaV2TaskProxyless', + elapsed: expect.stringMatching(/^\d+\.\d{3}s$/), + polls: '1', + error: 'ApiError ERROR_TASK_FAILED: Task failed' + }); + }); + + test('says the task was not created when createTask fails inside solve()', async () => { + client = new CaptchaClient({ clientKey: 'secret_key', debug: true }); + global.fetch = jest.fn(() => okResponse({ errorId: 1, errorCode: 'ERROR_KEY_DOES_NOT_EXIST', errorDescription: 'Key not found' })); + + await expect(client.solve(recaptchaTask())).rejects.toThrow(ApiError); + + expect(summaryOf()).toMatchObject({ + status: 'not solved', + taskId: '- (task was not created)', + polls: '0', + error: 'ApiError ERROR_KEY_DOES_NOT_EXIST: Key not found' + }); + }); + + test('includes the transport cause hidden behind "fetch failed"', async () => { + client = new CaptchaClient({ clientKey: 'secret_key', debug: true }); + const cause = Object.assign(new Error('Connect Timeout Error (attempted address: api.captcha-solver.com:443, timeout: 10000ms)'), { + name: 'ConnectTimeoutError', + code: 'UND_ERR_CONNECT_TIMEOUT' + }); + global.fetch = jest.fn(() => Promise.reject(new TypeError('fetch failed', { cause }))); + + await expect(client.getBalance()).rejects.toThrow(NetworkError); + + expect(lineOf('getBalance')).toContain( + 'failed: NetworkError: fetch failed <- ConnectTimeoutError UND_ERR_CONNECT_TIMEOUT: Connect Timeout Error (attempted address: api.captcha-solver.com:443, timeout: 10000ms)' + ); + expect(messageOf('getBalance').split('\n').at(-1)).toMatch(/^RESPONSE: none - no response from the server \(NetworkError, \d+ms\)$/); + }); + + test('logs the JSON body of a non-2xx HTTP response', async () => { + client = new CaptchaClient({ clientKey: 'secret_key', debug: true, baseUrl: 'https://api.captcha-solver.com/no-such-path' }); + global.fetch = jest.fn(() => Promise.resolve({ + ok: false, + status: 404, + statusText: 'Not Found', + json: () => Promise.resolve({ message: 'The route could not be found.' }) + })); + + await expect(client.getBalance()).rejects.toThrow(NetworkError); + + expect(lineOf('getBalance')).toMatch(/getBalance -> failed: NetworkError: HTTP error: 404 Not Found \(\d+ms\)$/); + expect(sectionsOf('getBalance')).toEqual({ + 'REQUEST (POST https://api.captcha-solver.com/no-such-path/getBalance)': { clientKey: '[MASKED]' }, + 'RESPONSE (HTTP 404 Not Found)': { message: 'The route could not be found.' } + }); + }); + + test('says when the response body is not valid JSON', async () => { + client = new CaptchaClient({ clientKey: 'secret_key', debug: true }); + global.fetch = jest.fn(() => Promise.resolve({ + ok: false, + status: 502, + statusText: 'Bad Gateway', + json: () => Promise.reject(new SyntaxError('Unexpected token < in JSON')) + })); + + await expect(client.getBalance()).rejects.toThrow(NetworkError); + + expect(lineOf('getBalance')).toMatch(/getBalance -> failed: NetworkError: HTTP error: 502 Bad Gateway \(\d+ms\)$/); + expect(messageOf('getBalance').split('\n').at(-1)).toMatch(/^RESPONSE \(HTTP 502 Bad Gateway, \d+ms\): body is not valid JSON$/); + }); + + test('a failing debug output never changes what the caller gets', async () => { + debug.mockImplementation(() => { throw new Error('console is broken'); }); + client = new CaptchaClient({ clientKey: 'secret_key', debug: true, pollingInterval: 1 }); + global.fetch = jest.fn() + .mockImplementationOnce(() => okResponse({ errorId: 0, taskId: 12345 })) + .mockImplementationOnce(() => okResponse({ errorId: 0, status: 'ready', solution: { gRecaptchaResponse: 'token' } })) + .mockImplementationOnce(() => okResponse({ errorId: 1, errorCode: 'ERROR_KEY_DOES_NOT_EXIST', errorDescription: 'Key not found' })); + + await expect(client.solve(recaptchaTask())).resolves.toEqual({ gRecaptchaResponse: 'token' }); + const error = await client.getBalance().catch((e) => e); + expect(error).toBeInstanceOf(ApiError); + expect(error.errorCode).toBe('ERROR_KEY_DOES_NOT_EXIST'); + expect(debug).toHaveBeenCalled(); + }); + + test('says the body was not received when the timeout hits while reading it', async () => { + client = new CaptchaClient({ clientKey: 'secret_key', debug: true, timeout: 20 }); + // Headers arrive at once; the body only fails when the request is aborted by the timeout. + global.fetch = jest.fn((url, options) => Promise.resolve({ + ok: true, + status: 200, + statusText: 'OK', + json: () => new Promise((resolve, reject) => { + options.signal.addEventListener('abort', () => reject(Object.assign(new Error('aborted'), { name: 'AbortError' }))); + }) + })); + + await expect(client.getBalance()).rejects.toThrow(TimeoutError); + + expect(lineOf('getBalance')).toMatch(/getBalance -> failed: TimeoutError: Request timed out after 20ms \(\d+ms\)$/); + expect(messageOf('getBalance').split('\n').at(-1)).toMatch(/^RESPONSE \(HTTP 200 OK, \d+ms\): body was not received \(TimeoutError\)$/); + }); + + test('reports a solve() timeout in the summary', async () => { + client = new CaptchaClient({ clientKey: 'secret_key', debug: true, timeout: 40, pollingInterval: 5 }); + global.fetch = jest.fn() + .mockImplementationOnce(() => okResponse({ errorId: 0, taskId: 12345 })) + .mockImplementation(() => okResponse({ errorId: 0, status: 'processing' })); + + await expect(client.solve(recaptchaTask())).rejects.toThrow(TimeoutError); + + const summary = summaryOf(); + expect(summary).toMatchObject({ + status: 'not solved', + taskId: '12345', + error: 'TimeoutError: Task 12345 timed out after 40ms' + }); + expect(Number(summary.polls)).toBeGreaterThan(0); + expect(summary).not.toHaveProperty('serverSolveTime'); + }); + + test('logs the error the caller receives, not the raw transport error', async () => { + client = new CaptchaClient({ clientKey: 'secret_key', debug: true, timeout: 10 }); + global.fetch = jest.fn((url, options) => new Promise((resolve, reject) => { + options.signal.addEventListener('abort', () => reject(Object.assign(new Error('aborted'), { name: 'AbortError' }))); + })); + + await expect(client.getBalance()).rejects.toThrow(TimeoutError); + + expect(lineOf('getBalance')).toMatch(/getBalance -> failed: TimeoutError: Request timed out after 10ms \(\d+ms\)$/); + expect(lineOf('getBalance')).not.toContain('AbortError'); + expect(messageOf('getBalance').split('\n').at(-1)).toMatch(/^RESPONSE: none - no response from the server \(TimeoutError, \d+ms\)$/); + }); + }); + test('aborts an HTTP request after timeout', async () => { client.timeout = 10; global.fetch = jest.fn((url, options) => new Promise((resolve, reject) => { @@ -306,7 +578,7 @@ describe('CaptchaClient error edge cases (async)', () => { }); }); - test('throws NetworkError on a non-2xx HTTP status without reading the body', async () => { + test('throws NetworkError on a non-2xx HTTP status after reading the error body', async () => { const json = jest.fn(); global.fetch = jest.fn(() => Promise.resolve({ ok: false, @@ -318,7 +590,7 @@ describe('CaptchaClient error edge cases (async)', () => { const error = await client.createTask(task()).catch((e) => e); expect(error).toBeInstanceOf(NetworkError); expect(error.message).toBe('HTTP error: 502 Bad Gateway'); - expect(json).not.toHaveBeenCalled(); + expect(json).toHaveBeenCalledTimes(1); }); test('throws NetworkError when the response body is not valid JSON', async () => {