diff --git a/CHANGELOG.md b/CHANGELOG.md index 7034356..65d27c4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,33 @@ All notable changes to this project are documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [1.2.0] - 2026-09-12 + +### Added + +- **ALTCHA support** via `altcha($url, $options)` on both `CapSkip` and + `AsyncCapSkip`. Pass `challenge_url` for CapSkip to fetch the challenge, or + `challenge_json` with the document itself (a JSON string, or an array which is + serialized for you). Sending both is allowed — the inline document wins. The + result exposes `token` (the value the site's `altcha` form field expects) and + `number`, the counter that solved it; `code` keeps the same raw string. +- Parameter aliases `challengeUrl`/`challengeURL` for `challenge_url` and + `challengeJson`/`challengeJSON` for `challenge_json`. +- Both ALTCHA generations are handled: the legacy scheme (SHA-1/256/384/512) and + proof-of-work v2 (PBKDF2 or SHA). Their tokens are shaped differently — a v2 + payload carries no top-level `number`, its counter sitting at + `solution.counter` — so the counter is taken from the server's own `solution` + object, the one field both report the same way, and dug out of the token only + when a poll did not carry it. + +### Notes + +- ALTCHA is CPU proof-of-work rather than a browser solve, so it uses + `defaultTimeout` instead of the longer `recaptchaTimeout` that reCAPTCHA, + Turnstile and GeeTest use. +- A proxy passed to `altcha()` applies only to the `challenge_url` fetch; a task + carrying its challenge inline never touches the network. + ## [1.1.0] - 2026-07-26 ### Added diff --git a/README.md b/README.md index 2c807a9..24014a6 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE) [![Tests](https://github.com/capskip/capskip-php/actions/workflows/ci.yml/badge.svg)](https://github.com/capskip/capskip-php/actions/workflows/ci.yml) -**Solve reCAPTCHA v2, reCAPTCHA v3, Cloudflare Turnstile, GeeTest and image captchas from PHP.** +**Solve reCAPTCHA v2, reCAPTCHA v3, Cloudflare Turnstile, GeeTest, ALTCHA and image captchas from PHP.** Official PHP client for [CapSkip](https://capskip.com), a **local captcha solver** that runs on your own machine. Licensed once, not billed per solve. @@ -19,7 +19,7 @@ composer require capskip/capskip CapSkip is a desktop app. It does the solving on your machine and exposes the standard captcha-solver HTTP API — the same `in.php` / `res.php` endpoints every 2captcha-compatible client already speaks — on `127.0.0.1:8080`. -This SDK is a thin wrapper over that API, with the method names you would expect: `normal()`, `recaptcha()`, `turnstile()`, `geetest()`. Nothing leaves your network, and there is no credit balance to keep an eye on. +This SDK is a thin wrapper over that API, with the method names you would expect: `normal()`, `recaptcha()`, `turnstile()`, `geetest()`, `altcha()`. Nothing leaves your network, and there is no credit balance to keep an eye on. ## Supported captcha types @@ -34,6 +34,7 @@ This SDK is a thin wrapper over that API, with the method names you would expect | **Cloudflare Turnstile solver** (widget) | `$solver->turnstile($sitekey, $url)` | | Cloudflare Turnstile (challenge page) | `$solver->turnstile($sitekey, $url, ['data' => ..., 'pagedata' => ...])` | | **GeeTest v3 solver** (slide puzzle) | `$solver->geetest($gt, $challenge, $url)` | +| **ALTCHA solver** (proof-of-work) | `$solver->altcha($url, [...])` | **hCaptcha and FunCaptcha/Arkose are not supported.** hCaptcha is the one people misidentify most often, since it also puts a `data-sitekey` on the widget — check for `class="h-captcha"` or a `js.hcaptcha.com` script before reaching for `recaptcha()`. @@ -131,6 +132,7 @@ $solver = new CapSkip([ 'port' => 8080, // CapSkip port from app settings 'defaultTimeout' => 120, // seconds — image captcha polling timeout 'recaptchaTimeout' => 300, // seconds — reCAPTCHA / Turnstile / GeeTest polling timeout + // (ALTCHA uses defaultTimeout — CPU work, not a browser solve) 'pollingInterval' => 5, // max seconds between res.php polls (starts at 0.25s, backs off to this) ]); ``` @@ -210,7 +212,25 @@ $result = $solver->geetest( $result['challenge']; $result['validate']; $result['seccode']; ``` -### With a proxy (reCAPTCHA, Turnstile & GeeTest only) +### ALTCHA + +ALTCHA is proof-of-work, not recognition — there is nothing to read, so a solve +is deterministic and takes milliseconds. Give CapSkip the endpoint that serves +the challenge, or the challenge document itself. + +```php +$result = $solver->altcha('https://example.com/signup', [ + 'challenge_url' => 'https://example.com/captcha/api/altcha/challenge', +]); + +// Post this back in the form field the widget uses, named `altcha` +$result['token']; +``` + +Challenges expire fast — some sites inside two minutes — so fetch one +immediately before solving and submit the token promptly. + +### With a proxy (reCAPTCHA, Turnstile, GeeTest & ALTCHA only) ```php // Proxy is not supported for image captcha @@ -290,6 +310,9 @@ Every solve method returns an associative array: ] ``` +ALTCHA adds `token` (the same string as `code`, named for the form field it goes +in) and `number`, the counter that solved it. + GeeTest additionally expands its answer into `challenge`, `validate`, and `seccode`, while `code` keeps the raw JSON string. @@ -325,7 +348,7 @@ All four extend `CapSkip\Exceptions\CapSkipError`, so you can catch them all at ### How do I solve a captcha in PHP? -Install the CapSkip desktop app, `composer require capskip/capskip`, then call the method that matches the widget — `recaptcha()`, `turnstile()`, `geetest()` or `normal()`. Each one blocks until CapSkip has an answer, then returns a token, or the recognized text in the case of an image captcha. +Install the CapSkip desktop app, `composer require capskip/capskip`, then call the method that matches the widget — `recaptcha()`, `turnstile()`, `geetest()`, `altcha()` or `normal()`. Each one blocks until CapSkip has an answer, then returns a token, or the recognized text in the case of an image captcha. ### Is this a free captcha solver? @@ -333,7 +356,7 @@ The SDK itself is MIT-licensed and free. Solving needs the CapSkip app, which is ### Which captchas can it solve? -reCAPTCHA v2 (checkbox and invisible), reCAPTCHA v3, reCAPTCHA Enterprise, Cloudflare Turnstile, GeeTest v3, and image/text captchas. Not hCaptcha, and not FunCaptcha/Arkose. +reCAPTCHA v2 (checkbox and invisible), reCAPTCHA v3, reCAPTCHA Enterprise, Cloudflare Turnstile, GeeTest v3, ALTCHA, and image/text captchas. Not hCaptcha, and not FunCaptcha/Arkose. ### Does it work with Laravel, Guzzle or Symfony? diff --git a/docs/API_REFERENCE.md b/docs/API_REFERENCE.md index 017d3ed..cbf54f7 100644 --- a/docs/API_REFERENCE.md +++ b/docs/API_REFERENCE.md @@ -22,8 +22,10 @@ The SDK only supports the four captcha types documented by CapSkip. | reCAPTCHA v3 | `recaptcha(..., ['version' => 'v3'])` | `userrecaptcha` + `version=v3` | | Cloudflare Turnstile | `turnstile()` | `turnstile` | | GeeTest v3 (slide) | `geetest()` | `geetest` | +| ALTCHA (proof-of-work) | `altcha()` | `altcha` | -**Proxy** is supported for reCAPTCHA, Turnstile, and GeeTest — not for image captcha. +**Proxy** is supported for reCAPTCHA, Turnstile, GeeTest, and ALTCHA — not for image +captcha. For ALTCHA the proxy is used only for the `challenge_url` fetch. --- @@ -253,6 +255,111 @@ rather than `defaultTimeout`. --- +## 6. ALTCHA — `altcha($url, $options)` + +ALTCHA is not a recognition captcha. There is no image, audio or text to read: +the site issues a proof-of-work challenge and the client must brute-force a +number that satisfies it. A solve is therefore deterministic and cheap — +typically milliseconds. + +### POST `/in.php` + +| Parameter | Type | Required | Description | +|---|---|---|---| +| `key` | string | Yes | CapSkip API key | +| `method` | string | Yes | `altcha` | +| `pageurl` | string | Yes | Full URL of the page the challenge came from | +| `challenge_url` | string | One of the two | Endpoint CapSkip fetches the challenge from | +| `challenge_json` | string | One of the two | The challenge document itself, as a JSON string | +| `json` | int | No | `0` plain text, `1` JSON | +| `proxy` | string | No | Proxy address — used **only** for the `challenge_url` fetch | +| `proxytype` | string | No | Proxy type | + +Sending both challenge parameters is allowed: the inline `challenge_json` wins, +because fetching would only re-obtain what you already supplied. + +### Getting the challenge + +Open DevTools → Network on the target page and look for the request the +`` makes for its challenge (often something like +`/altcha/challenge`). The request URL is your `challenge_url`; its JSON response +is your `challenge_json`. + +The widget attribute that names that endpoint depends on the widget version, so +read the page source rather than assuming: + +| Widget | Attribute | +|---|---| +| v1 / v2 | `challengeurl="…"`, with a separate `challengejson="…"` for an inline challenge | +| v3+ | `challenge="…"` — the same attribute takes either a URL or the challenge data | + +> **Challenges expire, and the window is short** — some sites inside two minutes. +> Once expired, the site refuses the solution with a bare "verification failed" +> that looks exactly like a wrong answer. Fetch the challenge immediately before +> solving and submit the token promptly; do not fetch a batch in advance, and do +> not hold a token while a user fills in a form. +> +> CapSkip refuses an already-expired inline challenge immediately rather than +> burning CPU on a token that cannot work. If you passed `challenge_url` and the +> challenge expired while the job queued, it fetches a fresh one automatically. + +### SDK usage + +```php +// CapSkip fetches the challenge for you +$result = $solver->altcha('https://example.com/signup', [ + 'challenge_url' => 'https://example.com/captcha/api/altcha/challenge', +]); + +// …or hand it the document you already have. No network request at all. +$result = $solver->altcha('https://example.com/signup', [ + 'challenge_json' => [ + 'algorithm' => 'SHA-256', 'challenge' => '…', 'salt' => '…', + 'signature' => '…', 'maxnumber' => 1000000, + ], +]); + +$result['token']; // the base64 payload to post back +$result['number']; // the counter that solved it +$result['code']; // the same string as token +``` + +`challenge_json` accepts an array (serialized for you) or a JSON string. + +`number` is reported for both ALTCHA generations. Their tokens differ — a legacy +payload carries it as a top-level `number`, while a proof-of-work v2 payload has +none, its counter sitting at `solution.counter` — so it is read from the server's +own `solution` object, which reports both the same way. + +Post the token back in the form field the widget uses, named `altcha`: + +```php +$body = http_build_query([ + 'email' => 'someone@example.com', + 'altcha' => $result['token'], +]); +``` + +Do not re-encode, trim or re-order the token: it is base64 of a JSON document +whose fields are covered by the server's HMAC signature, so any modification +invalidates it. Some integrations read the payload from a JSON body field +instead — check what the page's own submit sends and mirror it. + +Unlike GeeTest and reCAPTCHA this is CPU proof-of-work rather than a browser +solve, so it uses `defaultTimeout`, not `recaptchaTimeout`. + +### Algorithms + +CapSkip supports the legacy scheme (SHA-1/256/384/512) and PoW v2 with PBKDF2 or +SHA. **Argon2id and scrypt are refused**, not attempted: a task using one returns +`ERROR_CAPTCHA_UNSOLVABLE` and is never retried. ALTCHA itself recommends PBKDF2 +as the default, so this affects a minority of sites. + +All three widget types (`native`, `checkbox`, `switch`) work — the distinction is +purely visual and never reaches CapSkip. + +--- + ## Return value Every solve method returns: diff --git a/examples/altcha.php b/examples/altcha.php new file mode 100644 index 0000000..52e2b56 --- /dev/null +++ b/examples/altcha.php @@ -0,0 +1,100 @@ + Network on the target page and look for the + * request the `` makes for its challenge (often something like + * `/altcha/challenge`). The request URL is your `challenge_url`; its JSON + * response is your `challenge_json`. + * + * Note the widget attribute that names the endpoint changed between versions: + * v1/v2 use `challengeurl="..."`, while v3+ uses `challenge="..."` for both a + * URL and inline data. Read the page source rather than assuming. + * + * Challenges expire fast -- some sites inside two minutes -- so fetch one + * immediately before solving and post the token promptly. An expired challenge + * is rejected with a bare "verification failed" that looks exactly like a wrong + * answer. + * + * This example issues its own challenge the way a site's server would, so it + * runs as-is with no third-party dependency. Swap in your target's endpoint to + * use it for real. + */ + +declare(strict_types=1); + +require __DIR__ . '/../vendor/autoload.php'; + +use CapSkip\CapSkip; + +$solver = new CapSkip([ + 'apiKey' => getenv('CAPSKIP_API_KEY') ?: 'capskip', + 'host' => getenv('CAPSKIP_HOST') ?: '127.0.0.1', + 'port' => (int) (getenv('CAPSKIP_PORT') ?: 8080), +]); + +const PAGE_URL = 'https://example.com/signup'; + +/** + * Mint an ALTCHA challenge, exactly as a site's own server would. + * + * Replace this with a fetch of your target's challenge endpoint -- or skip it + * entirely and pass `challenge_url` so CapSkip does the fetching. + * + * @return array + */ +function issueChallenge(int $number = 54321): array +{ + $salt = bin2hex(random_bytes(12)) . '?expires=' . (time() + 600); + + return [ + 'algorithm' => 'SHA-256', + 'challenge' => hash('sha256', $salt . $number), + 'salt' => $salt, + 'signature' => str_repeat('0', 64), + 'maxnumber' => 100000, + ]; +} + +// --- Option A: you already have the challenge document ----------------------- +// No network request at all: CapSkip solves it locally. +$result = $solver->altcha(PAGE_URL, ['challenge_json' => issueChallenge()]); + +echo 'Captcha ID: ' . $result['captchaId'] . PHP_EOL; +echo 'Number: ' . $result['number'] . PHP_EOL; +echo 'Token: ' . substr($result['token'], 0, 60) . '...' . PHP_EOL; + +// --- Option B: let CapSkip fetch the challenge -------------------------------- +// Point it at the endpoint the widget calls. Add `proxy` if the endpoint should +// be fetched from a particular IP -- the proxy is used only for that fetch, +// never for the solve itself. +// +// $result = $solver->altcha(PAGE_URL, [ +// 'challenge_url' => 'https://example.com/captcha/api/altcha/challenge', +// 'proxy' => ['type' => 'HTTP', 'uri' => 'login:password@1.2.3.4:8080'], +// ]); + +// Post the token back in the form field the widget uses, named `altcha`: +// +// $post = http_build_query([ +// 'email' => 'someone@example.com', +// 'altcha' => $result['token'], +// ]); +// +// Do not re-encode, trim or re-order it. The token is base64 of a JSON document +// whose fields are covered by the server's HMAC signature, so any modification +// invalidates it. + +// `code` holds the same string as `token`, which is what you forward if you are +// porting code written against another solver's API. +assert($result['code'] === $result['token']); diff --git a/src/ApiParams.php b/src/ApiParams.php index ab45e67..d85eb96 100644 --- a/src/ApiParams.php +++ b/src/ApiParams.php @@ -36,6 +36,12 @@ final class ApiParams 'proxy', 'proxytype', ]; + /** @var array */ + public const ALTCHA_SUBMIT = [ + 'method', 'pageurl', 'challenge_url', 'challenge_json', 'json', + 'proxy', 'proxytype', + ]; + /** * The only values CapSkip maps to a proxy scheme; it answers * ERROR_BAD_PARAMETERS for anything else, SOCKS4 included. Matched @@ -54,6 +60,10 @@ final class ApiParams 'data_s' => 'data-s', 'apiServer' => 'api_server', 'api_subdomain' => 'api_server', + 'challengeUrl' => 'challenge_url', + 'challengeURL' => 'challenge_url', + 'challengeJson' => 'challenge_json', + 'challengeJSON' => 'challenge_json', ]; /** @@ -201,6 +211,62 @@ public static function validateGeetestSubmit(array $params): void } } + /** + * Drop unset challenge params and serialize an inline challenge document. + * + * `altcha($url, ['challenge_url' => ..., 'challenge_json' => ...])` is + * normally called with one of the two left as null, and the form body can + * only carry a string -- so a document passed as an array is serialized + * rather than triggering an array-to-string conversion. Mirrors the server, + * which reads a JSON-body `null` as "not sent". + * + * @param array $params + * + * @return array + */ + public static function normalizeAltchaSubmit(array $params): array + { + $out = []; + foreach ($params as $key => $value) { + if ($value !== null) { + $out[$key] = $value; + } + } + + if (isset($out['challenge_json']) && is_array($out['challenge_json'])) { + $out['challenge_json'] = (string) json_encode($out['challenge_json']); + } + + return $out; + } + + /** + * @param array $params + */ + public static function validateAltchaSubmit(array $params): void + { + if (empty($params['pageurl'])) { + throw new ValidationException("'pageurl' is required for ALTCHA."); + } + + // CapSkip answers ERROR_BAD_PARAMETERS when neither is sent. Sending both + // is deliberately allowed -- the inline document simply wins, because + // fetching would only re-obtain what the caller already supplied. + if (empty($params['challenge_url']) && empty($params['challenge_json'])) { + throw new ValidationException( + "ALTCHA needs a challenge: pass 'challenge_url' for CapSkip to fetch it, " + . "or 'challenge_json' with the challenge document itself." + ); + } + + $unknown = self::unknownKeys($params, self::ALTCHA_SUBMIT); + if (!empty($unknown)) { + throw new ValidationException( + 'Unsupported parameters for ALTCHA: ' . self::reprList($unknown) . '.' + ); + } + } + /** * Apply aliases + proxy normalization, then validate for the captcha type. * @@ -221,6 +287,9 @@ public static function prepareSubmitParams(array $params, string $captchaType, s self::validateTurnstileSubmit($params); } elseif ($captchaType === 'geetest') { self::validateGeetestSubmit($params); + } elseif ($captchaType === 'altcha') { + $params = self::normalizeAltchaSubmit($params); + self::validateAltchaSubmit($params); } // Skipped for 'normal', which rejects proxy outright with a clearer message. diff --git a/src/CapSkip.php b/src/CapSkip.php index 39a15ad..bbd4ca4 100644 --- a/src/CapSkip.php +++ b/src/CapSkip.php @@ -14,7 +14,7 @@ class CapSkip { /** Installed SDK version. */ - public const VERSION = '1.1.0'; + public const VERSION = '1.2.0'; /** * First poll fires this soon after submitting (in seconds), then the interval @@ -151,6 +151,49 @@ public function geetest(string $gt, string $challenge, string $url, array $optio return self::applyGeetestSolution($result); } + /** + * Solve an ALTCHA proof-of-work challenge. + * + * Pass `challenge_url` for CapSkip to fetch the challenge itself, or + * `challenge_json` with the document you already have (a JSON string, or an + * array which is serialized for you). Sending both is allowed -- the inline + * document wins. A proxy applies only to the `challenge_url` fetch. + * + * Challenges expire fast -- some sites inside two minutes -- and an expired + * one is refused with a bare "verification failed" that looks exactly like a + * wrong answer. Fetch the challenge immediately before calling, and post the + * token promptly. + * + * The result carries the raw answer as `code`, the same string as `token` + * (what the site's `altcha` form field expects, verbatim), and the counter + * that solved it as `number`. + * + * @param array $options `challenge_url`, `challenge_json`, `proxy`, ... + * + * @return array + */ + public function altcha(string $url, array $options = []): array + { + // An unset challenge param is dropped rather than sent as null, so + // passing both keys with one left out works. + $given = []; + foreach ($options as $key => $value) { + if ($value !== null) { + $given[$key] = $value; + } + } + + // Unlike GeeTest and reCAPTCHA this is CPU proof-of-work measured in + // milliseconds, not a browser solve, so it keeps the default timeout. + $result = $this->solve(array_merge( + ['url' => $url], + $given, + ['method' => 'altcha', 'poll_json' => 1] + )); + + return self::applyAltchaSolution($result); + } + /** * Submit then poll to completion. Used by the higher-level solve methods. * @@ -370,6 +413,81 @@ public static function applyGeetestSolution(array $result): array return $result; } + /** + * ALTCHA answers come back as a base64 payload: the challenge document with + * the winning counter added. That payload is what the site's own `altcha` + * form field carries, so it is posted back verbatim. + * + * Expose it as `token`, and the counter as `number`. `code` keeps the raw + * answer so callers that forward it verbatim (or that were written against + * another solver's API) keep working. + * + * The counter comes from the server's own `solution` object when the poll + * carried one, because that is the single field both ALTCHA generations + * report the same way. Only if it is absent -- a plain-text poll -- is it dug + * out of the token, which is shaped differently per scheme. If neither yields + * one, the result keeps its token and simply has no `number`, rather than + * masking the server's reply. + * + * @param array $result + * + * @return array + */ + public static function applyAltchaSolution(array $result): array + { + $code = (string) ($result['code'] ?? ''); + $result['token'] = $code; + + $solution = $result['solution'] ?? null; + unset($result['solution']); + + $number = is_array($solution) ? ($solution['number'] ?? null) : null; + if ($number === null) { + $number = self::altchaTokenCounter($code); + } + + if ($number !== null) { + $result['number'] = $number; + } + + return $result; + } + + /** + * Dig the winning counter out of a token, whichever scheme produced it. + * + * The two ALTCHA generations nest it differently: a legacy payload is the + * challenge document with a top-level `number` added, while a proof-of-work + * v2 payload is `{"challenge": {...}, "solution": {"counter": N, ...}}` and + * has no `number` at all. Returns null if the payload does not decode. + * + * @return mixed + */ + private static function altchaTokenCounter(string $code) + { + // strict mode: reject anything that is not genuinely base64 rather than + // silently decoding garbage. + $decoded = base64_decode($code, true); + if ($decoded === false) { + return null; + } + + $payload = json_decode($decoded, true); + if (!is_array($payload)) { + return null; + } + + if (array_key_exists('number', $payload)) { + return $payload['number']; + } + + if (isset($payload['solution']) && is_array($payload['solution'])) { + return $payload['solution']['counter'] ?? null; + } + + return null; + } + /** * @param array $result * @param array|string $polled @@ -384,6 +502,13 @@ public static function applyPollResult(array $result, $polled): array if ($userAgent) { $result['userAgent'] = $userAgent; } + // ALTCHA's createTask-shaped `solution` object. Carried through so + // applyAltchaSolution can read the counter the server already worked + // out, which is the only reliable source for a proof-of-work v2 + // answer; that method unsets it, so it never reaches the caller. + if (isset($polled['solution']) && is_array($polled['solution'])) { + $result['solution'] = $polled['solution']; + } } else { $result['code'] = $polled; } @@ -411,6 +536,9 @@ private function prepareSendParams(array $params): array if ($method === 'geetest') { return ApiParams::prepareSubmitParams($params, 'geetest'); } + if ($method === 'altcha') { + return ApiParams::prepareSubmitParams($params, 'altcha'); + } return ApiParams::applyProxy(ApiParams::applyParamAliases($params)); } diff --git a/tests/AltchaTest.php b/tests/AltchaTest.php new file mode 100644 index 0000000..3764737 --- /dev/null +++ b/tests/AltchaTest.php @@ -0,0 +1,397 @@ + */ + public array $incomings = []; + + public string $request; + + public function __construct(?string $request = null) + { + parent::__construct(); + $this->request = $request ?? AltchaTest::token(); + } + + public function in_(array $options = []): string + { + unset($options['files']); + $this->incomings = $options; + + return 'OK|123'; + } + + public function res(array $params = []): string + { + $json = $params['json'] ?? null; + if ($json === 1 || $json === '1') { + return (string) json_encode([ + 'status' => 1, + 'request' => $this->request, + 'solution' => ['token' => $this->request, 'number' => AltchaTest::NUMBER], + ]); + } + + return 'OK|' . $this->request; + } +} + +/** Mock client whose poll returns exactly the payload it was given. */ +class RawAltchaApiClient extends ApiClient +{ + /** @var array */ + public array $incomings = []; + + /** @var array */ + private array $payload; + + /** @param array $payload */ + public function __construct(array $payload) + { + parent::__construct(); + $this->payload = $payload; + } + + public function in_(array $options = []): string + { + unset($options['files']); + $this->incomings = $options; + + return 'OK|123'; + } + + public function res(array $params = []): string + { + return (string) json_encode($this->payload); + } +} + +class AltchaTest extends TestCase +{ + private const URL = 'https://mysite.com/signup'; + private const CHALLENGE_URL = 'https://mysite.com/captcha/api/altcha/challenge'; + + public const NUMBER = 9661; + + /** @var array */ + public const CHALLENGE_DOC = [ + 'algorithm' => 'SHA-256', + 'challenge' => '3dd28253be6cc0c54d95f7f98c517e68', + 'salt' => '46d5b1c8871e5152d902ee3f?expires=1893456000', + 'signature' => '4b1cf0e0be0f4e5247e50b0f9a449830', + 'maxnumber' => 1000000, + ]; + + public const V2_NUMBER = 47; + + /** + * What CapSkip hands back for a *legacy* challenge: base64 of the solved + * challenge document, with the winning counter in `number`. + */ + public static function token(): string + { + return base64_encode((string) json_encode( + array_merge(self::CHALLENGE_DOC, ['number' => self::NUMBER]) + )); + } + + /** + * A PoW v2 answer is shaped completely differently: no top-level `number`, + * and the counter sits at `solution.counter`. Captured from a real + * PBKDF2/SHA-256 deployment (captcha.seventy9.co.uk), the scheme altcha.org + * documents today. + */ + public static function v2Token(): string + { + return base64_encode((string) json_encode([ + 'challenge' => [ + 'parameters' => [ + 'algorithm' => 'PBKDF2/SHA-256', + 'cost' => 50000, + 'expiresAt' => 1789224090, + 'keyLength' => 32, + 'keyPrefix' => '00', + 'nonce' => '634c4f591fd086beb40d67312b85808a', + 'salt' => '511e1c75edbf295278c9bfb68191053c', + ], + 'signature' => '9197e4a35ebff399d669e747c7c5e6ab079b30fe3437df268dc7caf34cf9e281', + ], + 'solution' => [ + 'counter' => self::V2_NUMBER, + 'derivedKey' => '0099db7cb36864d8875ff8305c9a3d2649b1f72cb774de1c', + ], + ])); + } + + public static function challengeJson(): string + { + return (string) json_encode(self::CHALLENGE_DOC); + } + + private CapSkip $solver; + + protected function setUp(): void + { + $this->solver = new CapSkip(['apiKey' => 'API_KEY', 'pollingInterval' => 1]); + $this->solver->apiClient = new MockAltchaApiClient(); + } + + /** @param array $options @return array */ + private function solve(array $options = []): array + { + return $this->solver->altcha( + self::URL, + array_merge(['challenge_url' => self::CHALLENGE_URL], $options) + ); + } + + /** @param array $expected */ + private function assertSent(array $expected): void + { + /** @var MockAltchaApiClient $client */ + $client = $this->solver->apiClient; + $this->assertEquals(array_merge($expected, ['key' => 'API_KEY']), $client->incomings); + } + + public function testBasic(): void + { + $result = $this->solve(); + + $this->assertSent([ + 'method' => 'altcha', + 'pageurl' => self::URL, + 'challenge_url' => self::CHALLENGE_URL, + ]); + $this->assertSame('123', $result['captchaId']); + } + + public function testChallengeJsonString(): void + { + $this->solve(['challenge_url' => null, 'challenge_json' => self::challengeJson()]); + + $this->assertSent([ + 'method' => 'altcha', + 'pageurl' => self::URL, + 'challenge_json' => self::challengeJson(), + ]); + } + + public function testChallengeJsonAcceptsAnArray(): void + { + // The form body can only carry a string, so a document passed as an array + // has to be serialized rather than triggering an array-to-string notice. + $this->solve(['challenge_url' => null, 'challenge_json' => self::CHALLENGE_DOC]); + + /** @var MockAltchaApiClient $client */ + $client = $this->solver->apiClient; + $this->assertEquals( + self::CHALLENGE_DOC, + json_decode((string) $client->incomings['challenge_json'], true) + ); + } + + public function testCamelCaseAliases(): void + { + $this->solve(['challenge_url' => null, 'challengeUrl' => self::CHALLENGE_URL]); + + $this->assertSent([ + 'method' => 'altcha', + 'pageurl' => self::URL, + 'challenge_url' => self::CHALLENGE_URL, + ]); + } + + public function testChallengeJsonCamelCaseAlias(): void + { + $this->solve(['challenge_url' => null, 'challengeJSON' => self::challengeJson()]); + + $this->assertSent([ + 'method' => 'altcha', + 'pageurl' => self::URL, + 'challenge_json' => self::challengeJson(), + ]); + } + + public function testBothChallengeParamsAreAllowed(): void + { + // CapSkip is deliberately more permissive than 2Captcha here: sending + // both is not an error, the inline document simply wins. + $this->solve(['challenge_json' => self::challengeJson()]); + + $this->assertSent([ + 'method' => 'altcha', + 'pageurl' => self::URL, + 'challenge_url' => self::CHALLENGE_URL, + 'challenge_json' => self::challengeJson(), + ]); + } + + public function testProxy(): void + { + $this->solve(['proxy' => ['type' => 'HTTP', 'uri' => '1.2.3.4:3128']]); + + $this->assertSent([ + 'method' => 'altcha', + 'pageurl' => self::URL, + 'challenge_url' => self::CHALLENGE_URL, + 'proxy' => '1.2.3.4:3128', + 'proxytype' => 'HTTP', + ]); + } + + public function testExposesTokenAndNumber(): void + { + $result = $this->solve(); + + $this->assertSame(self::token(), $result['code']); + $this->assertSame(self::token(), $result['token']); + $this->assertSame(self::NUMBER, $result['number']); + } + + public function testExposesTheCounterForAProofOfWorkV2Answer(): void + { + // A v2 token carries no top-level `number` -- the counter is at + // `solution.counter`, and the server reports it as `solution.number` in + // the poll payload. Reading only the token's own `number` silently drops + // it for every PBKDF2 site, which is the scheme ALTCHA recommends. + $token = self::v2Token(); + $this->solver->apiClient = new RawAltchaApiClient([ + 'status' => 1, + 'request' => $token, + 'solution' => ['token' => $token, 'number' => self::V2_NUMBER], + ]); + + $result = $this->solve(); + + $this->assertSame($token, $result['token']); + $this->assertSame(self::V2_NUMBER, $result['number']); + } + + public function testRecoversAV2CounterFromTheTokenWithoutASolution(): void + { + $token = self::v2Token(); + $this->solver->apiClient = new RawAltchaApiClient([ + 'status' => 1, + 'request' => $token, + ]); + + $result = $this->solve(); + + $this->assertSame(self::V2_NUMBER, $result['number']); + } + + public function testDoesNotLeakThePollSolutionIntoTheResult(): void + { + // Its two fields are already exposed as `token` and `number`. + $result = $this->solve(); + + $this->assertArrayNotHasKey('solution', $result); + } + + public function testUndecodableAnswerIsLeftAlone(): void + { + // No `solution` object either -- a server returning something that is not + // a token has no counter to report, so there is nothing to fall back on. + $this->solver->apiClient = new RawAltchaApiClient([ + 'status' => 1, + 'request' => 'not-base64-json', + ]); + + $result = $this->solve(); + + $this->assertSame('not-base64-json', $result['code']); + $this->assertArrayNotHasKey('number', $result); + } + + public function testTrustsTheServerCounterOverAnUnreadableToken(): void + { + // If the two ever disagree, the server worked the answer out and the + // decode is only an inference from it. + $this->solver->apiClient = new RawAltchaApiClient([ + 'status' => 1, + 'request' => 'not-base64-json', + 'solution' => ['token' => 'not-base64-json', 'number' => 512], + ]); + + $result = $this->solve(); + + $this->assertSame(512, $result['number']); + } + + public function testUsesTheDefaultTimeoutNotTheRecaptchaOne(): void + { + // ALTCHA is CPU proof-of-work measured in milliseconds, not a browser + // solve, so it must not inherit reCAPTCHA's much longer budget. + $this->assertNotSame($this->solver->defaultTimeout, $this->solver->recaptchaTimeout); + + $this->solve(); + + /** @var MockAltchaApiClient $client */ + $client = $this->solver->apiClient; + $this->assertArrayNotHasKey('timeout', $client->incomings); + } + + public function testMissingUrlRaises(): void + { + $this->expectException(ValidationException::class); + $this->solver->altcha('', ['challenge_url' => self::CHALLENGE_URL]); + } + + public function testMissingBothChallengeParamsRaises(): void + { + // CapSkip answers ERROR_BAD_PARAMETERS; fail locally instead of paying + // for the round-trip. + $this->expectException(ValidationException::class); + $this->solver->altcha(self::URL); + } + + public function testEmptyChallengeParamsRaise(): void + { + $this->expectException(ValidationException::class); + $this->solver->altcha(self::URL, ['challenge_url' => '', 'challenge_json' => '']); + } + + public function testUnsupportedParameterRaises(): void + { + $this->expectException(ValidationException::class); + $this->solve(['sitekey' => 'not-an-altcha-param']); + } + + /** @return array> */ + public function proxyTypeProvider(): array + { + return [['HTTP'], ['HTTPS'], ['SOCKS5'], ['SOCKS5H'], ['socks5h']]; + } + + /** @dataProvider proxyTypeProvider */ + public function testAcceptedProxyTypes(string $proxytype): void + { + $this->solve(['proxy' => ['type' => $proxytype, 'uri' => '1.2.3.4:3128']]); + + /** @var MockAltchaApiClient $client */ + $client = $this->solver->apiClient; + $this->assertSame($proxytype, $client->incomings['proxytype']); + } + + public function testSocks4IsRejected(): void + { + $this->expectException(ValidationException::class); + $this->solve(['proxy' => ['type' => 'SOCKS4', 'uri' => '1.2.3.4:3128']]); + } + + public function testUnknownProxyTypeIsRejected(): void + { + $this->expectException(ValidationException::class); + $this->solve(['proxy' => '1.2.3.4:3128', 'proxytype' => 'FTP']); + } +} diff --git a/tests/IntegrationTest.php b/tests/IntegrationTest.php index f8c83b4..8da289e 100644 --- a/tests/IntegrationTest.php +++ b/tests/IntegrationTest.php @@ -220,4 +220,34 @@ public function testMultipleSolves(): void $this->assertSame(MockServer::CODE, $first['code']); $this->assertSame(MockServer::CODE, $second['code']); } + public function testAltchaWithChallengeUrl(): void + { + $solver = $this->makeSolver(); + $result = $solver->altcha(self::URL, [ + 'challenge_url' => 'https://example.com/captcha/api/altcha/challenge', + ]); + + $this->assertSame(MockServer::ALTCHA_TOKEN, $result['code']); + $this->assertSame(MockServer::ALTCHA_TOKEN, $result['token']); + $this->assertSame(MockServer::ALTCHA_NUMBER, $result['number']); + $this->assertNotEmpty($result['captchaId']); + } + + public function testAltchaWithInlineChallengeArray(): void + { + // An array has to reach the server as JSON, not as the string "Array", + // or the server answers ERROR_BAD_PARAMETERS. + $solver = $this->makeSolver(); + $result = $solver->altcha(self::URL, [ + 'challenge_json' => [ + 'algorithm' => 'SHA-256', + 'challenge' => '3dd28253be6cc0c54d95f7f98c517e68', + 'salt' => '46d5b1c8871e5152d902ee3f?expires=1893456000', + 'signature' => '4b1cf0e0be0f4e5247e50b0f9a449830', + 'maxnumber' => 1000000, + ], + ]); + + $this->assertSame(MockServer::ALTCHA_NUMBER, $result['number']); + } } diff --git a/tests/MockServer.php b/tests/MockServer.php index b10cdc9..83b2d45 100644 --- a/tests/MockServer.php +++ b/tests/MockServer.php @@ -13,6 +13,8 @@ class MockServer { public const CODE = 'SOLVED_TOKEN_abc123'; public const USER_AGENT = 'CapSkipUA/1.0'; + public const ALTCHA_NUMBER = 9661; + public const ALTCHA_TOKEN = 'eyJhbGdvcml0aG0iOiJTSEEtMjU2IiwiY2hhbGxlbmdlIjoiM2RkMjgyNTNiZTZjYzBjNTRkOTVmN2Y5OGM1MTdlNjgiLCJudW1iZXIiOjk2NjEsInNhbHQiOiI0NmQ1YjFjODg3MWU1MTUyZDkwMmVlM2Y/ZXhwaXJlcz0xODkzNDU2MDAwIiwic2lnbmF0dXJlIjoiNGIxY2YwZTBiZTBmNGU1MjQ3ZTUwYjBmOWE0NDk4MzAiLCJ0b29rIjoxNi41OH0='; public const PNG_BASE64 = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=='; public string $host = '127.0.0.1'; diff --git a/tests/server/router.php b/tests/server/router.php index 9e14961..87c1e9c 100644 --- a/tests/server/router.php +++ b/tests/server/router.php @@ -15,6 +15,12 @@ const MOCK_CODE = 'SOLVED_TOKEN_abc123'; const MOCK_USER_AGENT = 'CapSkipUA/1.0'; +// ALTCHA answers are base64 of the challenge document with the winning counter +// added, so the mock has to return a real one for the token/number parsing to +// mean anything. +const MOCK_ALTCHA_NUMBER = 9661; +const MOCK_ALTCHA_TOKEN = 'eyJhbGdvcml0aG0iOiJTSEEtMjU2IiwiY2hhbGxlbmdlIjoiM2RkMjgyNTNiZTZjYzBjNTRkOTVmN2Y5OGM1MTdlNjgiLCJudW1iZXIiOjk2NjEsInNhbHQiOiI0NmQ1YjFjODg3MWU1MTUyZDkwMmVlM2Y/ZXhwaXJlcz0xODkzNDU2MDAwIiwic2lnbmF0dXJlIjoiNGIxY2YwZTBiZTBmNGU1MjQ3ZTUwYjBmOWE0NDk4MzAiLCJ0b29rIjoxNi41OH0='; + // A minimal valid 1x1 PNG. The SDK never inspects the bytes, so exact pixels do // not matter — the mock just needs to return something for /image.png. const MOCK_PNG_BASE64 = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=='; @@ -75,6 +81,18 @@ $wantJson ? '{"status":0,"request":"CAPCHA_NOT_READY"}' : 'CAPCHA_NOT_READY', $wantJson ? 'application/json' : 'text/plain' ); + } elseif (($state['idType'][$cid] ?? '') === 'altcha') { + // CapSkip emits a superset: the legacy status/request pair plus the + // createTask-shaped solution object. + if ($wantJson) { + $sendText((string) json_encode([ + 'status' => 1, + 'request' => MOCK_ALTCHA_TOKEN, + 'solution' => ['token' => MOCK_ALTCHA_TOKEN, 'number' => MOCK_ALTCHA_NUMBER], + ]), 'application/json'); + } else { + $sendText('OK|' . MOCK_ALTCHA_TOKEN); + } } elseif ($wantJson && ($state['idType'][$cid] ?? '') === 'turnstile') { $sendText('{"status":1,"request":"' . MOCK_CODE . '","useragent":"' . MOCK_USER_AGENT . '"}', 'application/json'); } elseif ($wantJson) {