Laravel Dusk CAPTCHA: Pass Turnstile in a Browser Test

laravel dusk captcha - Laravel Dusk CAPTCHA: Pass Turnstile in a Browser Test

This guide shows how to pass a Laravel Dusk CAPTCHA, which means a test that has to get through someone else’s widget, not how to add one to your app. When a Dusk test reaches a page with a Cloudflare Turnstile widget, the test can read the sitekey, ask CapSkip for a token with the PHP SDK, write it into the widget’s hidden field with $browser->script() and press the real submit button. CapSkip runs on your own Windows PC, so a token costs no fee per solve.

What you need

  • PHP 8.3 or newer for the current Laravel 13 line, whose framework package requires ^8.3, or PHP 8.2 for Laravel 12, which requires ^8.2. Check yours with php -v, and get a newer build from windows.php.net if needed. Dusk 8.8.0 and the php-webdriver package it installs also need the zip extension. In php.ini I enabled curl, openssl, mbstring, fileinfo, zip, pdo_sqlite, sqlite3 and intl. I ran 8.2.29 with Laravel 12.72.0, and 8.3.28, 8.4.15 and 8.5.0 with Laravel 13.42.0.
  • Google Chrome. Mine reported 157.0.8103.50 on Windows 11, and Dusk installs a ChromeDriver for it in Step 1.
  • CapSkip running on your Windows PC, and the capskip/capskip package at 1.7.0, the version I ran. The connection settings in the setup guide choose between Local mode, which answers at 127.0.0.1 for that PC only, and Server mode, which answers on your network address or public IP.
  • A page that carries a standard Turnstile widget: a div with the class cf-turnstile and a data-sitekey attribute, which the Cloudflare docs describe as the markup that makes the widget add an invisible cf-turnstile-response field to the form.

Everything below ran against two mocks, one standing in for CapSkip and one for the Cloudflare siteverify check, and the page under test was a small Laravel app of mine with a sign-up form. The real CapSkip app on this PC received no task, so I measured no real Turnstile solve time, and no real Cloudflare page has accepted a token from this code. I also did not test whether a real Cloudflare widget in automated Chrome leaves an injected value in place.

Step 1: install Dusk, ChromeDriver and the CapSkip settings

The Laravel Dusk docs ask for Chrome and the laravel/dusk package, then the dusk:install command, which creates tests/Browser and downloads a ChromeDriver. CapSkip goes in as a development dependency too, because only the tests call it.

# PowerShell, in the root folder of your Laravel project
composer require --dev laravel/dusk capskip/capskip
php artisan dusk:install

On my Windows PHP builds, whose php.ini named no certificate file, the first dusk:install created the scaffold and then failed with cURL error 60, an SSL certificate problem, while fetching the ChromeDriver download list. The same error came from dusk:chrome-driver with the detect option. Run php -i and look for the Loaded Configuration File line to find your php.ini, download cacert.pem from curl.se/docs/caextract.html, save it as C:\php\cacert.pem and add these two lines to that php.ini. Then the detect option fetched ChromeDriver 157.0.8103.78 for my Chrome 157.

; In php.ini, with cacert.pem saved at this path
curl.cainfo="C:\php\cacert.pem"
openssl.cafile="C:\php\cacert.pem"
# Install the ChromeDriver that matches the Chrome on this PC
php artisan dusk:chrome-driver --detect

The generated tests/DuskTestCase.php starts ChromeDriver for you on port 9515 and runs Chrome headless unless the environment variable DUSK_HEADLESS_DISABLED is set, as the installed source shows. On 8.3.28 and 8.5.0 I ran the tests below with a visible window and again headless, and both modes passed.

Tell Dusk where CapSkip is

Dusk reads a file named .env.dusk.local when you start it from the local environment. The docs say it backs up your .env, renames the Dusk file to .env for the run and restores the original afterwards. In my runs the .env checksum was identical before and after, and no .env.backup file was left behind.

That swap only reaches the process that runs your tests. Dusk drives a browser at APP_URL and does not start your app: the CI examples in the Dusk docs run php artisan serve next to it. So serve it yourself, and make APP_URL match the address the browser will visit. With no CapSkip settings in .env, the mock still received every task, so the test process read .env.dusk.local.

# PowerShell, in the project folder: copy .env, then change and add lines
Copy-Item .env .env.dusk.local
(Get-Content .env.dusk.local) -replace '^APP_URL=.*', 'APP_URL=http://127.0.0.1:8000' | Set-Content .env.dusk.local
Add-Content .env.dusk.local "`nCAPSKIP_HOST=127.0.0.1`nCAPSKIP_PORT=8080"

Step 2: a helper that solves the widget

I picked Turnstile over reCAPTCHA and MTCaptcha for three reasons. The widget is a plain div, so Dusk can read data-sitekey with attribute() and no JavaScript has to be parsed. The SDK call turnstile(sitekey, url, options) takes the two values the test already has. And Cloudflare documents both the field name, cf-turnstile-response, and the check that a server runs on it.

Create the folder tests/Concerns, which Laravel does not have yet, and save this trait there as SolvesTurnstile.php. Four details in it came out of the runs.

<?php

namespace Tests\Concerns;

use CapSkip\CapSkip;
use Laravel\Dusk\Browser;

trait SolvesTurnstile
{
    /**
     * Ask CapSkip for a token for the Turnstile widget on the current page
     * and write it into the widget's hidden field.
     */
    protected function solveTurnstile(Browser $browser, string $widget = '.cf-turnstile'): string
    {
        $solver = new CapSkip([
            'host' => env('CAPSKIP_HOST', '127.0.0.1'),
            'port' => (int) env('CAPSKIP_PORT', 8080),
            'apiKey' => env('CAPSKIP_API_KEY', 'capskip'),
        ]);

        // The widget adds its hidden field after the page loads, and the field
        // is never displayed, so wait for presence and not for visibility.
        $browser->waitUntilPresent('input[name="cf-turnstile-response"]');

        $options = ['timeout' => 60];  // seconds the SDK may wait for the token
        foreach (['action' => 'data-action', 'data' => 'data-cdata'] as $option => $attribute) {
            $value = $browser->attribute($widget, $attribute);
            if ($value !== null) {
                $options[$option] = $value;
            }
        }

        $result = $solver->turnstile(
            $browser->attribute($widget, 'data-sitekey'),
            $browser->driver->getCurrentURL(),
            $options
        );

        $browser->script(sprintf(
            'document.querySelector(%s).value = %s;',
            json_encode('input[name="cf-turnstile-response"]'),
            json_encode($result['code'])
        ));

        return $result['code'];
    }
}

First, wait with waitUntilPresent. The Dusk source says waitFor waits until an element is displayed, and a hidden input never is: in my run waitFor with an explicit limit of 3 seconds ended after 3.19 seconds with a WebDriver TimeoutException reading Waited 3 seconds for selector, and with the default limit it ended after 5.17 seconds with Waited 5 seconds for selector, while the field was already in the page. Second, the page address goes to CapSkip as the current URL of the browser. My mock site compares the hostname behind the token with its own, and a task sent for localhost against a site served at 127.0.0.1 was refused with a hostname message. That rule is mine, but the siteverify docs list hostname in the response, so a real site can make the same comparison.

Third, the helper forwards data-action and data-cdata as the action and data options, which the CapSkip API docs name as the sources of those two values. My widget carried data-action, and the mock logged action=signup on the task. Fourth, a missing sitekey fails early: attribute() returns null for an absent attribute, and the SDK answered with a TypeError saying argument 1 must be of type string. A page that creates its widget with turnstile.render may have no data-sitekey at all, and then the sitekey has to come from that call.

The token travels through json_encode twice over, so no character in it can break the JavaScript string. The shorter form is the value() method of Dusk, which writes the same way, through executeScript. I confirmed that it also fills a hidden input.

The result can also carry a userAgent, which the Turnstile PHP guide treats as required on challenge pages. Chrome under Dusk reports its own string, Chrome/157.0.0.0 here, and my mock reported a Chrome/140 string. If your site compares them, add this to the helper.

// Optional, before the return line of solveTurnstile(): later requests of this
// browser then carry the User-Agent string that CapSkip reported for the token.
if (isset($result['userAgent'])) {
    $browser->driver->executeCustomCommand('/session/:sessionId/goog/cdp/execute', 'POST', [
        'cmd' => 'Network.setUserAgentOverride',
        'params' => ['userAgent' => $result['userAgent']],
    ]);
}

On 8.3.28 against the mock, a page visited after that call showed the server and navigator.userAgent the Chrome/140 string. I did not test whether a real site cares about the match.

Step 3: write the test and run it

The page under test

The tests expect this contract: a route at /signup, a text input named username, a div with the class cf-turnstile, a data-sitekey and a data-action, a button labelled Create account, a redirect to /welcome that shows Welcome and the name, and the validation message The cf-turnstile-response field is required. when the field is empty. If you have no such page, replace routes/web.php and save the view as resources/views/signup.blade.php.

<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::get('/signup', fn () => view('signup'));

Route::post('/signup', function (Request $request) {
    $data = $request->validate([
        'username' => ['required', 'string', 'max:40'],
        'cf-turnstile-response' => ['required', 'string'],
    ]);

    return redirect('/welcome')->with('name', $data['username']);
});

Route::get('/welcome', fn (Request $request) =>
    '<h1>Welcome, ' . e($request->session()->get('name', 'stranger')) . '</h1>');
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>Sign up</title></head>
<body>
@foreach ($errors->all() as $message)
    <p class="error">{{ $message }}</p>
@endforeach
<form method="POST" action="/signup">
    @csrf
    <input type="text" name="username">
    <div class="cf-turnstile" data-sitekey="0x4AAAAAAAEXAMPLE" data-action="signup"></div>
    <button type="submit">Create account</button>
</form>
<script>
    // Stand-in for the Cloudflare script: the real widget adds this hidden
    // input to the form a moment after the page has loaded.
    setTimeout(function () {
        var field = document.createElement('input');
        field.type = 'hidden';
        field.name = 'cf-turnstile-response';
        document.querySelector('.cf-turnstile').appendChild(field);
    }, 400);
</script>
</body>
</html>

This sample only checks that the field is present. The result table below came from a fuller version of the page that also sent the token to my mock siteverify.

The first test is the pass. The second shows that the page really refuses a form without a token. Save both in tests/Browser/SignupCaptchaTest.php.

<?php

namespace Tests\Browser;

use Laravel\Dusk\Browser;
use Tests\Concerns\SolvesTurnstile;
use Tests\DuskTestCase;

class SignupCaptchaTest extends DuskTestCase
{
    use SolvesTurnstile;

    public function test_signup_passes_the_captcha(): void
    {
        $this->browse(function (Browser $browser) {
            $browser->visit('/signup')
                ->type('username', 'alice');

            $this->solveTurnstile($browser);

            $browser->press('Create account')
                ->waitForText('Welcome, alice')
                ->assertPathIs('/welcome');
        });
    }

    public function test_signup_without_a_token_is_refused(): void
    {
        $this->browse(function (Browser $browser) {
            $browser->visit('/signup')
                ->type('username', 'bob')
                ->waitUntilPresent('input[name="cf-turnstile-response"]')
                ->press('Create account')
                ->waitForText('The cf-turnstile-response field is required.')
                ->assertPathIs('/signup');
        });
    }
}

If your page differs, change the path, the field names, the button label and the texts. Then use two PowerShell prompts, one for the app and one for the tests.

# First prompt, in the project folder: serve the app
php artisan serve --host=127.0.0.1 --port=8000

# Second prompt, same folder: run the browser tests
php artisan dusk

# Optional, to watch Chrome: set this PowerShell variable before the line above
$env:DUSK_HEADLESS_DISABLED = 'true'

My mock site validates the field as required, posts it to the mock siteverify, accepts a token once and compares the hostname. Those are my rules, not those of Cloudflare. Every row below used the mock CapSkip, Chrome 157.0.8103.50 and ChromeDriver 157.0.8103.78 on Windows 11, with the Duration line of the PHPUnit output.

PHPLaravelChrome windowResult
8.2.2912.72.0visible2 passed, 5.20 seconds
8.3.2813.42.0visible, then headless2 passed, 4.96 and 5.68 seconds
8.4.1513.42.0visible2 passed, 5.27 seconds
8.5.013.42.0visible, then headless2 passed, 4.46 and 4.33 seconds

The time limit and the SDK timeout

The PHP setting max_execution_time does not stop a Dusk run. I set it to 30 in php.ini, and a probe inside the test read 0 on 8.2.29, 8.3.28, 8.4.15 and 8.5.0, because php artisan dusk starts PHPUnit on the command line, where the limit is off.

For Turnstile the PHP SDK 1.7.0 waits up to its defaultTimeout, 120 seconds, unless the call passes a timeout option, as the trait does with 60. The SDK reads the result at 0, 0.25, 0.75, 1.75 and 3.75 seconds after the submit, then at 7.75 and every 5 seconds, and it checks the deadline only when the next read is due. So the call ends later than the number you gave it.

Mock CapSkip, never finishesMeasured
timeout 5, inside a Dusk test, PHP 8.3.28TimeoutException after 7.83 seconds
timeout 60, plain command line, PHP 8.3.28TimeoutException after 62.97 seconds, last read at 57.93
Token ready after 45 seconds, timeout 60, Dusk testToken returned after 48.31 seconds, form accepted

The last row also shows that the browser can wait: Chrome and ChromeDriver sat idle for those 48 seconds and the next command worked. I did not test anything longer. The Cloudflare docs give a Turnstile token five minutes of life and one use, so ask for it after the page has loaded and fill it in at once. A token I sent a second time was refused by my mock with timeout-or-duplicate, the code the docs name for that case.

Common errors

In this table, seen means I produced the error myself against the mocks.

ErrorCauseFix
cURL error 60 during dusk:installphp.ini names no CA bundle (seen)Set curl.cainfo in php.ini, then run dusk:chrome-driver with the detect option
NetworkException: Failed to connect to 127.0.0.1 port 8080 after about 2000 ms: Couldn’t connect to serverNothing listens at the CapSkip host and port. It failed after about 2 seconds (seen, 2.02 s on a closed port)Start CapSkip, and compare CAPSKIP_HOST and CAPSKIP_PORT in .env.dusk.local with its connection settings
TimeoutException: timeout 60 exceededNo token before the deadline (seen)Check the CapSkip monitor, then raise the timeout option
ApiException with ERROR_CAPTCHA_UNSOLVABLEThe mock answered it; the solve failed (seen)Run the test again, since a new task is a new attempt
ValidationException: Unsupported parameters for TurnstileAn option Turnstile does not take, such as invisible (seen)Remove that option from the turnstile call
TypeError: Argument #1 ($sitekey) must be of type stringThe widget has no data-sitekey attribute (seen)Read the sitekey from the page’s turnstile.render call
Waited 5 seconds for selectorwaitFor with its default limit on the hidden field (seen)Use waitUntilPresent
The cf-turnstile-response field is required.The form was posted with the field empty (seen, the second test)Fill the field before you press the button
Captcha refused: timeout-or-duplicateThe mock saw the token a second time (seen)Ask for a new token for every form submission
Deprecated: curl_close()The full text is Function curl_close() is deprecated since 8.5, as it has no effect since PHP 8.0. The SDK still calls it. Laravel sends it to the log channel in LOG_DEPRECATIONS_CHANNEL, null in the skeleton, so nothing printed. With the channel set to single I counted two entries for one solve (seen)Leave it, or filter it, until the SDK drops the call

Running CapSkip on another machine

A Dusk suite does not have to run on the PC that hosts CapSkip. Switch CapSkip to Server mode, put that machine’s address in CAPSKIP_HOST in .env.dusk.local, and nothing else in the helper changes. If API Key Validation is on, add CAPSKIP_API_KEY with your key, which the helper passes as apiKey. CapSkip opens its port to every address when Server mode starts, so to keep it to the machines you expect, add a Windows Firewall block rule for the others. The solver still runs on your own Windows machine.

FAQ

Should my own app’s tests solve its CAPTCHA at all?

Usually not. When the app is yours, turn the check off or fake the verification in the Dusk environment. This guide is for pages whose verification you cannot change, such as a staging site run by someone else.

Does the same helper work for reCAPTCHA or MTCaptcha?

The SDK has recaptcha() and mtcaptcha() with the same shape, but the field names differ and I ran only Turnstile. The Symfony Panther guide shows reCAPTCHA in a PHP browser script.

Should I use Pest browser testing instead of Dusk?

The Dusk docs now recommend Pest 4 for browser tests in new projects. The CapSkip call is plain PHP, so the same idea should carry over, but I ran only Dusk.

Is this for queue jobs too?

No. A job has its own worker limits, which the Laravel queue guide covers. A Dusk test is a command line process, so the limit that applied here was the SDK timeout.

A Laravel Dusk CAPTCHA step comes down to four moves: wait for the hidden field, read the sitekey, ask for a token just before you need it and write it with script(). For a captcha solver with no fee per token, CapSkip runs on your own PC, so a failed run costs only another test run. The Cloudflare Turnstile solver page covers the widget itself, the Turnstile PHP guide shows the same call without a browser, and the PHP CAPTCHA solver page lists the other types.