Skip to content
Permalink

Comparing changes

Choose two branches to see what’s changed or to start a new pull request. If you need to, you can also or learn more about diff comparisons.

Open a pull request

Create a new pull request by comparing changes across two branches. If you need to, you can also . Learn more about diff comparisons here.
base repository: Scyllaly/hcaptcha
Failed to load repositories. Confirm that selected base ref is valid, then try again.
Loading
base: 4.4.5
Choose a base ref
...
head repository: Scyllaly/hcaptcha
Failed to load repositories. Confirm that selected head ref is valid, then try again.
Loading
compare: master
Choose a head ref

Commits on Mar 17, 2023

  1. Update README.md

    Scyllaly authored Mar 17, 2023
    Copy the full SHA
    20990c6 View commit details

Commits on Mar 18, 2023

  1. Update README.md

    Scyllaly authored Mar 18, 2023
    Copy the full SHA
    7450181 View commit details
  2. Update README.md

    Scyllaly authored Mar 18, 2023
    Copy the full SHA
    fb1e7d9 View commit details
  3. Update README.md

    Scyllaly authored Mar 18, 2023
    Copy the full SHA
    a0033c3 View commit details
  4. Update README.md

    Scyllaly authored Mar 18, 2023
    Copy the full SHA
    403b2fb View commit details
  5. Update README.md

    Scyllaly authored Mar 18, 2023
    Copy the full SHA
    abf2384 View commit details
  6. Update README.md

    Scyllaly authored Mar 18, 2023
    Copy the full SHA
    3ab3014 View commit details
  7. Update README.md

    Scyllaly authored Mar 18, 2023
    Copy the full SHA
    120a668 View commit details
  8. Update README.md

    Scyllaly authored Mar 18, 2023
    Copy the full SHA
    90e1142 View commit details
  9. Update README.md

    Scyllaly authored Mar 18, 2023
    Copy the full SHA
    57dad0a View commit details
  10. Update README.md

    Scyllaly authored Mar 18, 2023
    Copy the full SHA
    24d45f9 View commit details
  11. Update README.md

    Scyllaly authored Mar 18, 2023
    Copy the full SHA
    212d92e View commit details
  12. Update README.md

    Scyllaly authored Mar 18, 2023
    Copy the full SHA
    6ab1b91 View commit details
  13. Update README.md

    Scyllaly authored Mar 18, 2023
    Copy the full SHA
    c80f7ba View commit details
  14. Update README.md

    Scyllaly authored Mar 18, 2023
    Copy the full SHA
    8cb0662 View commit details
  15. Copy the full SHA
    39eabf3 View commit details
  16. Create checkmarx-one.yml

    Scyllaly authored Mar 18, 2023
    Copy the full SHA
    1d22f39 View commit details
  17. Create checkmarx.yml

    Scyllaly authored Mar 18, 2023
    Copy the full SHA
    f1c933c View commit details
  18. Create codeql.yml

    Scyllaly authored Mar 18, 2023
    Copy the full SHA
    c954493 View commit details
  19. Update README.md

    Scyllaly authored Mar 18, 2023
    Copy the full SHA
    eb06bf6 View commit details

Commits on Apr 22, 2023

  1. Update LICENSE

    Scyllaly authored Apr 22, 2023
    Copy the full SHA
    da3b829 View commit details
  2. Copy the full SHA
    4e062ed View commit details

Commits on Aug 10, 2023

  1. Add score verification

    phuclh committed Aug 10, 2023
    Copy the full SHA
    43055b3 View commit details
  2. Copy the full SHA
    83a8885 View commit details

Commits on Aug 18, 2023

  1. Merge pull request #15 from phuclh/master

    Add score verification
    Scyllaly authored Aug 18, 2023
    Copy the full SHA
    4f37913 View commit details

Commits on Sep 22, 2023

  1. Copy the full SHA
    6edc929 View commit details
  2. Copy the full SHA
    8c3e07b View commit details

Commits on Oct 21, 2023

  1. Merge pull request #17 from phuclh/master

    Fix the namespace of RuntimeException
    Scyllaly authored Oct 21, 2023
    Copy the full SHA
    741e0c0 View commit details

Commits on Feb 27, 2024

  1. Copy the full SHA
    624f03a View commit details

Commits on Mar 4, 2024

  1. store lastScore

    usamamuneerchaudhary committed Mar 4, 2024
    Copy the full SHA
    71202f2 View commit details
  2. Copy the full SHA
    4bd3d12 View commit details
  3. fix

    usamamuneerchaudhary committed Mar 4, 2024
    Copy the full SHA
    e18bea5 View commit details

Commits on Jun 8, 2024

  1. Merge pull request #19 from usamamuneerchaudhary/master

    Get the score if available
    Scyllaly authored Jun 8, 2024
    Copy the full SHA
    ed31f8a View commit details
  2. Merge pull request #18 from laravel-shift/l11-compatibility

    Laravel 11.x Compatibility
    Scyllaly authored Jun 8, 2024
    Copy the full SHA
    5b7d5ec View commit details

Commits on Aug 30, 2024

  1. Create environment variable to enable or disable hCaptcha for use in …

    …development mode (true/false)
    rubekx committed Aug 30, 2024
    Copy the full SHA
    84a29dd View commit details
  2. feat: Add environment variable to enable/disable hCaptcha for develop…

    …ment mode
    
    - Added an environment variable to toggle hCaptcha usage in development mode (true/false).
    - Implemented basic and conditional validation approaches for hCaptcha.
    rubekx committed Aug 30, 2024
    Copy the full SHA
    31f4f53 View commit details

Commits on Aug 31, 2024

  1. Merge pull request #23 from rubekx/feature/hcaptcha-enable-disable

    Feature/hcaptcha enable disable
    Scyllaly authored Aug 31, 2024
    Copy the full SHA
    f5d3d66 View commit details

Commits on Feb 16, 2025

  1. Copy the full SHA
    de9ff2f View commit details

Commits on Feb 22, 2025

  1. Merge pull request #25 from laravel-shift/l12-compatibility

    Laravel 12.x Compatibility
    Scyllaly authored Feb 22, 2025
    Copy the full SHA
    b9b362a View commit details
Showing with 117 additions and 21 deletions.
  1. +1 −1 LICENSE
  2. +49 −15 README.md
  3. +1 −1 composer.json
  4. +59 −2 src/HCaptcha.php
  5. +4 −2 src/HCaptchaServiceProvider.php
  6. +3 −0 src/config/config.php
2 changes: 1 addition & 1 deletion LICENSE
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
The MIT License (MIT)

Copyright (c) 2020 SSRPanel
Copyright (c) 2023 Scyllaly

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
64 changes: 49 additions & 15 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
# hCaptcha
Project based on [laravel-reCAPTCHA](https://github.com/Dylanchouxd/laravel-reCAPTCHA) development.
# Introduction
The hCaptcha is a human-computer verification solution that replaces Google reCaptcha. It has high performance, high availability and high recognition, especially suitable for regions with poor network quality, such as East Asia, Middle East, etc. Many well-known companies are using the hCaptcha solution.


The package is one of the recommended package on [the official developer guide of HCaptcha](https://github.com/hCaptcha/hcaptcha-integrations-list#laravel). No malicious code, ensuring the security of your development supply chain.

- Purchase a [VPS](https://bwh88.net/aff.php?aff=20075) or [Akamai VPS](https://www.linode.com/lp/refer/?r=2d4a0088743a2a06e3405514d486b8966c51a439) for developing and deploying applications.

## Installation

@@ -13,34 +18,37 @@ composer require scyllaly/hcaptcha

In `app/config/app.php` add the following :

1- The ServiceProvider to the providers array :
Step 1: The ServiceProvider to the providers array :

```php
Scyllaly\HCaptcha\HCaptchaServiceProvider::class,
```

2- The class alias to the aliases array :
Step 2: The class alias to the aliases array :

```php
'HCaptcha' => Scyllaly\HCaptcha\Facades\HCaptcha::class,
```

3- Publish the config file
Step 3: Publish the config file

```ssh
```Shell
php artisan vendor:publish --provider="Scyllaly\HCaptcha\HCaptchaServiceProvider"
```

### Configuration

Add `HCAPTCHA_SECRET` and `HCAPTCHA_SITEKEY` in **.env** file :
Add `HCAPTCHA_SECRET`, `HCAPTCHA_SITEKEY` and `HCAPTCHA_ENABLED` in **.env** file :

```
HCAPTCHA_SECRET=secret-key
HCAPTCHA_SITEKEY=site-key
HCAPTCHA_ENABLED=true
```

(You can obtain them from [here](https://docs.hcaptcha.com/api#getapikey))
(You can obtain them from [Official Developer Guide](https://docs.hcaptcha.com/api#getapikey))

- Tips: If you do not have an account, please [sign up](https://hCaptcha.com/?r=d315c350eeee) it first.

### Usage

@@ -58,7 +66,7 @@ With [language support](https://docs.hcaptcha.com/configuration) or [onloadCallb
{!! HCaptcha::renderJs('fr', true, 'hcaptchaCallback') !!}
```

#### Display hCAPTCHA
#### Display hCaptcha

Default widget :

@@ -72,7 +80,7 @@ With [custom attributes](https://docs.hcaptcha.com/configuration#themes) (theme,
{!! HCaptcha::display(['data-theme' => 'dark']) !!}
```

Invisible hCAPTCHA using a [submit button](https://docs.hcaptcha.com/configuration#themes):
Invisible hCaptcha using a [submit button](https://docs.hcaptcha.com/configuration#themes):

```php
{!! HCaptcha::displaySubmit('my-form-id', 'submit now!', ['data-theme' => 'dark']) !!}
@@ -82,15 +90,41 @@ callback submit the form on a successful captcha verification.

#### Validation

Add `'h-captcha-response' => 'required|HCaptcha'` to rules array :
There are two ways to apply HCaptcha validation to your form:

#### 1. Basic Approach

This method always applies the HCaptcha validation rule.

```php
$validate = Validator::make(Input::all(), [
'h-captcha-response' => 'required|HCaptcha'
'h-captcha-response' => 'required|HCaptcha'
]);

```

In this approach, the `h-captcha-response` field is required and validated using the `HCaptcha` rule without any conditions.

#### 2. Conditional Approach

This method applies the HCaptcha validation rule only if the `HCAPTCHA_ENABLED` environment variable is set to `true`.

```php
$isHcaptchaEnabled = env('HCAPTCHA_ENABLED');
$rules = [
// Other validation rules...
];

if ($isHcaptchaEnabled) {
$rules['h-captcha-response'] = 'required|HCaptcha';
}

$request->validate($rules);

```

In this approach, the `h-captcha-response` field will be required and validated using the `HCaptcha` rule only when `HCAPTCHA_ENABLED` is set to `true`. This adds flexibility to your validation logic, allowing you to enable or disable HCaptcha validation as needed.

##### Custom Validation Message

Add the following values to the `custom` array in the `validation` language file :
@@ -99,7 +133,7 @@ Add the following values to the `custom` array in the `validation` language file
'custom' => [
'h-captcha-response' => [
'required' => 'Please verify that you are not a robot.',
'captcha' => 'Captcha error! try again later or contact site admin.',
'h_captcha' => 'Captcha error! try again later or contact site admin.',
],
],
```
@@ -145,8 +179,8 @@ HCaptcha::shouldReceive('verifyResponse')
// POST request, with request body including `h-captcha-response`
$response = $this->json('POST', '/register', [
'h-captcha-response' => '1',
'name' => 'John',
'email' => 'john@example.com',
'name' => 'Scyllaly',
'email' => 'Scyllaly@example.com',
'password' => '123456',
'password_confirmation' => '123456',
]);
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
@@ -15,7 +15,7 @@
],
"require": {
"php": ">=5.5.5",
"illuminate/support": "5.*|6.*|7.*|8.*|^9.0|10.*"
"illuminate/support": "5.*|6.*|7.*|8.*|^9.0|10.*|^11.0|^12.0"
},
"require-dev": {
"phpunit/phpunit": "~4.8|^9.5.10|^10.0"
61 changes: 59 additions & 2 deletions src/HCaptcha.php
Original file line number Diff line number Diff line change
@@ -36,18 +36,33 @@ class HCaptcha
*/
protected $verifiedResponses = [];

/**
* @var null
* lastScore
*/
protected $lastScore = null;

/**
* Whether to use hCaptcha or not.
*
* @var bool
*/
protected $enabled;

/**
* HCaptcha.
*
* @param string $secret
* @param string $sitekey
* @param array $options
* @param bool $enabled
*/
public function __construct($secret, $sitekey, $options = [])
public function __construct($secret, $sitekey, $options = [], $enabled = true)
{
$this->secret = $secret;
$this->sitekey = $sitekey;
$this->http = new Client($options);
$this->enabled = $enabled;
}

/**
@@ -59,6 +74,10 @@ public function __construct($secret, $sitekey, $options = [])
*/
public function display($attributes = [])
{
if (!$this->enabled) {
return '';
}

$attributes = $this->prepareAttributes($attributes);
return '<div' . $this->buildAttributes($attributes) . '></div>';
}
@@ -82,6 +101,10 @@ public function displayWidget($attributes = [])
*/
public function displaySubmit($formIdentifier, $text = 'submit', $attributes = [])
{
if (!$this->enabled) {
return sprintf('<button%s><span>%s</span></button>', $this->buildAttributes($attributes), $text);
}

$javascript = '';
if (!isset($attributes['data-callback'])) {
$functionName = 'onSubmit' . str_replace(['-', '=', '\'', '"', '<', '>', '`'], '', $formIdentifier);
@@ -111,6 +134,10 @@ public function displaySubmit($formIdentifier, $text = 'submit', $attributes = [
*/
public function renderJs($lang = null, $callback = false, $onLoadClass = 'onloadCallBack')
{
if (!$this->enabled) {
return '';
}

return '<script src="' . $this->getJsLink($lang, $callback, $onLoadClass) . '" async defer></script>' . "\n";
}

@@ -124,11 +151,15 @@ public function renderJs($lang = null, $callback = false, $onLoadClass = 'onload
*/
public function verifyResponse($response, $clientIp = null)
{
if (!$this->enabled) {
return true; // Always true if hCaptcha is disabled
}

if (empty($response)) {
return false;
}

// Return true if response already verfied before.
// Return true if response already verified before.
if (in_array($response, $this->verifiedResponses)) {
return true;
}
@@ -140,6 +171,18 @@ public function verifyResponse($response, $clientIp = null)
]);

if (isset($verifyResponse['success']) && $verifyResponse['success'] === true) {
$this->lastScore = isset($verifyResponse['score']) ? $verifyResponse['score'] : null;
// Check score if it's enabled.
$isScoreVerificationEnabled = config('HCaptcha.score_verification_enabled', false);

if ($isScoreVerificationEnabled && !array_key_exists('score', $verifyResponse)) {
throw new \RuntimeException('Score Verification is an exclusive Enterprise feature! Moreover, make sure you are sending the remoteip in your request payload!');
}

if ($isScoreVerificationEnabled && $verifyResponse['score'] > config('HCaptcha.score_threshold', 0.7)) {
return false;
}

// A response can only be verified once from hCaptcha, so we need to
// cache it to make it work in case we want to verify it multiple times.
$this->verifiedResponses[] = $response;
@@ -175,6 +218,10 @@ public function verifyRequest(Request $request)
*/
public function getJsLink($lang = null, $callback = false, $onLoadClass = 'onloadCallBack')
{
if (!$this->enabled) {
return '';
}

$client_api = static::CLIENT_API;
$params = [];

@@ -184,6 +231,16 @@ public function getJsLink($lang = null, $callback = false, $onLoadClass = 'onloa
return $client_api . '?' . http_build_query($params);
}

/**
* Get the score from the last successful hCaptcha verification.
*
* @return float|null The score of the last verification or null if not available.
*/
public function getScoreFromLastVerification()
{
return $this->lastScore;
}

/**
* @param $params
* @param $onLoadClass
6 changes: 4 additions & 2 deletions src/HCaptchaServiceProvider.php
Original file line number Diff line number Diff line change
@@ -58,13 +58,15 @@ public function register()
return new HCaptcha(
$hCaptcha['secret'],
$hCaptcha['sitekey'],
$hCaptcha['options']
$hCaptcha['options'],
$hCaptcha['enabled'],
);
} else {
return new HCaptcha(
$app['config']['HCaptcha.secret'],
$app['config']['HCaptcha.sitekey'],
$app['config']['HCaptcha.options']
$app['config']['HCaptcha.options'],
$app['config']['HCaptcha.enabled'],
);
}
});
3 changes: 3 additions & 0 deletions src/config/config.php
Original file line number Diff line number Diff line change
@@ -3,8 +3,11 @@
return [
'secret' => env('HCAPTCHA_SECRET'),
'sitekey' => env('HCAPTCHA_SITEKEY'),
'enabled' => env('HCAPTCHA_ENABLED', true), //Enable or disable hCaptcha for development environments
'server-get-config' => false,
'options' => [
'timeout' => 30,
],
'score_verification_enabled' => false, // This is an exclusive Enterprise feature
'score_threshold' => 0.7 // Any requests above this score will be considered as spam
];