Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion examples/debug_mode.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ import { CaptchaClient, Tasks } from '@captcha-solver-api/javascript-sdk';
* 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.
* The API key, passwords, cookies and proxy credentials are shown as [MASKED]. Review the
* log before sharing it: URLs and other task fields may still contain application data.
*
* How it works:
* STEP-01 - Configure the SDK client with debug logging enabled.
Expand Down
13 changes: 11 additions & 2 deletions src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,12 @@ export class CaptchaClient {
try {
const response = await fetch(`${this.baseUrl}${endpoint}`, { method: 'POST', headers, body: JSON.stringify(payload), signal: controller.signal });
httpStatus = `${response.status} ${response.statusText ?? ''}`.trim();
// Without debug nobody looks at an error body, so fail on the status at once: a proxy
// can send 502 headers and then stall the body until the request timeout.
if (!response.ok && !this.debug) {
response.body?.cancel().catch(() => {});
throw new NetworkError(`HTTP error: ${response.status} ${response.statusText}`);
}
try {
data = await response.json() as typeof data;
} catch (parseError) {
Expand Down Expand Up @@ -366,10 +372,13 @@ export class CaptchaClient {
let polls = 0;
try {
taskId = await this.createTask(task, languagePool);
// The polling budget starts once the task exists, as in 1.x: a slow createTask must not
// eat into it. startedAt still measures the whole solve() for the debug summary.
const pollingStartedAt = 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`);
const remaining = this.timeout - (Date.now() - pollingStartedAt); 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`);
if (Date.now() - pollingStartedAt >= 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') {
Expand Down
34 changes: 31 additions & 3 deletions tests/unit/async/client.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -472,6 +472,30 @@ describe('CaptchaClient (async)', () => {
await expect(client.solve(task)).rejects.toThrow(TimeoutError);
});

test('does not count createTask time against the polling timeout', async () => {
client.timeout = 100;
client.pollingInterval = 20;

global.fetch = jest.fn()
// createTask takes longer than the whole timeout, but still within the HTTP abort
// budget because the mock ignores the abort signal.
.mockImplementationOnce(() => new Promise(resolve => setTimeout(() => resolve({
ok: true,
json: () => Promise.resolve({ errorId: 0, taskId: 12345 })
}), 150)))
.mockImplementationOnce(() => Promise.resolve({
ok: true,
json: () => Promise.resolve({ errorId: 0, status: 'ready', solution: { gRecaptchaResponse: 'token' } })
}));

const task = new Tasks.RecaptchaV2Proxyless({
websiteURL: 'https://example.com',
websiteKey: 'test_key'
});

await expect(client.solve(task)).resolves.toEqual({ gRecaptchaResponse: 'token' });
});

test('throws ApiError when a task fails during polling', async () => {
global.fetch = jest.fn()
.mockImplementationOnce(() =>
Expand Down Expand Up @@ -578,19 +602,23 @@ describe('CaptchaClient error edge cases (async)', () => {
});
});

test('throws NetworkError on a non-2xx HTTP status after reading the error body', async () => {
const json = jest.fn();
test('throws NetworkError on a non-2xx HTTP status without waiting for the body', async () => {
// A body that never arrives: without debug the error must not wait for it.
const json = jest.fn(() => new Promise(() => {}));
const cancel = jest.fn(() => Promise.resolve());
global.fetch = jest.fn(() => Promise.resolve({
ok: false,
status: 502,
statusText: 'Bad Gateway',
body: { cancel },
json
}));

const error = await client.createTask(task()).catch((e) => e);
expect(error).toBeInstanceOf(NetworkError);
expect(error.message).toBe('HTTP error: 502 Bad Gateway');
expect(json).toHaveBeenCalledTimes(1);
expect(json).not.toHaveBeenCalled();
expect(cancel).toHaveBeenCalledTimes(1);
});

test('throws NetworkError when the response body is not valid JSON', async () => {
Expand Down