Implement reCaptcha v3 (#3655)

* Implement score based reCaptcha v3

* Apply suggestions from code review
This commit is contained in:
Yağızhan Burak Yakar authored and GitHub committed 2026-05-29 22:41:21 +03:00
1 parent 4375cf357d
commit 22832ee02e
10 files changed
+197 -48

No files matched your search

+1
View File
@@ -27,6 +27,7 @@ class Admin extends \Api_Abstract
'captcha_provider' => $config['captcha_provider'] ?? 'recaptcha_v2',
'captcha_recaptcha_publickey' => $config['captcha_recaptcha_publickey'] ?? null,
'captcha_recaptcha_privatekey' => $config['captcha_recaptcha_privatekey'] ?? null,
'captcha_recaptcha_v3_threshold' => $config['captcha_recaptcha_v3_threshold'] ?? 0.5,
'turnstile_site_key' => $config['turnstile_site_key'] ?? null,
'turnstile_secret_key' => $config['turnstile_secret_key'] ?? null,
'hcaptcha_site_key' => $config['hcaptcha_site_key'] ?? null,
+1
View File
@@ -26,6 +26,7 @@ class Guest extends \Api_Abstract
'enabled' => $config['captcha_enabled'] ?? false,
'version' => $config['captcha_version'] ?? null,
'captcha_provider' => $config['captcha_provider'] ?? 'recaptcha_v2',
'recaptcha_v3_threshold' => $config['captcha_recaptcha_v3_threshold'] ?? 0.5,
'turnstile_site_key' => $config['turnstile_site_key'] ?? null,
'hcaptcha_site_key' => $config['hcaptcha_site_key'] ?? null,
];
+21 -1
View File
@@ -154,7 +154,7 @@ class Service implements InjectionAwareInterface
if (isset($config['captcha_enabled']) && $config['captcha_enabled']) {
$provider = $config['captcha_provider'] ?? 'recaptcha_v2';
if ($provider === 'recaptcha_v2') {
if ($provider === 'recaptcha_v2' || $provider === 'recaptcha_v3') {
if (!isset($config['captcha_recaptcha_privatekey']) || $config['captcha_recaptcha_privatekey'] == '') {
throw new \FOSSBilling\InformationException("To use reCAPTCHA you must get an API key from <a href='https://www.google.com/recaptcha/admin/create'>here</a>");
}
@@ -176,6 +176,26 @@ class Service implements InjectionAwareInterface
if (!isset($content['success']) || $content['success'] !== true) {
throw new \FOSSBilling\InformationException('reCAPTCHA verification failed.');
}
if ($provider === 'recaptcha_v3') {
$threshold = (float) ($config['captcha_recaptcha_v3_threshold'] ?? 0.5);
if (!is_finite($threshold)) {
$threshold = 0.5;
}
$threshold = min(1.0, max(0.0, $threshold));
$score = isset($content['score']) ? (float) $content['score'] : 0.0;
if ($score < $threshold) {
throw new \FOSSBilling\InformationException('reCAPTCHA verification failed.');
}
$expectedAction = 'fossbilling_submit';
$action = $params['g-recaptcha-action'] ?? $expectedAction;
if ($action !== $expectedAction || ($content['action'] ?? null) !== $expectedAction) {
throw new \FOSSBilling\InformationException('reCAPTCHA verification failed.');
}
}
} elseif ($provider === 'turnstile') {
if (empty($config['turnstile_secret_key'])) {
throw new \FOSSBilling\InformationException('Cloudflare Turnstile secret key is not configured.');
@@ -78,6 +78,7 @@
<label class="form-label" for="provider-select">{{ 'CAPTCHA Provider'|trans }}</label>
<select name="captcha_provider" class="form-select" id="provider-select">
<option value="recaptcha_v2" {% if not params.captcha_provider or params.captcha_provider == 'recaptcha_v2' %}selected{% endif %}>{{ 'Google reCAPTCHA v2'|trans }}</option>
<option value="recaptcha_v3" {% if params.captcha_provider == 'recaptcha_v3' %}selected{% endif %}>{{ 'Google reCAPTCHA v3'|trans }}</option>
<option value="turnstile" {% if params.captcha_provider == 'turnstile' %}selected{% endif %}>{{ 'Cloudflare Turnstile'|trans }}</option>
<option value="hcaptcha" {% if params.captcha_provider == 'hcaptcha' %}selected{% endif %}>{{ 'hCaptcha'|trans }}</option>
</select>
@@ -87,13 +88,18 @@
<div id="recaptcha_v2_settings" class="mt-3">
<div class="row g-3">
<div class="col-lg-6">
<label class="form-label" for="captcha_recaptcha_publickey">{{ 'reCAPTCHA Public Key'|trans }}</label>
<label class="form-label" for="captcha_recaptcha_publickey">{{ 'reCAPTCHA Site Key'|trans }}</label>
<input class="form-control" type="text" id="captcha_recaptcha_publickey" name="captcha_recaptcha_publickey" value="{{ params.captcha_recaptcha_publickey }}">
</div>
<div class="col-lg-6">
<label class="form-label" for="captcha_recaptcha_privatekey">{{ 'reCAPTCHA Secret Key'|trans }}</label>
<input class="form-control" type="text" id="captcha_recaptcha_privatekey" name="captcha_recaptcha_privatekey" value="{{ params.captcha_recaptcha_privatekey }}">
</div>
<div class="col-lg-6" id="recaptcha_v3_threshold_wrap">
<label class="form-label" for="captcha_recaptcha_v3_threshold">{{ 'reCAPTCHA v3 Minimum Score'|trans }}</label>
<input class="form-control" type="number" id="captcha_recaptcha_v3_threshold" name="captcha_recaptcha_v3_threshold" value="{{ params.captcha_recaptcha_v3_threshold|default(0.5) }}" min="0" max="1" step="0.1">
<small class="form-hint">{{ 'Google returns a score from 0.0 to 1.0. Higher thresholds are stricter.'|trans }}</small>
</div>
</div>
</div>
@@ -198,7 +204,8 @@ document.addEventListener('DOMContentLoaded', function () {
function toggleProviderSettings() {
const selectedProvider = document.getElementById('provider-select').value;
document.getElementById('recaptcha_v2_settings').style.display = selectedProvider === 'recaptcha_v2' ? 'block' : 'none';
document.getElementById('recaptcha_v2_settings').style.display = selectedProvider === 'recaptcha_v2' || selectedProvider === 'recaptcha_v3' ? 'block' : 'none';
document.getElementById('recaptcha_v3_threshold_wrap').style.display = selectedProvider === 'recaptcha_v3' ? 'block' : 'none';
document.getElementById('turnstile_settings').style.display = selectedProvider === 'turnstile' ? 'block' : 'none';
document.getElementById('hcaptcha_settings').style.display = selectedProvider === 'hcaptcha' ? 'block' : 'none';
}
@@ -12,6 +12,50 @@
<script src='https://www.google.com/recaptcha/api.js' async defer loading="lazy"></script>
<div class="g-recaptcha" data-sitekey="{{ rc.publickey }}"></div>
{% endif %}
{% elseif provider == 'recaptcha_v3' %}
{% if rc.publickey %}
<script src="https://www.google.com/recaptcha/api.js?render={{ rc.publickey }}" async defer loading="lazy"></script>
<input type="hidden" name="g-recaptcha-response" value="">
<input type="hidden" name="g-recaptcha-action" value="fossbilling_submit">
<script>
(function () {
const script = document.currentScript;
const form = script.closest('form');
if (!form) {
return;
}
form.addEventListener('submit', function (event) {
if (form.dataset.recaptchaV3Verified === 'true') {
form.dataset.recaptchaV3Verified = '';
return;
}
event.preventDefault();
event.stopImmediatePropagation();
if (!window.grecaptcha) {
form.dataset.recaptchaV3Verified = 'true';
form.requestSubmit();
return;
}
const tokenField = form.querySelector('input[name="g-recaptcha-response"]');
const actionField = form.querySelector('input[name="g-recaptcha-action"]');
window.grecaptcha.ready(function () {
window.grecaptcha.execute('{{ rc.publickey|e('js') }}', { action: actionField.value }).then(function (token) {
tokenField.value = token;
form.dataset.recaptchaV3Verified = 'true';
form.requestSubmit();
}).catch(function () {
form.dataset.recaptchaV3Verified = 'true';
form.requestSubmit();
});
});
}, true);
}());
</script>
{% endif %}
{% elseif provider == 'hcaptcha' %}
{% if rc.hcaptcha_site_key %}
<script src='https://js.hcaptcha.com/1/api.js' async defer loading="lazy"></script>
@@ -19,4 +63,4 @@
{% endif %}
{% endif %}
{% endif %}
{% endif %}
{% endif %}
@@ -68,45 +68,7 @@
<textarea id="embed-contact-message" class="embed-textarea" name="message" cols="5" rows="5" required="required">{{ request.message }}</textarea>
</div>
{% if guest.extension_is_on({ "mod": "antispam" }) %}
{% set rc = guest.antispam_recaptcha %}
{% if rc.enabled %}
{% if rc.version == 2 %}
<script src='https://www.google.com/recaptcha/api.js' async defer></script>
<div class="g-recaptcha" data-sitekey="{{ rc.publickey }}"></div>
{% else %}
{% set server = "https://www.google.com/recaptcha/api" %}
<script>
var RecaptchaOptions = {
theme : 'custom',
custom_theme_widget: 'recaptcha_widget'
};
</script>
<div id="recaptcha_widget" style="display:none">
<div id="recaptcha_image"></div>
<div class="recaptcha_only_if_incorrect_sol" style="color:red">{{ 'Incorrect please try again'|trans }}</div>
<div class="embed-field">
<label class="embed-label" for="recaptcha_response_field">{{ 'Enter the words above'|trans }}</label>
<input class="embed-input" type="text" id="recaptcha_response_field" name="recaptcha_response_field" />
<a class="embed-button" href="javascript:Recaptcha.reload()">
<span class="dark-icon i-reload"></span>
{{ 'Reload challenge'|trans }}
</a>
</div>
</div>
<script src="{{ server }}/challenge?k={{ rc.publickey }}"></script>
<noscript>
<iframe src="{{ server }}/noscript?k={{ rc.publickey }}" height="300" width="500" frameborder="0"></iframe><br/>
<textarea name="recaptcha_challenge_field" rows="3" cols="40"></textarea>
<input type="hidden" name="recaptcha_response_field" value="manual_challenge"/>
</noscript>
{% endif %}
{% endif %}
{% endif %}
{{ include('mod_antispam_recaptcha.html.twig') }}
<button class="embed-button" type="submit">{{ 'Send'|trans }}</button>
</div>
@@ -161,6 +161,50 @@
<div class="g-recaptcha" data-sitekey="{{ config.publickey }}"></div>
</div>
{% endif %}
{% elseif provider == 'recaptcha_v3' %}
{% if config.publickey %}
<script src="https://www.google.com/recaptcha/api.js?render={{ config.publickey }}" async defer></script>
<input type="hidden" name="g-recaptcha-response" value="">
<input type="hidden" name="g-recaptcha-action" value="fossbilling_submit">
<script>
(function () {
const script = document.currentScript;
const form = script.closest('form');
if (!form) {
return;
}
form.addEventListener('submit', function (event) {
if (form.dataset.recaptchaV3Verified === 'true') {
form.dataset.recaptchaV3Verified = '';
return;
}
event.preventDefault();
event.stopImmediatePropagation();
if (!window.grecaptcha) {
form.dataset.recaptchaV3Verified = 'true';
form.requestSubmit();
return;
}
const tokenField = form.querySelector('input[name="g-recaptcha-response"]');
const actionField = form.querySelector('input[name="g-recaptcha-action"]');
window.grecaptcha.ready(function () {
window.grecaptcha.execute('{{ config.publickey|e('js') }}', { action: actionField.value }).then(function (token) {
tokenField.value = token;
form.dataset.recaptchaV3Verified = 'true';
form.requestSubmit();
}).catch(function () {
form.dataset.recaptchaV3Verified = 'true';
form.requestSubmit();
});
});
}, true);
}());
</script>
{% endif %}
{% elseif provider == 'hcaptcha' %}
{% if config.hcaptcha_site_key %}
<div class="mb-3">
@@ -27,6 +27,50 @@
<div class="g-recaptcha" data-sitekey="{{ config.publickey }}"></div>
</div>
{% endif %}
{% elseif provider == 'recaptcha_v3' %}
{% if config.publickey %}
<script src="https://www.google.com/recaptcha/api.js?render={{ config.publickey }}" async defer></script>
<input type="hidden" name="g-recaptcha-response" value="">
<input type="hidden" name="g-recaptcha-action" value="fossbilling_submit">
<script>
(function () {
const script = document.currentScript;
const form = script.closest('form');
if (!form) {
return;
}
form.addEventListener('submit', function (event) {
if (form.dataset.recaptchaV3Verified === 'true') {
form.dataset.recaptchaV3Verified = '';
return;
}
event.preventDefault();
event.stopImmediatePropagation();
if (!window.grecaptcha) {
form.dataset.recaptchaV3Verified = 'true';
form.requestSubmit();
return;
}
const tokenField = form.querySelector('input[name="g-recaptcha-response"]');
const actionField = form.querySelector('input[name="g-recaptcha-action"]');
window.grecaptcha.ready(function () {
window.grecaptcha.execute('{{ config.publickey|e('js') }}', { action: actionField.value }).then(function (token) {
tokenField.value = token;
form.dataset.recaptchaV3Verified = 'true';
form.requestSubmit();
}).catch(function () {
form.dataset.recaptchaV3Verified = 'true';
form.requestSubmit();
});
});
}, true);
}());
</script>
{% endif %}
{% elseif provider == 'hcaptcha' %}
{% if config.hcaptcha_site_key %}
<div class="mb-3">
@@ -30,6 +30,7 @@ final class GuestTest extends \BBTestCase
'enabled' => true,
'version' => null,
'captcha_provider' => 'recaptcha_v2',
'recaptcha_v3_threshold' => 0.5,
'turnstile_site_key' => null,
'hcaptcha_site_key' => null,
],
@@ -43,6 +44,7 @@ final class GuestTest extends \BBTestCase
'enabled' => true,
'version' => null,
'captcha_provider' => 'recaptcha_v2',
'recaptcha_v3_threshold' => 0.5,
'turnstile_site_key' => null,
'hcaptcha_site_key' => null,
],
@@ -58,6 +60,7 @@ final class GuestTest extends \BBTestCase
'enabled' => false,
'version' => 2,
'captcha_provider' => 'recaptcha_v2',
'recaptcha_v3_threshold' => 0.5,
'turnstile_site_key' => null,
'hcaptcha_site_key' => null,
],
@@ -71,6 +74,7 @@ final class GuestTest extends \BBTestCase
'enabled' => false,
'version' => null,
'captcha_provider' => 'recaptcha_v2',
'recaptcha_v3_threshold' => 0.5,
'turnstile_site_key' => null,
'hcaptcha_site_key' => null,
],
@@ -86,6 +90,7 @@ final class GuestTest extends \BBTestCase
'enabled' => true,
'version' => null,
'captcha_provider' => 'turnstile',
'recaptcha_v3_threshold' => 0.5,
'turnstile_site_key' => 'abc',
'hcaptcha_site_key' => null,
],
@@ -101,10 +106,28 @@ final class GuestTest extends \BBTestCase
'enabled' => true,
'version' => null,
'captcha_provider' => 'hcaptcha',
'recaptcha_v3_threshold' => 0.5,
'turnstile_site_key' => null,
'hcaptcha_site_key' => 'abc',
],
],
[
[
'captcha_enabled' => true,
'captcha_provider' => 'recaptcha_v3',
'captcha_recaptcha_publickey' => 'abc',
'captcha_recaptcha_v3_threshold' => '0.7',
],
[
'publickey' => 'abc',
'enabled' => true,
'version' => null,
'captcha_provider' => 'recaptcha_v3',
'recaptcha_v3_threshold' => '0.7',
'turnstile_site_key' => null,
'hcaptcha_site_key' => null,
],
],
];
}
+8 -5
View File
@@ -35,6 +35,7 @@ final class GuestTest extends TestCase
'captcha_provider' => 'hcaptcha',
'hcaptcha_site_key' => 'site-key',
'hcaptcha_secret_key' => 'secret-key',
'captcha_recaptcha_v3_threshold' => '0.7',
'check_temp_emails' => false,
'sfs' => false,
]);
@@ -49,6 +50,7 @@ final class GuestTest extends TestCase
$this->assertSame('hcaptcha', $config['captcha_provider']);
$this->assertSame('site-key', $config['hcaptcha_site_key']);
$this->assertSame('secret-key', $config['hcaptcha_secret_key']);
$this->assertSame('0.7', $config['captcha_recaptcha_v3_threshold']);
$this->assertFalse((bool) $config['check_temp_emails']);
$this->assertFalse((bool) $config['sfs']);
}
@@ -60,8 +62,9 @@ final class GuestTest extends TestCase
$result = Request::makeRequest('admin/extension/config_save', [
'ext' => 'mod_antispam',
'captcha_enabled' => true,
'captcha_provider' => 'turnstile',
'turnstile_site_key' => 'turnstile-site-key',
'captcha_provider' => 'recaptcha_v3',
'captcha_recaptcha_publickey' => 'recaptcha-site-key',
'captcha_recaptcha_v3_threshold' => '0.8',
]);
$this->assertTrue($result->wasSuccessful(), $result->generatePHPUnitMessage());
@@ -71,9 +74,9 @@ final class GuestTest extends TestCase
$config = $result->getResult();
$this->assertIsArray($config);
$this->assertTrue((bool) $config['enabled']);
$this->assertSame('turnstile', $config['captcha_provider']);
$this->assertSame('turnstile-site-key', $config['turnstile_site_key']);
$this->assertNull($config['publickey']);
$this->assertSame('recaptcha_v3', $config['captcha_provider']);
$this->assertSame('recaptcha-site-key', $config['publickey']);
$this->assertSame('0.8', $config['recaptcha_v3_threshold']);
}
private function captureOriginalConfig(): void