Skip to content
Draft
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
6 changes: 6 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -95,3 +95,9 @@ ANYSTACK_TRIAL_POLICY_ID=
FILAMENT_USERS=

BIFROST_API_KEY=your-secure-api-key-here

TURNSTILE_SITE_KEY=
TURNSTILE_SECRET_KEY=
# Optional comma-separated allow list of hostnames the challenge may be solved on.
# Leave empty to rely on the widget's domain list in the Cloudflare dashboard.
TURNSTILE_HOSTNAMES=
9 changes: 2 additions & 7 deletions app/Http/Controllers/Auth/CustomerAuthController.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use App\Enums\TeamUserStatus;
use App\Http\Controllers\Controller;
use App\Http\Requests\Auth\LoginRequest;
use App\Http\Requests\Auth\RegisterRequest;
use App\Models\Plugin;
use App\Models\TeamUser;
use App\Models\User;
Expand Down Expand Up @@ -32,14 +33,8 @@ public function showRegister(): View
return view('auth.register');
}

public function register(Request $request): RedirectResponse
public function register(RegisterRequest $request): RedirectResponse
{
$request->validate([
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email:rfc,dns', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);

$user = User::create([
'name' => $request->name,
'email' => $request->email,
Expand Down
42 changes: 42 additions & 0 deletions app/Http/Requests/Auth/RegisterRequest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<?php

namespace App\Http\Requests\Auth;

use App\Rules\Turnstile;
use Illuminate\Foundation\Http\FormRequest;

class RegisterRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}

/**
* @return array<string, array<int, mixed>>
*/
public function rules(): array
{
$rules = [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email:rfc,dns', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
];

if (config('services.turnstile.secret_key')) {
$rules['cf-turnstile-response'] = ['required', new Turnstile('register')];
}

return $rules;
}

/**
* @return array<string, string>
*/
public function messages(): array
{
return [
'cf-turnstile-response.required' => 'Please complete the security check.',
];
}
}
76 changes: 70 additions & 6 deletions app/Rules/Turnstile.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,29 @@

use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Translation\PotentiallyTranslatedString;

class Turnstile implements ValidationRule
{
private const SITEVERIFY_URL = 'https://challenges.cloudflare.com/turnstile/v0/siteverify';

private const TIMEOUT_SECONDS = 10;

/**
* Cloudflare documents tokens as being up to 2048 characters, so anything
* longer is junk that isn't worth a siteverify round trip.
*/
private const MAX_TOKEN_LENGTH = 2048;

/**
* @param string|null $expectedAction The `data-action` the widget was rendered with. When
* given, a token minted by a different form is rejected.
*/
public function __construct(private ?string $expectedAction = null) {}

/**
* Run the validation rule.
*
Expand All @@ -22,20 +40,66 @@ public function validate(string $attribute, mixed $value, Closure $fail): void
return;
}

if (empty($value)) {
if (! is_string($value) || $value === '') {
$fail('Please complete the security check.');

return;
}

$response = Http::asForm()->post('https://challenges.cloudflare.com/turnstile/v0/siteverify', [
'secret' => $secretKey,
'response' => $value,
'remoteip' => request()->ip(),
]);
if (strlen($value) > self::MAX_TOKEN_LENGTH) {
$fail('Security verification failed. Please try again.');

return;
}

try {
$response = Http::asForm()
->timeout(self::TIMEOUT_SECONDS)
->post(self::SITEVERIFY_URL, [
'secret' => $secretKey,
'response' => $value,
'remoteip' => request()->ip(),
]);
} catch (ConnectionException $e) {
Log::warning('Turnstile siteverify request failed.', ['exception' => $e->getMessage()]);

$fail('Security verification failed. Please try again.');

return;
}

if (! $response->successful() || ! $response->json('success')) {
$fail('Security verification failed. Please try again.');

return;
}

if ($this->expectedAction !== null && $response->json('action') !== $this->expectedAction) {
$fail('Security verification failed. Please try again.');

return;
}

if (! $this->hostnameIsAllowed($response->json('hostname'))) {
$fail('Security verification failed. Please try again.');
}
}

/**
* Hostname pinning is opt-in: with no allow list configured we defer to the
* domain list already enforced on the widget by Cloudflare.
*/
private function hostnameIsAllowed(mixed $hostname): bool
{
$allowed = array_filter(array_map(
trim(...),
explode(',', (string) config('services.turnstile.hostnames'))
));

if ($allowed === []) {
return true;
}

return is_string($hostname) && in_array($hostname, $allowed, true);
}
}
1 change: 1 addition & 0 deletions config/services.php
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@
'turnstile' => [
'site_key' => env('TURNSTILE_SITE_KEY'),
'secret_key' => env('TURNSTILE_SECRET_KEY'),
'hostnames' => env('TURNSTILE_HOSTNAMES'),
],

'satis' => [
Expand Down
2 changes: 2 additions & 0 deletions resources/views/auth/register.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@
<flux:label>Confirm Password</flux:label>
<flux:input name="password_confirmation" type="password" autocomplete="new-password" required viewable placeholder="Confirm your password" />
</flux:field>

<x-turnstile action="register" />
</div>

<flux:button type="submit" variant="primary" class="w-full">Create account</flux:button>
Expand Down
2 changes: 2 additions & 0 deletions resources/views/components/layouts/auth.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@
</style>
@livewireStyles
@vite('resources/css/app.css')

@stack('head')
</head>
<body
x-cloak
Expand Down
21 changes: 21 additions & 0 deletions resources/views/components/turnstile.blade.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
@props(['action' => null, 'size' => 'flexible'])

@if (config('services.turnstile.site_key'))
@once
@push('head')
<script src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer></script>
@endpush
@endonce

<div>
<div
{{ $attributes->class('cf-turnstile') }}
data-sitekey="{{ config('services.turnstile.site_key') }}"
@if ($action) data-action="{{ $action }}" @endif
data-theme="auto"
data-size="{{ $size }}"
></div>

<flux:error name="cf-turnstile-response" />
</div>
@endif
Loading