Skip to content

Commit

Permalink
feat: Create initial honeypot plugin
Browse files Browse the repository at this point in the history
  • Loading branch information
johnnynotsolucky committed Nov 27, 2024
0 parents commit 3bba358
Show file tree
Hide file tree
Showing 14 changed files with 448 additions and 0 deletions.
21 changes: 21 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# EditorConfig is awesome: https://EditorConfig.org

# Top-most EditorConfig file
root = true

# All files
[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
indent_style = tab
indent_size = 4

# Markdown files
[*.md]
trim_trailing_whitespace = false

[*.{yaml,yml}]
indent_size = 2
indent_style = space
52 changes: 52 additions & 0 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
name: CI

on:
workflow_dispatch:
push:
branches:
- main
pull_request:

jobs:
ecs:
name: ECS Check
runs-on: ubuntu-latest
env:
DEFAULT_COMPOSER_FLAGS: "--no-interaction --no-ansi --no-progress"
steps:
- uses: actions/checkout@v4
- uses: shivammathur/setup-php@v2
with:
php-version: 8.2
- run: composer install --prefer-dist --no-progress
- name: Run ecs check
run: |
vendor/bin/ecs --memory-limit=1G --no-progress-bar
rector:
name: Rector dry-run
runs-on: ubuntu-latest
env:
DEFAULT_COMPOSER_FLAGS: "--no-interaction --no-ansi --no-progress"
steps:
- uses: actions/checkout@v4
- uses: shivammathur/setup-php@v2
with:
php-version: 8.2
- run: composer install --prefer-dist --no-progress
- name: Run rector --dry-run
run: |
vendor/bin/rector --memory-limit=1G --no-progress-bar --dry-run
phpstan:
name: PHPStan
runs-on: ubuntu-latest
env:
DEFAULT_COMPOSER_FLAGS: "--no-interaction --no-ansi --no-progress"
steps:
- uses: actions/checkout@v4
- uses: shivammathur/setup-php@v2
with:
php-version: 8.2
- run: composer install --prefer-dist --no-progress
- name: Run phpstan
run: |
vendor/bin/phpstan --memory-limit=1G
8 changes: 8 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
*.DS_Store
*.idea/*
*.log
*Thumbs.db
.env
composer.lock
/node_modules
/vendor
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Release Notes for honeypot

## 1.0.0-beta.1

- Initial beta release
40 changes: 40 additions & 0 deletions LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
Copyright © Foster Commerce

Permission is hereby granted to any person obtaining a copy of this software
(the “Software”) to use, copy, modify, merge, publish and/or distribute copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

1. **Don’t plagiarize.** The above copyright notice and this license shall be
included in all copies or substantial portions of the Software.

2. **Don’t use the same license on more than one project.** Each licensed copy
of the Software shall be actively installed in no more than one production
environment at a time.

3. **Don’t mess with the licensing features.** Software features related to
licensing shall not be altered or circumvented in any way, including (but
not limited to) license validation, payment prompts, feature restrictions,
and update eligibility.

4. **Pay up.** Payment shall be made immediately upon receipt of any notice,
prompt, reminder, or other message indicating that a payment is owed.

5. **Follow the law.** All use of the Software shall not violate any applicable
law or regulation, nor infringe the rights of any other person or entity.

Failure to comply with the foregoing conditions will automatically and
immediately result in termination of the permission granted hereby. This
license does not include any right to receive updates to the Software or
technical support. Licensees bear all risk related to the quality and
performance of the Software and any modifications made or obtained to it,
including liability for actual and consequential harm, such as loss or
corruption of data, and any necessary service, repair, or correction.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER
LIABILITY, INCLUDING SPECIAL, INCIDENTAL AND CONSEQUENTIAL DAMAGES, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
35 changes: 35 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# Craft Honeypot

```html

<form>
{{ honeypot() }}
</form>
```

## Requirements

This plugin requires Craft CMS 4.12.0 or later, and PHP 8.0.2 or later.

## Installation

You can install this plugin from the Plugin Store or with Composer.

#### From the Plugin Store

Go to the Plugin Store in your project’s Control Panel and search for “honeypot”. Then press “Install”.

#### With Composer

Open your terminal and run the following commands:

```bash
# go to the project directory
cd /path/to/my-project.test

# tell Composer to load the plugin
composer require fostercommerce/craft-honeypot

# tell Craft to install the plugin
./craft plugin/install honeypot
```
50 changes: 50 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
{
"name": "fostercommerce/craft-honeypot",
"type": "craft-plugin",
"license": "proprietary",
"version": "1.0.0-beta.1",
"support": {
"email": "support@fostercommerce.com",
"issues": "https://github.com/fostercommerce/craft-honeypot/issues?state=open",
"source": "https://github.com/fostercommerce/craft-honeypot",
"docs": "https://github.com/fostercommerce/craft-honeypot",
"rss": "https://github.com/fostercommerce/craft-honeypot/releases.atom"
},
"require": {
"php": ">=8.0.2",
"craftcms/cms": "^4.0.0|^5.0.0"
},
"require-dev": {
"craftcms/phpstan": "dev-main",
"craftcms/rector": "dev-main",
"fostercommerce/ecs": "dev-main",
"fostercommerce/phpstan": "dev-main",
"fostercommerce/rector": "dev-main"
},
"autoload": {
"psr-4": {
"fostercommerce\\honeypot\\": "src/"
}
},
"extra": {
"handle": "honeypot",
"name": "honeypot",
"developer": "Foster Commerce",
"documentationUrl": "https://github.com/fostercommerce/craft-honeypot"
},
"config": {
"sort-packages": true,
"allow-plugins": {
"yiisoft/yii2-composer": true,
"craftcms/plugin-installer": true
}
},
"scripts": {
"phpstan": "phpstan --memory-limit=1G",
"ecs:check": "ecs check --ansi --memory-limit=1G",
"ecs:fix": "ecs check --ansi --fix --memory-limit=1G",
"rector:fix": "rector process --config rector.php",
"rector:dry-run": "rector process --dry-run --config rector.php"
}
}

11 changes: 11 additions & 0 deletions ecs.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?php

declare(strict_types=1);

use fostercommerce\ecs\ECSConfig;

return ECSConfig::configure()
->withPaths([
__DIR__ . '/src',
__FILE__,
]);
7 changes: 7 additions & 0 deletions phpstan.neon
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
includes:
- vendor/craftcms/phpstan/phpstan.neon

parameters:
paths:
- src
level: 9
13 changes: 13 additions & 0 deletions rector.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

declare(strict_types = 1);

use fostercommerce\rector\RectorConfig;
use fostercommerce\rector\SetList;

return RectorConfig::configure()
->withPaths([
__DIR__ . '/src',
__FILE__,
])
->withSets([SetList::CRAFT_CMS_40]);
96 changes: 96 additions & 0 deletions src/Plugin.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
<?php

namespace fostercommerce\honeypot;

use Craft;
use craft\base\Model;
use craft\base\Plugin as BasePlugin;
use craft\helpers\App;
use craft\web\Application;
use craft\web\Request;
use fostercommerce\honeypot\models\Settings;
use fostercommerce\honeypot\web\twig\Honeypot;
use yii\base\Event;

/**
* @method static Plugin getInstance()
* @method Settings getSettings()
*/
class Plugin extends BasePlugin
{
/**
* @var string[]
*/
private const LOG_LEVELS = ['debug', 'info', 'error', 'warning'];

public bool $hasCpSettings = true;

public function init(): void
{
parent::init();

$this->attachEventHandlers();

Craft::$app->view->registerTwigExtension(new Honeypot());
}

protected function createSettingsModel(): ?Model
{
return Craft::createObject(Settings::class);
}

protected function settingsHtml(): ?string
{
return Craft::$app->view->renderTemplate('honeypot/_settings.twig', [
'plugin' => $this,
'settings' => $this->getSettings(),
]);
}

private function attachEventHandlers(): void
{
Event::on(
Application::class,
Application::EVENT_BEFORE_REQUEST,
function (Event $event): void {
/** @var Request $request */
$request = Craft::$app->getRequest();
if ($request->getIsPost() || $request->getIsPut()) {
$settings = $this->getSettings();
$honeypotValue = $request->getBodyParam($settings->honeypotFieldName);
if ($honeypotValue === null) {
// A bot simply has to remove the input field altogether to bypass this check.
return;
}

if (! empty($honeypotValue)) {
if ($settings->logSpamSubmissions !== false) {
$userIp = $request->getUserIP();
$userAgent = $request->getUserAgent();
$action = implode('/', $request->getActionSegments());
$message = sprintf('Spam submission blocked. IP: %s, Action: %s, User Agent: %s', $userIp, $action, $userAgent);

if (in_array($settings->logSpamSubmissions, self::LOG_LEVELS, true)) {
Craft::{$settings->logSpamSubmissions}($message);
} else {
Craft::debug($message);
}
}

if ($settings->spamDetectedResponse !== false || App::devMode()) {
ob_start();

if ($settings->spamDetectedResponse !== false) {
echo $settings->spamDetectedResponse;
} else {
echo 'Spam submission detected';
}
}

exit(0);
}
}
}
);
}
}
31 changes: 31 additions & 0 deletions src/config.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

return [
/**
* Whether the honeypot is enabled
*/
'enabled' => true,

/**
* The name to give the hidden input field.
*
* This should be unique so that it does not conflict with any of your form inputs.
*/
'honeypotFieldName' => 'my_password',

/**
* `false` to disable responses on non-dev environments.
*
* Set to a string value to enable a response on non-dev environment.s
*/
'spamDetectedResponse' => 'Spam submission recorded',

/**
* Whether to log every spam submission.
*
* `false` to disable logs.
*
* A string value of log-level to enable and generate a log with the desired level.
*/
'logSpamSubmissions' => 'debug',
];
Loading

0 comments on commit 3bba358

Please sign in to comment.